code
stringlengths
1
2.08M
language
stringclasses
1 value
/*! HTML5 Shiv vpre3.5 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed */ ;(function(window, document) { /** Preset options */ var options = window.html5 || {}; /** Used to skip problem elements */ var reSkip = /^<|^(?:button|form|map|select|textarea|object|iframe|option|optgroup)$/i; /** Not all elements can be cloned in IE (this list can be shortend) **/ var saveClones = /^<|^(?:a|b|button|code|div|fieldset|form|h1|h2|h3|h4|h5|h6|i|iframe|img|input|label|li|link|ol|option|p|param|q|script|select|span|strong|style|table|tbody|td|textarea|tfoot|th|thead|tr|ul)$/i; /** Detect whether the browser supports default html5 styles */ var supportsHtml5Styles; /** Detect whether the browser supports unknown elements */ var supportsUnknownElements; (function() { var a = document.createElement('a'); a.innerHTML = '<xyz></xyz>'; //if the hidden property is implemented we can assume, that the browser supports HTML5 Styles | this fails in Chrome 8 supportsHtml5Styles = ('hidden' in a); //if we are part of Modernizr, we do an additional test to solve the Chrome 8 fail if(supportsHtml5Styles && typeof injectElementWithStyles == 'function'){ injectElementWithStyles('#modernizr{}', function(node){ node.hidden = true; supportsHtml5Styles = (window.getComputedStyle ? getComputedStyle(node, null) : node.currentStyle).display == 'none'; }); } supportsUnknownElements = a.childNodes.length == 1 || (function() { // assign a false positive if unable to shiv try { (document.createElement)('a'); } catch(e) { return true; } var frag = document.createDocumentFragment(); return ( typeof frag.cloneNode == 'undefined' || typeof frag.createDocumentFragment == 'undefined' || typeof frag.createElement == 'undefined' ); }()); }()); /*--------------------------------------------------------------------------*/ /** * Creates a style sheet with the given CSS text and adds it to the document. * @private * @param {Document} ownerDocument The document. * @param {String} cssText The CSS text. * @returns {StyleSheet} The style element. */ function addStyleSheet(ownerDocument, cssText) { var p = ownerDocument.createElement('p'), parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; p.innerHTML = 'x<style>' + cssText + '</style>'; return parent.insertBefore(p.lastChild, parent.firstChild); } /** * Returns the value of `html5.elements` as an array. * @private * @returns {Array} An array of shived element node names. */ function getElements() { var elements = html5.elements; return typeof elements == 'string' ? elements.split(' ') : elements; } /** * Shivs the `createElement` and `createDocumentFragment` methods of the document. * @private * @param {Document|DocumentFragment} ownerDocument The document. */ function shivMethods(ownerDocument) { var cache = {}, docCreateElement = ownerDocument.createElement, docCreateFragment = ownerDocument.createDocumentFragment, frag = docCreateFragment(); ownerDocument.createElement = function(nodeName) { //abort shiv if(!html5.shivMethods){ return docCreateElement(nodeName); } var node; if(cache[nodeName]){ node = cache[nodeName].cloneNode(); } else if(saveClones.test(nodeName)){ node = (cache[nodeName] = docCreateElement(nodeName)).cloneNode(); } else { node = docCreateElement(nodeName); } // Avoid adding some elements to fragments in IE < 9 because // * Attributes like `name` or `type` cannot be set/changed once an element // is inserted into a document/fragment // * Link elements with `src` attributes that are inaccessible, as with // a 403 response, will cause the tab/window to crash // * Script elements appended to fragments will execute when their `src` // or `text` property is set return node.canHaveChildren && !reSkip.test(nodeName) ? frag.appendChild(node) : node; }; ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' + 'var n=f.cloneNode(),c=n.createElement;' + 'h.shivMethods&&(' + // unroll the `createElement` calls getElements().join().replace(/\w+/g, function(nodeName) { docCreateElement(nodeName); frag.createElement(nodeName); return 'c("' + nodeName + '")'; }) + ');return n}' )(html5, frag); } /*--------------------------------------------------------------------------*/ /** * Shivs the given document. * @memberOf html5 * @param {Document} ownerDocument The document to shiv. * @returns {Document} The shived document. */ function shivDocument(ownerDocument) { var shived; if (ownerDocument.documentShived) { return ownerDocument; } if (html5.shivCSS && !supportsHtml5Styles) { shived = !!addStyleSheet(ownerDocument, // corrects block display not defined in IE6/7/8/9 'article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}' + // corrects audio display not defined in IE6/7/8/9 'audio{display:none}' + // corrects canvas and video display not defined in IE6/7/8/9 'canvas,video{display:inline-block;*display:inline;*zoom:1}' + // corrects 'hidden' attribute and audio[controls] display not present in IE7/8/9 '[hidden]{display:none}audio[controls]{display:inline-block;*display:inline;*zoom:1}' + // adds styling not present in IE6/7/8/9 'mark{background:#FF0;color:#000}' ); } if (!supportsUnknownElements) { shived = !shivMethods(ownerDocument); } if (shived) { ownerDocument.documentShived = shived; } return ownerDocument; } /*--------------------------------------------------------------------------*/ /** * The `html5` object is exposed so that more elements can be shived and * existing shiving can be detected on iframes. * @type Object * @example * * // options can be changed before the script is included * html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false }; */ var html5 = { /** * An array or space separated string of node names of the elements to shiv. * @memberOf html5 * @type Array|String */ 'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video', /** * A flag to indicate that the HTML5 style sheet should be inserted. * @memberOf html5 * @type Boolean */ 'shivCSS': !(options.shivCSS === false), /** * A flag to indicate that the document's `createElement` and `createDocumentFragment` * methods should be overwritten. * @memberOf html5 * @type Boolean */ 'shivMethods': !(options.shivMethods === false), /** * A string to describe the type of `html5` object ("default" or "default print"). * @memberOf html5 * @type String */ 'type': 'default', // shivs the document according to the specified `html5` object options 'shivDocument': shivDocument }; /*--------------------------------------------------------------------------*/ // expose html5 window.html5 = html5; // shiv the document shivDocument(document); /*------------------------------- Print Shiv -------------------------------*/ /** Used to filter media types */ var reMedia = /^$|\b(?:all|print)\b/; /** Used to namespace printable elements */ var shivNamespace = 'html5shiv'; /** Detect whether the browser supports shivable style sheets */ var supportsShivableSheets = !supportsUnknownElements && (function() { // assign a false negative if unable to shiv var docEl = document.documentElement; return !( typeof document.namespaces == 'undefined' || typeof document.parentWindow == 'undefined' || typeof docEl.applyElement == 'undefined' || typeof docEl.removeNode == 'undefined' || typeof window.attachEvent == 'undefined' ); }()); /*--------------------------------------------------------------------------*/ /** * Wraps all HTML5 elements in the given document with printable elements. * (eg. the "header" element is wrapped with the "html5shiv:header" element) * @private * @param {Document} ownerDocument The document. * @returns {Array} An array wrappers added. */ function addWrappers(ownerDocument) { var node, nodes = ownerDocument.getElementsByTagName('*'), index = nodes.length, reElements = RegExp('^(?:' + getElements().join('|') + ')$', 'i'), result = []; while (index--) { node = nodes[index]; if (reElements.test(node.nodeName)) { result.push(node.applyElement(createWrapper(node))); } } return result; } /** * Creates a printable wrapper for the given element. * @private * @param {Element} element The element. * @returns {Element} The wrapper. */ function createWrapper(element) { var node, nodes = element.attributes, index = nodes.length, wrapper = element.ownerDocument.createElement(shivNamespace + ':' + element.nodeName); // copy element attributes to the wrapper while (index--) { node = nodes[index]; node.specified && wrapper.setAttribute(node.nodeName, node.nodeValue); } // copy element styles to the wrapper wrapper.style.cssText = element.style.cssText; return wrapper; } /** * Shivs the given CSS text. * (eg. header{} becomes html5shiv\:header{}) * @private * @param {String} cssText The CSS text to shiv. * @returns {String} The shived CSS text. */ function shivCssText(cssText) { var pair, parts = cssText.split('{'), index = parts.length, reElements = RegExp('(^|[\\s,>+~])(' + getElements().join('|') + ')(?=[[\\s,>+~#.:]|$)', 'gi'), replacement = '$1' + shivNamespace + '\\:$2'; while (index--) { pair = parts[index] = parts[index].split('}'); pair[pair.length - 1] = pair[pair.length - 1].replace(reElements, replacement); parts[index] = pair.join('}'); } return parts.join('{'); } /** * Removes the given wrappers, leaving the original elements. * @private * @params {Array} wrappers An array of printable wrappers. */ function removeWrappers(wrappers) { var index = wrappers.length; while (index--) { wrappers[index].removeNode(); } } /*--------------------------------------------------------------------------*/ /** * Shivs the given document for print. * @memberOf html5 * @param {Document} ownerDocument The document to shiv. * @returns {Document} The shived document. */ function shivPrint(ownerDocument) { var shivedSheet, wrappers, namespaces = ownerDocument.namespaces, ownerWindow = ownerDocument.parentWindow; if (!supportsShivableSheets || ownerDocument.printShived) { return ownerDocument; } if (typeof namespaces[shivNamespace] == 'undefined') { namespaces.add(shivNamespace); } ownerWindow.attachEvent('onbeforeprint', function() { var imports, length, sheet, collection = ownerDocument.styleSheets, cssText = [], index = collection.length, sheets = Array(index); // convert styleSheets collection to an array while (index--) { sheets[index] = collection[index]; } // concat all style sheet CSS text while ((sheet = sheets.pop())) { // IE does not enforce a same origin policy for external style sheets... // but has trouble with some dynamically created stylesheets if (!sheet.disabled && reMedia.test(sheet.media)) { try { imports = sheet.imports; length = imports.length; } catch(er){ length = 0; } for (index = 0; index < length; index++) { sheets.push(imports[index]); } try { cssText.push(sheet.cssText); } catch(er){} } } // wrap all HTML5 elements with printable elements and add the shived style sheet cssText = shivCssText(cssText.reverse().join('')); wrappers = addWrappers(ownerDocument); shivedSheet = addStyleSheet(ownerDocument, cssText); }); ownerWindow.attachEvent('onafterprint', function() { // remove wrappers, leaving the original elements, and remove the shived style sheet removeWrappers(wrappers); shivedSheet.removeNode(true); }); ownerDocument.printShived = true; return ownerDocument; } /*--------------------------------------------------------------------------*/ // expose API html5.type += ' print'; html5.shivPrint = shivPrint; // shiv for print shivPrint(document); }(this, document));
JavaScript
var langList = [ {name:'en', charset:'UTF-8'}, {name:'zh-cn', charset:'UTF-8'}, {name:'zh-tw', charset:'UTF-8'} ]; var skinList = [ {name:'default', charset:'UTF-8'}, {name:'whyGreen', charset:'UTF-8'} ];
JavaScript
var $lang={ errAlertMsg: "\u4E0D\u5408\u6CD5\u7684\u65E5\u671F\u683C\u5F0F\u6216\u8005\u65E5\u671F\u8D85\u51FA\u9650\u5B9A\u7BC4\u570D,\u9700\u8981\u64A4\u92B7\u55CE?", aWeekStr: ["\u5468","\u65E5","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"], aLongWeekStr:["\u5468","\u661F\u671F\u65E5","\u661F\u671F\u4E00","\u661F\u671F\u4E8C","\u661F\u671F\u4E09","\u661F\u671F\u56DB","\u661F\u671F\u4E94","\u661F\u671F\u516D"], aMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00","\u5341\u4E8C"], aLongMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00\u6708","\u5341\u4E8C\u6708"], clearStr: "\u6E05\u7A7A", todayStr: "\u4ECA\u5929", okStr: "\u78BA\u5B9A", updateStr: "\u78BA\u5B9A", timeStr: "\u6642\u9593", quickStr: "\u5FEB\u901F\u9078\u64C7", err_1: '\u6700\u5C0F\u65E5\u671F\u4E0D\u80FD\u5927\u65BC\u6700\u5927\u65E5\u671F!' }
JavaScript
var $lang={ errAlertMsg: "Invalid date or the date out of range,redo or not?", aWeekStr: ["wk", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], aLongWeekStr:["wk","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"], aMonStr: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], aLongMonStr: ["January","February","March","April","May","June","July","August","September","October","November","December"], clearStr: "Clear", todayStr: "Today", okStr: "OK", updateStr: "OK", timeStr: "Time", quickStr: "Quick Selection", err_1: 'MinDate Cannot be bigger than MaxDate!' }
JavaScript
var $lang={ errAlertMsg: "\u4E0D\u5408\u6CD5\u7684\u65E5\u671F\u683C\u5F0F\u6216\u8005\u65E5\u671F\u8D85\u51FA\u9650\u5B9A\u8303\u56F4,\u9700\u8981\u64A4\u9500\u5417?", aWeekStr: ["\u5468","\u65E5","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"], aLongWeekStr:["\u5468","\u661F\u671F\u65E5","\u661F\u671F\u4E00","\u661F\u671F\u4E8C","\u661F\u671F\u4E09","\u661F\u671F\u56DB","\u661F\u671F\u4E94","\u661F\u671F\u516D"], aMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00","\u5341\u4E8C"], aLongMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00\u6708","\u5341\u4E8C\u6708"], clearStr: "\u6E05\u7A7A", todayStr: "\u4ECA\u5929", okStr: "\u786E\u5B9A", updateStr: "\u786E\u5B9A", timeStr: "\u65F6\u95F4", quickStr: "\u5FEB\u901F\u9009\u62E9", err_1: '\u6700\u5C0F\u65E5\u671F\u4E0D\u80FD\u5927\u4E8E\u6700\u5927\u65E5\u671F!' }
JavaScript
/** * jQuery Validation Plugin 1.8.0 * * http://bassistance.de/jquery-plugins/jquery-plugin-validation/ * http://docs.jquery.com/Plugins/Validation * * Copyright (c) 2006 - 2011 Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function($) { $.extend($.fn, { // http://docs.jquery.com/Plugins/Validation/validate validate: function( options ) { // if nothing is selected, return nothing; can't chain anyway if (!this.length) { options && options.debug && window.console && console.warn( "nothing selected, can't validate, returning nothing" ); return; } // check if a validator for this form was already created var validator = $.data(this[0], 'validator'); if ( validator ) { return validator; } validator = new $.validator( options, this[0] ); $.data(this[0], 'validator', validator); if ( validator.settings.onsubmit ) { // allow suppresing validation by adding a cancel class to the submit button this.find("input, button").filter(".cancel").click(function() { validator.cancelSubmit = true; }); // when a submitHandler is used, capture the submitting button if (validator.settings.submitHandler) { this.find("input, button").filter(":submit").click(function() { validator.submitButton = this; }); } // validate the form on submit this.submit( function( event ) { if ( validator.settings.debug ) // prevent form submit to be able to see console output event.preventDefault(); function handle() { if ( validator.settings.submitHandler ) { if (validator.submitButton) { // insert a hidden input as a replacement for the missing submit button var hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm); } validator.settings.submitHandler.call( validator, validator.currentForm ); if (validator.submitButton) { // and clean up afterwards; thanks to no-block-scope, hidden can be referenced hidden.remove(); } return false; } return true; } // prevent submit for invalid forms or custom submit handlers if ( validator.cancelSubmit ) { validator.cancelSubmit = false; return handle(); } if ( validator.form() ) { if ( validator.pendingRequest ) { validator.formSubmitted = true; return false; } return handle(); } else { validator.focusInvalid(); return false; } }); } return validator; }, // http://docs.jquery.com/Plugins/Validation/valid valid: function() { if ( $(this[0]).is('form')) { return this.validate().form(); } else { var valid = true; var validator = $(this[0].form).validate(); this.each(function() { valid &= validator.element(this); }); return valid; } }, // attributes: space seperated list of attributes to retrieve and remove removeAttrs: function(attributes) { var result = {}, $element = this; $.each(attributes.split(/\s/), function(index, value) { result[value] = $element.attr(value); $element.removeAttr(value); }); return result; }, // http://docs.jquery.com/Plugins/Validation/rules rules: function(command, argument) { var element = this[0]; if (command) { var settings = $.data(element.form, 'validator').settings; var staticRules = settings.rules; var existingRules = $.validator.staticRules(element); switch(command) { case "add": $.extend(existingRules, $.validator.normalizeRule(argument)); staticRules[element.id] = existingRules; if (argument.messages) settings.messages[element.id] = $.extend( settings.messages[element.id], argument.messages ); break; case "remove": if (!argument) { delete staticRules[element.id]; return existingRules; } var filtered = {}; $.each(argument.split(/\s/), function(index, method) { filtered[method] = existingRules[method]; delete existingRules[method]; }); return filtered; } } var data = $.validator.normalizeRules( $.extend( {}, $.validator.metadataRules(element), $.validator.classRules(element), $.validator.attributeRules(element), $.validator.staticRules(element) ), element); // make sure required is at front if (data.required) { var param = data.required; delete data.required; data = $.extend({required: param}, data); } return data; } }); // Custom selectors $.extend($.expr[":"], { // http://docs.jquery.com/Plugins/Validation/blank blank: function(a) {return !$.trim("" + a.value);}, // http://docs.jquery.com/Plugins/Validation/filled filled: function(a) {return !!$.trim("" + a.value);}, // http://docs.jquery.com/Plugins/Validation/unchecked unchecked: function(a) {return !a.checked;} }); // constructor for validator $.validator = function( options, form ) { this.settings = $.extend( true, {}, $.validator.defaults, options ); this.currentForm = form; this.init(); }; $.validator.format = function(source, params) { if ( arguments.length == 1 ) return function() { var args = $.makeArray(arguments); args.unshift(source); return $.validator.format.apply( this, args ); }; if ( arguments.length > 2 && params.constructor != Array ) { params = $.makeArray(arguments).slice(1); } if ( params.constructor != Array ) { params = [ params ]; } $.each(params, function(i, n) { source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n); }); return source; }; $.extend($.validator, { defaults: { messages: {}, groups: {}, rules: {}, errorClass: "error", validClass: "valid", errorElement: "label", focusInvalid: true, errorContainer: $( [] ), errorLabelContainer: $( [] ), onsubmit: true, ignore: [], ignoreTitle: false, onfocusin: function(element) { this.lastActive = element; // hide error label and remove error class on focus if enabled if ( this.settings.focusCleanup && !this.blockFocusCleanup ) { this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass ); this.addWrapper(this.errorsFor(element)).hide(); } }, onfocusout: function(element) { if ( !this.checkable(element) && (element.id in this.submitted || !this.optional(element)) ) { this.element(element); } }, onkeyup: function(element) { if ( element.id in this.submitted || element == this.lastElement ) { this.element(element); } }, onclick: function(element) { // click on selects, radiobuttons and checkboxes if ( element.id in this.submitted ) this.element(element); // or option elements, check parent select in that case else if (element.parentNode.name in this.submitted) this.element(element.parentNode); }, highlight: function( element, errorClass, validClass ) { $(element).addClass(errorClass).removeClass(validClass); }, unhighlight: function( element, errorClass, validClass ) { $(element).removeClass(errorClass).addClass(validClass); } }, // http://docs.jquery.com/Plugins/Validation/Validator/setDefaults setDefaults: function(settings) { $.extend( $.validator.defaults, settings ); }, messages: { required: "This field is required.", remote: "Please fix this field.", email: "Please enter a valid email address.", url: "Please enter a valid URL.", date: "Please enter a valid date.", dateISO: "Please enter a valid date (ISO).", number: "Please enter a valid number.", digits: "Please enter only digits.", creditcard: "Please enter a valid credit card number.", equalTo: "Please enter the same value again.", accept: "Please enter a value with a valid extension.", maxlength: $.validator.format("Please enter no more than {0} characters."), minlength: $.validator.format("Please enter at least {0} characters."), rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."), range: $.validator.format("Please enter a value between {0} and {1}."), max: $.validator.format("Please enter a value less than or equal to {0}."), min: $.validator.format("Please enter a value greater than or equal to {0}.") }, autoCreateRanges: false, prototype: { init: function() { this.labelContainer = $(this.settings.errorLabelContainer); this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm); this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer ); this.submitted = {}; this.valueCache = {}; this.pendingRequest = 0; this.pending = {}; this.invalid = {}; this.reset(); var groups = (this.groups = {}); $.each(this.settings.groups, function(key, value) { $.each(value.split(/\s/), function(index, name) { groups[name] = key; }); }); var rules = this.settings.rules; $.each(rules, function(key, value) { rules[key] = $.validator.normalizeRule(value); }); function delegate(event) { var validator = $.data(this[0].form, "validator"), eventType = "on" + event.type.replace(/^validate/, ""); validator.settings[eventType] && validator.settings[eventType].call(validator, this[0] ); } $(this.currentForm) .validateDelegate(":text, :password, :file, select, textarea", "focusin focusout keyup", delegate) .validateDelegate(":radio, :checkbox, select, option", "click", delegate); if (this.settings.invalidHandler) $(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler); }, // http://docs.jquery.com/Plugins/Validation/Validator/form form: function() { this.checkForm(); $.extend(this.submitted, this.errorMap); this.invalid = $.extend({}, this.errorMap); if (!this.valid()) $(this.currentForm).triggerHandler("invalid-form", [this]); this.showErrors(); return this.valid(); }, checkForm: function() { this.prepareForm(); for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) { this.check( elements[i] ); } return this.valid(); }, // http://docs.jquery.com/Plugins/Validation/Validator/element element: function( element ) { element = this.clean( element ); this.lastElement = element; this.prepareElement( element ); this.currentElements = $(element); var result = this.check( element ); if ( result ) { delete this.invalid[element.id]; } else { this.invalid[element.id] = true; } if ( !this.numberOfInvalids() ) { // Hide error containers on last error this.toHide = this.toHide.add( this.containers ); } this.showErrors(); return result; }, // http://docs.jquery.com/Plugins/Validation/Validator/showErrors showErrors: function(errors) { if(errors) { // add items to error list and map $.extend( this.errorMap, errors ); this.errorList = []; for ( var name in errors ) { this.errorList.push({ message: errors[name], element: this.findByName(name)[0] }); } // remove items from success list this.successList = $.grep( this.successList, function(element) { return !(element.id in errors); }); } this.settings.showErrors ? this.settings.showErrors.call( this, this.errorMap, this.errorList ) : this.defaultShowErrors(); }, // http://docs.jquery.com/Plugins/Validation/Validator/resetForm resetForm: function() { if ( $.fn.resetForm ) $( this.currentForm ).resetForm(); this.submitted = {}; this.prepareForm(); this.hideErrors(); this.elements().removeClass( this.settings.errorClass ); }, numberOfInvalids: function() { return this.objectLength(this.invalid); }, objectLength: function( obj ) { var count = 0; for ( var i in obj ) count++; return count; }, hideErrors: function() { this.addWrapper( this.toHide ).hide(); }, valid: function() { return this.size() == 0; }, size: function() { return this.errorList.length; }, focusInvalid: function() { if( this.settings.focusInvalid ) { try { $(this.findLastActive() || this.errorList.length && this.errorList[0].element || []) .filter(":visible") .focus() // manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find .trigger("focusin"); } catch(e) { // ignore IE throwing errors when focusing hidden elements } } }, findLastActive: function() { var lastActive = this.lastActive; return lastActive && $.grep(this.errorList, function(n) { return n.element.id == lastActive.name; }).length == 1 && lastActive; }, elements: function() { var validator = this, rulesCache = {}; // select all valid inputs inside the form (no submit or reset buttons) // workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved return $([]).add(this.currentForm.elements) .filter(":input") .not(":submit, :reset, :image, [disabled]") .not( this.settings.ignore ) .filter(function() { !this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this); // select only the first element for each name, and only those with rules specified if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) return false; rulesCache[this.name] = true; return true; }); }, clean: function( selector ) { return $( selector )[0]; }, errors: function() { return $( this.settings.errorElement + "." + this.settings.errorClass, this.errorContext ); }, reset: function() { this.successList = []; this.errorList = []; this.errorMap = {}; this.toShow = $([]); this.toHide = $([]); this.currentElements = $([]); }, prepareForm: function() { this.reset(); this.toHide = this.errors().add( this.containers ); }, prepareElement: function( element ) { this.reset(); this.toHide = this.errorsFor(element); }, check: function( element ) { element = this.clean( element ); // if radio/checkbox, validate first element in group instead if (this.checkable(element)) { element = this.findByName( element.id ).not(this.settings.ignore)[0]; } var rules = $(element).rules(); var dependencyMismatch = false; for (var method in rules ) { var rule = { method: method, parameters: rules[method] }; try { var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters ); // if a method indicates that the field is optional and therefore valid, // don't mark it as valid when there are no other rules if ( result == "dependency-mismatch" ) { dependencyMismatch = true; continue; } dependencyMismatch = false; if ( result == "pending" ) { this.toHide = this.toHide.not( this.errorsFor(element) ); return; } if( !result ) { this.formatAndAdd( element, rule ); return false; } } catch(e) { this.settings.debug && window.console && console.log("exception occured when checking element " + element.id + ", check the '" + rule.method + "' method", e); throw e; } } if (dependencyMismatch) return; if ( this.objectLength(rules) ) this.successList.push(element); return true; }, // return the custom message for the given element and validation method // specified in the element's "messages" metadata customMetaMessage: function(element, method) { if (!$.metadata) return; var meta = this.settings.meta ? $(element).metadata()[this.settings.meta] : $(element).metadata(); return meta && meta.messages && meta.messages[method]; }, // return the custom message for the given element name and validation method customMessage: function( name, method ) { var m = this.settings.messages[name]; return m && (m.constructor == String ? m : m[method]); }, // return the first defined argument, allowing empty strings findDefined: function() { for(var i = 0; i < arguments.length; i++) { if (arguments[i] !== undefined) return arguments[i]; } return undefined; }, defaultMessage: function( element, method) { return this.findDefined( this.customMessage( element.id, method ), this.customMetaMessage( element, method ), // title is never undefined, so handle empty string as undefined !this.settings.ignoreTitle && element.title || undefined, $.validator.messages[method], "<strong>Warning: No message defined for " + element.id + "</strong>" ); }, formatAndAdd: function( element, rule ) { var message = this.defaultMessage( element, rule.method ), theregex = /\$?\{(\d+)\}/g; if ( typeof message == "function" ) { message = message.call(this, rule.parameters, element); } else if (theregex.test(message)) { message = jQuery.format(message.replace(theregex, '{$1}'), rule.parameters); } this.errorList.push({ message: message, element: element }); this.errorMap[element.id] = message; this.submitted[element.id] = message; }, addWrapper: function(toToggle) { if ( this.settings.wrapper ) toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) ); return toToggle; }, defaultShowErrors: function() { for ( var i = 0; this.errorList[i]; i++ ) { var error = this.errorList[i]; this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass ); this.showLabel( error.element, error.message ); } if( this.errorList.length ) { this.toShow = this.toShow.add( this.containers ); } if (this.settings.success) { for ( var i = 0; this.successList[i]; i++ ) { this.showLabel( this.successList[i] ); } } if (this.settings.unhighlight) { for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) { this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass ); } } this.toHide = this.toHide.not( this.toShow ); this.hideErrors(); this.addWrapper( this.toShow ).show(); }, validElements: function() { return this.currentElements.not(this.invalidElements()); }, invalidElements: function() { return $(this.errorList).map(function() { return this.element; }); }, showLabel: function(element, message) { var label = this.errorsFor( element ); if ( label.length ) { // refresh error/success class label.removeClass().addClass( this.settings.errorClass ); // check if we have a generated label, replace the message then label.attr("generated") && label.html(message); } else { // create label label = $("<" + this.settings.errorElement + "/>") .attr({"for": this.idOrName(element), generated: true}) .addClass(this.settings.errorClass) .html(message || ""); if ( this.settings.wrapper ) { // make sure the element is visible, even in IE // actually showing the wrapped element is handled elsewhere label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent(); } if ( !this.labelContainer.append(label).length ) this.settings.errorPlacement ? this.settings.errorPlacement(label, $(element) ) : label.insertAfter(element); } if ( !message && this.settings.success ) { label.text(""); typeof this.settings.success == "string" ? label.addClass( this.settings.success ) : this.settings.success( label ); } this.toShow = this.toShow.add(label); }, errorsFor: function(element) { var name = this.idOrName(element); return this.errors().filter(function() { return $(this).attr('for') == name; }); }, idOrName: function(element) { return this.groups[element.id] || (this.checkable(element) ? element.id : element.id || element.id); }, checkable: function( element ) { return /radio|checkbox/i.test(element.type); }, findByName: function( name ) { // select by name and filter by form for performance over form.find("[name=...]") var form = this.currentForm; return $(document.getElementsByName(name)).map(function(index, element) { return element.form == form && element.id == name && element || null; }); }, getLength: function(value, element) { switch( element.nodeName.toLowerCase() ) { case 'select': return $("option:selected", element).length; case 'input': if( this.checkable( element) ) return this.findByName(element.id).filter(':checked').length; } return value.length; }, depend: function(param, element) { return this.dependTypes[typeof param] ? this.dependTypes[typeof param](param, element) : true; }, dependTypes: { "boolean": function(param, element) { return param; }, "string": function(param, element) { return !!$(param, element.form).length; }, "function": function(param, element) { return param(element); } }, optional: function(element) { return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch"; }, startRequest: function(element) { if (!this.pending[element.id]) { this.pendingRequest++; this.pending[element.id] = true; } }, stopRequest: function(element, valid) { this.pendingRequest--; // sometimes synchronization fails, make sure pendingRequest is never < 0 if (this.pendingRequest < 0) this.pendingRequest = 0; delete this.pending[element.id]; if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) { $(this.currentForm).submit(); this.formSubmitted = false; } else if (!valid && this.pendingRequest == 0 && this.formSubmitted) { $(this.currentForm).triggerHandler("invalid-form", [this]); this.formSubmitted = false; } }, previousValue: function(element) { return $.data(element, "previousValue") || $.data(element, "previousValue", { old: null, valid: true, message: this.defaultMessage( element, "remote" ) }); } }, classRuleSettings: { required: {required: true}, email: {email: true}, url: {url: true}, date: {date: true}, dateISO: {dateISO: true}, dateDE: {dateDE: true}, number: {number: true}, numberDE: {numberDE: true}, digits: {digits: true}, creditcard: {creditcard: true} }, addClassRules: function(className, rules) { className.constructor == String ? this.classRuleSettings[className] = rules : $.extend(this.classRuleSettings, className); }, classRules: function(element) { var rules = {}; var classes = $(element).attr('class'); classes && $.each(classes.split(' '), function() { if (this in $.validator.classRuleSettings) { $.extend(rules, $.validator.classRuleSettings[this]); } }); return rules; }, attributeRules: function(element) { var rules = {}; var $element = $(element); for (var method in $.validator.methods) { var value = $element.attr(method); if (value) { rules[method] = value; } } // maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) { delete rules.maxlength; } return rules; }, metadataRules: function(element) { if (!$.metadata) return {}; var meta = $.data(element.form, 'validator').settings.meta; return meta ? $(element).metadata()[meta] : $(element).metadata(); }, staticRules: function(element) { var rules = {}; var validator = $.data(element.form, 'validator'); if (validator.settings.rules) { rules = $.validator.normalizeRule(validator.settings.rules[element.id]) || {}; } return rules; }, normalizeRules: function(rules, element) { // handle dependency check $.each(rules, function(prop, val) { // ignore rule when param is explicitly false, eg. required:false if (val === false) { delete rules[prop]; return; } if (val.param || val.depends) { var keepRule = true; switch (typeof val.depends) { case "string": keepRule = !!$(val.depends, element.form).length; break; case "function": keepRule = val.depends.call(element, element); break; } if (keepRule) { rules[prop] = val.param !== undefined ? val.param : true; } else { delete rules[prop]; } } }); // evaluate parameters $.each(rules, function(rule, parameter) { rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter; }); // clean number parameters $.each(['minlength', 'maxlength', 'min', 'max'], function() { if (rules[this]) { rules[this] = Number(rules[this]); } }); $.each(['rangelength', 'range'], function() { if (rules[this]) { rules[this] = [Number(rules[this][0]), Number(rules[this][1])]; } }); if ($.validator.autoCreateRanges) { // auto-create ranges if (rules.min && rules.max) { rules.range = [rules.min, rules.max]; delete rules.min; delete rules.max; } if (rules.minlength && rules.maxlength) { rules.rangelength = [rules.minlength, rules.maxlength]; delete rules.minlength; delete rules.maxlength; } } // To support custom messages in metadata ignore rule methods titled "messages" if (rules.messages) { delete rules.messages; } return rules; }, // Converts a simple string to a {string: true} rule, e.g., "required" to {required:true} normalizeRule: function(data) { if( typeof data == "string" ) { var transformed = {}; $.each(data.split(/\s/), function() { transformed[this] = true; }); data = transformed; } return data; }, // http://docs.jquery.com/Plugins/Validation/Validator/addMethod addMethod: function(name, method, message) { $.validator.methods[name] = method; $.validator.messages[name] = message != undefined ? message : $.validator.messages[name]; if (method.length < 3) { $.validator.addClassRules(name, $.validator.normalizeRule(name)); } }, methods: { // http://docs.jquery.com/Plugins/Validation/Methods/required required: function(value, element, param) { // check if dependency is met if ( !this.depend(param, element) ) return "dependency-mismatch"; switch( element.nodeName.toLowerCase() ) { case 'select': // could be an array for select-multiple or a string, both are fine this way var val = $(element).val(); return val && val.length > 0; case 'input': if ( this.checkable(element) ) return this.getLength(value, element) > 0; default: return $.trim(value).length > 0; } }, // http://docs.jquery.com/Plugins/Validation/Methods/remote remote: function(value, element, param) { if ( this.optional(element) ) return "dependency-mismatch"; var previous = this.previousValue(element); if (!this.settings.messages[element.id] ) this.settings.messages[element.id] = {}; previous.originalMessage = this.settings.messages[element.id].remote; this.settings.messages[element.id].remote = previous.message; param = typeof param == "string" && {url:param} || param; if ( this.pending[element.id] ) { return "pending"; } if ( previous.old === value ) { return previous.valid; } previous.old = value; var validator = this; this.startRequest(element); var data = {}; data[element.id] = value; $.ajax($.extend(true, { url: param, mode: "abort", port: "validate" + element.id, dataType: "json", data: data, success: function(response) { validator.settings.messages[element.id].remote = previous.originalMessage; var valid = response === true; if ( valid ) { var submitted = validator.formSubmitted; validator.prepareElement(element); validator.formSubmitted = submitted; validator.successList.push(element); validator.showErrors(); } else { var errors = {}; var message = response || validator.defaultMessage( element, "remote" ); errors[element.id] = previous.message = $.isFunction(message) ? message(value) : message; validator.showErrors(errors); } previous.valid = valid; validator.stopRequest(element, valid); } }, param)); return "pending"; }, // http://docs.jquery.com/Plugins/Validation/Methods/minlength minlength: function(value, element, param) { return this.optional(element) || this.getLength($.trim(value), element) >= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/maxlength maxlength: function(value, element, param) { return this.optional(element) || this.getLength($.trim(value), element) <= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/rangelength rangelength: function(value, element, param) { var length = this.getLength($.trim(value), element); return this.optional(element) || ( length >= param[0] && length <= param[1] ); }, // http://docs.jquery.com/Plugins/Validation/Methods/min min: function( value, element, param ) { return this.optional(element) || value >= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/max max: function( value, element, param ) { return this.optional(element) || value <= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/range range: function( value, element, param ) { return this.optional(element) || ( value >= param[0] && value <= param[1] ); }, // http://docs.jquery.com/Plugins/Validation/Methods/email email: function(value, element) { // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/ return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/url url: function(value, element) { // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/ return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/date date: function(value, element) { return this.optional(element) || !/Invalid|NaN/.test(new Date(value)); }, // http://docs.jquery.com/Plugins/Validation/Methods/dateISO dateISO: function(value, element) { return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/number number: function(value, element) { return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/digits digits: function(value, element) { return this.optional(element) || /^\d+$/.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/creditcard // based on http://en.wikipedia.org/wiki/Luhn creditcard: function(value, element) { if ( this.optional(element) ) return "dependency-mismatch"; // accept only digits and dashes if (/[^0-9-]+/.test(value)) return false; var nCheck = 0, nDigit = 0, bEven = false; value = value.replace(/\D/g, ""); for (var n = value.length - 1; n >= 0; n--) { var cDigit = value.charAt(n); var nDigit = parseInt(cDigit, 10); if (bEven) { if ((nDigit *= 2) > 9) nDigit -= 9; } nCheck += nDigit; bEven = !bEven; } return (nCheck % 10) == 0; }, // http://docs.jquery.com/Plugins/Validation/Methods/accept accept: function(value, element, param) { param = typeof param == "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif"; return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i")); }, // http://docs.jquery.com/Plugins/Validation/Methods/equalTo equalTo: function(value, element, param) { // bind to the blur event of the target in order to revalidate whenever the target field is updated // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead var target = $(param).unbind(".validate-equalTo").bind("blur.validate-equalTo", function() { $(element).valid(); }); return value == target.val(); } } }); // deprecated, use $.validator.format instead $.format = $.validator.format; })(jQuery); // ajax mode: abort // usage: $.ajax({ mode: "abort"[, port: "uniqueport"]}); // if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort() ;(function($) { var pendingRequests = {}; // Use a prefilter if available (1.5+) if ( $.ajaxPrefilter ) { $.ajaxPrefilter(function(settings, _, xhr) { var port = settings.port; if (settings.mode == "abort") { if ( pendingRequests[port] ) { pendingRequests[port].abort(); } pendingRequests[port] = xhr; } }); } else { // Proxy ajax var ajax = $.ajax; $.ajax = function(settings) { var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode, port = ( "port" in settings ? settings : $.ajaxSettings ).port; if (mode == "abort") { if ( pendingRequests[port] ) { pendingRequests[port].abort(); } return (pendingRequests[port] = ajax.apply(this, arguments)); } return ajax.apply(this, arguments); }; } })(jQuery); // provides cross-browser focusin and focusout events // IE has native support, in other browsers, use event caputuring (neither bubbles) // provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation // handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target ;(function($) { // only implement if not provided by jQuery core (since 1.4) // TODO verify if jQuery 1.4's implementation is compatible with older jQuery special-event APIs if (!jQuery.event.special.focusin && !jQuery.event.special.focusout && document.addEventListener) { $.each({ focus: 'focusin', blur: 'focusout' }, function( original, fix ){ $.event.special[fix] = { setup:function() { this.addEventListener( original, handler, true ); }, teardown:function() { this.removeEventListener( original, handler, true ); }, handler: function(e) { arguments[0] = $.event.fix(e); arguments[0].type = fix; return $.event.handle.apply(this, arguments); } }; function handler(e) { e = $.event.fix(e); e.type = fix; return $.event.handle.call(this, e); } }); }; $.extend($.fn, { validateDelegate: function(delegate, type, handler) { return this.bind(type, function(event) { var target = $(event.target); if (target.is(delegate)) { return handler.apply(target, arguments); } }); } }); })(jQuery);
JavaScript
// 手机号码验证 jQuery.validator.addMethod("mobile", function(value, element) { var length = value.length; return this.optional(element) || (length == 11 && /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/.test(value) || /^(((18[0-9]{1})|(15[0-9]{1}))+\d{8})$/.test(value) || /^(((15[0-9]{1})|(15[0-9]{1}))+\d{8})$/.test(value)); }, "手机号码格式错误!"); // 电话号码验证 jQuery.validator.addMethod("phone", function(value, element) { //var tel = /^(\d{3,4}-?)?\d{7,9}$/g; var tel = /^(\d{3,4}-?)?\d{7,9}$/; return this.optional(element) || (tel.test(value)); }, "电话号码格式错误!"); // 特殊字符验证 jQuery.validator.addMethod("string", function(value, element) { return this.optional(element) || (/^[\u0391-\uFFE5\w]+$/.test(value)); }, "不允许包含特殊符号!"); // 中文英文验证 jQuery.validator.addMethod("cnen", function(value, element) { return this.optional(element) || (/^[\u4e00-\u9fa5a-zA-Z]+$/.test(value)); }, "不允许包含特殊符号!"); // 中文英文数字验证 jQuery.validator.addMethod("cnennum", function(value, element) { //return this.optional(element) || /^[\u4e00-\u9fa5a-zA-Z]+$/.test(value); return this.optional(element) || (/^[A-Za-z0-9\u4E00-\u9FA5]+$/.test(value)); }, "中文英文数字!"); // 增加只能是字母和数字的验证 jQuery.validator.addMethod("ennum", function(value, element) { return this.optional(element) || (/^[a-zA-Z0-9]+$/.test(value)); }, "只能输入英文和数字"); // 网址URL jQuery.validator.addMethod("enurl", function(value, element) { return this.optional(element) || (/^[a-zA-z]+://[^\s]/.test(value)); }, ""); //日期 jQuery.validator.addMethod("compareDate",function(value, element, param) { var startDate = $(param).val(); var date1 = parseInt(startDate.replace(/-/g,'')); var date2 = parseInt(value.replace(/-/g,'')); return this.optional(element) || (date1 < date2); },""); function Is_URL(str_url){ var strRegex = "^((https|http|ftp|rtsp|mms)?://)" + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@ + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184 + "|" // 允许IP和DOMAIN(域名) + "([0-9a-z_!~*'()-]+\.)*" // 域名- www. + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名 + "[a-z]{2,6})" // first level domain- .com or .museum + "(:[0-9]{1,4})?" // 端口- :80 + "((/?)|" // a slash isn't required if there is no file name + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"; var re=new RegExp(strRegex); //re.test() if (re.test(str_url)){ return (true); }else{ return (false); } } //日期 jQuery.validator.addMethod("isurl",function(value) { var strRegex = "^((https|http|ftp|rtsp|mms)?://)" + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@ + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184 + "|" // 允许IP和DOMAIN(域名) + "([0-9a-z_!~*'()-]+\.)*" // 域名- www. + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名 + "[a-z]{2,6})" // first level domain- .com or .museum + "(:[0-9]{1,4})?" // 端口- :80 + "((/?)|" // a slash isn't required if there is no file name + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"; var re=new RegExp(strRegex); //re.test() if (re.test(value)){ return (true); }else{ return (false); } });
JavaScript
/* Modernizr 2.6.2 (Custom Build) | MIT & BSD * Build: http://modernizr.com/download/#-draganddrop-hasevent */ ; window.Modernizr = (function( window, document, undefined ) { var version = '2.6.2', Modernizr = {}, docElement = document.documentElement, mod = 'modernizr', modElem = document.createElement(mod), mStyle = modElem.style, inputElem , toString = {}.toString, tests = {}, inputs = {}, attrs = {}, classes = [], slice = classes.slice, featureName, isEventSupported = (function() { var TAGNAMES = { 'select': 'input', 'change': 'input', 'submit': 'form', 'reset': 'form', 'error': 'img', 'load': 'img', 'abort': 'img' }; function isEventSupported( eventName, element ) { element = element || document.createElement(TAGNAMES[eventName] || 'div'); eventName = 'on' + eventName; var isSupported = eventName in element; if ( !isSupported ) { if ( !element.setAttribute ) { element = document.createElement('div'); } if ( element.setAttribute && element.removeAttribute ) { element.setAttribute(eventName, ''); isSupported = is(element[eventName], 'function'); if ( !is(element[eventName], 'undefined') ) { element[eventName] = undefined; } element.removeAttribute(eventName); } } element = null; return isSupported; } return isEventSupported; })(), _hasOwnProperty = ({}).hasOwnProperty, hasOwnProp; if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) { hasOwnProp = function (object, property) { return _hasOwnProperty.call(object, property); }; } else { hasOwnProp = function (object, property) { return ((property in object) && is(object.constructor.prototype[property], 'undefined')); }; } if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { var target = this; if (typeof target != "function") { throw new TypeError(); } var args = slice.call(arguments, 1), bound = function () { if (this instanceof bound) { var F = function(){}; F.prototype = target.prototype; var self = new F(); var result = target.apply( self, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return self; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; return bound; }; } function setCss( str ) { mStyle.cssText = str; } function setCssAll( str1, str2 ) { return setCss(prefixes.join(str1 + ';') + ( str2 || '' )); } function is( obj, type ) { return typeof obj === type; } function contains( str, substr ) { return !!~('' + str).indexOf(substr); } function testDOMProps( props, obj, elem ) { for ( var i in props ) { var item = obj[props[i]]; if ( item !== undefined) { if (elem === false) return props[i]; if (is(item, 'function')){ return item.bind(elem || obj); } return item; } } return false; } tests['draganddrop'] = function() { var div = document.createElement('div'); return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div); }; for ( var feature in tests ) { if ( hasOwnProp(tests, feature) ) { featureName = feature.toLowerCase(); Modernizr[featureName] = tests[feature](); classes.push((Modernizr[featureName] ? '' : 'no-') + featureName); } } Modernizr.addTest = function ( feature, test ) { if ( typeof feature == 'object' ) { for ( var key in feature ) { if ( hasOwnProp( feature, key ) ) { Modernizr.addTest( key, feature[ key ] ); } } } else { feature = feature.toLowerCase(); if ( Modernizr[feature] !== undefined ) { return Modernizr; } test = typeof test == 'function' ? test() : test; if (typeof enableClasses !== "undefined" && enableClasses) { docElement.className += ' ' + (test ? '' : 'no-') + feature; } Modernizr[feature] = test; } return Modernizr; }; setCss(''); modElem = inputElem = null; Modernizr._version = version; Modernizr.hasEvent = isEventSupported; return Modernizr; })(this, this.document); ;
JavaScript
(function(){ Douban.init_lnk_share = function(e){ var el = $(this), param = el.attr('rel').split('|'); var url = param[0]; var stype = param[1]; var title = param[2]; var content = param[3]; //var hash = window.document.getElementById("bigImage").src.replace(/.*key=([^&]+).*/,'$1'); var img =""; var siteUrl = param[4] ; var pin = ""; if (stype == "qzone"){ url = url + "&title=" + content + "&pic=" + img + "&url=" + siteUrl + pin; } if (stype == "sina"){ url = url + "&title=" + content + "&pic=" + img + "&url=" + siteUrl + pin; } if (stype == "renren"){ url = url + "title=" + title +"&content="+ content + "&pic=" + img + "&url=" + siteUrl + pin; } if (stype == "kaixing"){ url = url + "rtitle=" + title + "&rcontent=" + content + "&rurl=" + siteUrl + pin; } if (stype == "douban"){ url = url + "title=" + title + "&comment=" + content + "&url=" + siteUrl + pin; } if (stype == "MSN"){ url = url + "url=" + siteUrl + pin + "&title=" + title + "&description=" + content + "&screenshot=" + img; } window.open(encodeURI(url),"","height=500, width=600"); }; })();
JavaScript
/** * jQuery plugin for posting form including file inputs. * Copyright (c) 2010 Ewen Elder * * Licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * @author: Ewen Elder <glomainn at yahoo dot co dot uk> <ewen at jainaewen dot com> * @version: 1.0.1 (2010-22-02) **/ (function($) { $.fn.iframePostForm = function(o) { var J, a, i, n; a = $(this); o = $.extend({}, $.fn.iframePostForm.defaults, o); if (!$('#' + o.iframeID).length) { $('body').append('<iframe name="' + o.iframeID + '" id="' + o.iframeID + '" style="display:none"></iframe>') } return a.each(function() { i = $(this); i.attr('target', o.iframeID); i.submit(function() { o.post.apply(this); n = $('#' + o.iframeID); n.unbind('load').bind('load', function() { J = n.contents().find('body'); o.complete.apply(this, [J.html()]); setTimeout(function() { J.html('') }, 1) }) }) }) }; $.fn.iframePostForm.defaults = { iframeID: 'iframe-post-form', post: function() {}, complete: function(response) {} } })(jQuery);
JavaScript
(function($) { var defaultConfig = { errorRequired: '此项为必填项', errorTempl: '<span class="validate-error">{msg}</span>', optionTempl: '<span class="validate-option">{msg}</span>', callback: null }, CSS_ITEM = '.item', CSS_ERROR = '.validate-error', CSS_OPTION = '.validate-option', validateForm = function(el, oRules, oErrorMsg, oOptions, oConfig) { if (!oRules || !el) { return; } this.asyncList = []; this.asyncEndHandle = null; this._init(el, oRules, oErrorMsg, oOptions, oConfig); }; validateForm.prototype = { _init: function(el, oRules, oErrorMsg, oOptions, oConfig) { var node; node = this.node = $(el); this.form = (node.attr('tagName').toLowerCase() === 'form') ? node : node.find('form'); this.config = $.extend(defaultConfig, oConfig); this.rules = oRules; this.errorMsg = oErrorMsg || {}; this.optionMsg = oOptions || {}; node.data('validateForm', this); this._bindEvent(); }, _bindEvent: function() { if (this.node.data('hasBindValidateEvent')) { return; } this.node.data('hasBindValidateEvent', true); //bind form. this.form.submit($.proxy(function(e) { this.validate(); this._handleFormSubmit(e); }, this)).find('input, select, textarea').bind({ //bind error verifny blur: $.proxy(function(e) { this._handleBlur(e); }, this), //bind option msg focus: $.proxy(function(e) { this._handleFocus(e); }, this) }); this._bindRules(); }, _bindRules: function() { var rules = this.rules, k; for (k in rules) { if (rules.hasOwnProperty(k)) { $(rules[k].elems, this.form).each(function(i, e) { var $e = $(e), r = $e.data('validate-rules') || ''; $e.data('validate-rules', r + ',' + k) }); } } }, _handleBlur: function(e) { var $e = $(e.target), $item = $e.parents(CSS_ITEM).eq(0), i, r, len, k, hasError = false, rules = $e.data('validate-rules'); $item.find(CSS_OPTION).hide(); if (!rules) { return; } rules = rules.split(',').slice(1); for (i = 0, len = rules.length; i < len; i++) { r = this.rules[rules[i]]; this.validate(r, this.errorMsg[rules[i]], $e); } }, _handleFocus: function(e) { var na = e.target.getAttribute('name'), msg; if (!na) { return; } if (msg = this.optionMsg[na.toLowerCase()]) { this.displayOptionMsg($(e.target), msg); } }, _handleFormSubmit: function(e) { e.preventDefault(); var errorItems, processItems, o = this; errorItems = this.form.find('.has-error'); if (errorItems.length > 0) { e.preventDefault(); $(o.form).trigger('hasError'); return; } processItems = this.form.find('.has-process'); if (processItems.length > 0) { e.preventDefault(); this.asyncEndHandle = function() { o.asyncEndHandle = null; o._handleFormSubmit(e); }; return; } if (o.config.callback) { e.preventDefault(); o.config.callback(o.form); } else { o.form[0].submit(); } }, clearErrorMsg: function(el) { var item = el.parents(CSS_ITEM).eq(0); item.find(CSS_ERROR).hide(); }, displayError: function(el, msg) { var item = el.parents(CSS_ITEM).eq(0), option = item.find(CSS_OPTION), error = item.find(CSS_ERROR); option.hide(); if (error.length === 0) { $(this.config.errorTempl.replace('{msg}', msg)).appendTo(item).show(); return; } error.show().html(msg); return; }, displayOptionMsg: function(el, msg) { if (!msg) { return; } var item = el.parents(CSS_ITEM).eq(0), option = item.find(CSS_OPTION), error = item.hasClass('has-error'); if (error) { return; } if (option.length === 0) { $(this.config.optionTempl.replace('{msg}', msg)).appendTo(item).show(); return; } option.show().html(msg); return; }, asyncValidate: function(el, url, cb) { if (!el || !url) { return; } var item = el.parent(); if (item.hasClass('has-process')) { return; } item.addClass('has-process'); this.asyncList.push($.getJSON(url, $.proxy(function(da){ var list = this.asyncList; cb && cb(da); item.removeClass('has-process'); this.asyncList.pop(); if (list.length === 0) { this.asyncEndHandle && this.asyncEndHandle(); } }, this))); $('body').ajaxError(function(){ alert('远程验证失败!\n请稍候重试或将此问题反馈给我们(help@12ik.com)'); }); }, validate: function(rule, errorMsg, el) { var errorRequired = this.errorMsg.errorRequired, verify = function(r, errmsg, el, o) { var item = el.parents(CSS_ITEM).eq(0), hasError = false, k; if (r.isRequired && $.trim(el.val()) === '') { o.displayError(el, errorRequired || defaultConfig.errorRequired); hasError = true; item.addClass('has-error'); } else { for (k in r) { if (r.hasOwnProperty(k) && typeof r[k] === 'function') { if (r[k](el, o)) { o.displayError(el, errmsg[k]); item.addClass('has-error'); hasError = true; break; } } } if (!hasError) { o.clearErrorMsg(el); item.removeClass('has-error'); } } }, r, rules, errors, k; if (!rule) { rules = this.rules; errors = this.errorMsg; for (k in rules) { if (rules.hasOwnProperty(k)) { r = rules[k]; $(r.elems, this.form).each($.proxy(function(i, e) { verify(r, errors[k], $(e), this); }, this)); } } } else { verify(rule, errorMsg, el, this); } } }; // public validate methods. $.extend({ validate: { isEmail: function(s) { return /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(s); } } }); $.fn.validateForm = function(oRules, oErrorMsg, oOptions, oConfig) { var options = oOptions, config = oConfig; if (arguments.length === 3) { options = null; config = oOptions; } this.each(function() { new validateForm(this, oRules, oErrorMsg, options, config); }); return this; }; })(jQuery);
JavaScript
/*! * jQuery Templates Plugin 1.0.0pre * http://github.com/jquery/jquery-tmpl * Requires jQuery 1.4.2 * * Copyright 2011, Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( jQuery, undefined ){ var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /, newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = []; function newTmplItem( options, parentItem, fn, data ) { // Returns a template item data structure for a new rendered instance of a template (a 'template item'). // The content field is a hierarchical array of strings and nested items (to be // removed and replaced by nodes field of dom elements, once inserted in DOM). var newItem = { data: data || (data === 0 || data === false) ? data : (parentItem ? parentItem.data : {}), _wrap: parentItem ? parentItem._wrap : null, tmpl: null, parent: parentItem || null, nodes: [], calls: tiCalls, nest: tiNest, wrap: tiWrap, html: tiHtml, update: tiUpdate }; if ( options ) { jQuery.extend( newItem, options, { nodes: [], parent: parentItem }); } if ( fn ) { // Build the hierarchical content to be used during insertion into DOM newItem.tmpl = fn; newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem ); newItem.key = ++itemKey; // Keep track of new template item, until it is stored as jQuery Data on DOM element (stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem; } return newItem; } // Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core). 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 ), elems, i, l, tmplItems, parent = this.length === 1 && this[0].parentNode; appendToTmplItems = newTmplItems || {}; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); ret = this; } else { for ( i = 0, l = insert.length; i < l; i++ ) { cloneIndex = i; elems = (i > 0 ? this.clone(true) : this).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } cloneIndex = 0; ret = this.pushStack( ret, name, insert.selector ); } tmplItems = appendToTmplItems; appendToTmplItems = null; jQuery.tmpl.complete( tmplItems ); return ret; }; }); jQuery.fn.extend({ // Use first wrapped element as template markup. // Return wrapped set of template items, obtained by rendering template against data. tmpl: function( data, options, parentItem ) { return jQuery.tmpl( this[0], data, options, parentItem ); }, // Find which rendered template item the first wrapped DOM element belongs to tmplItem: function() { return jQuery.tmplItem( this[0] ); }, // Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template. template: function( name ) { return jQuery.template( name, this[0] ); }, domManip: function( args, table, callback, options ) { if ( args[0] && jQuery.isArray( args[0] )) { var dmArgs = jQuery.makeArray( arguments ), elems = args[0], elemsLength = elems.length, i = 0, tmplItem; while ( i < elemsLength && !(tmplItem = jQuery.data( elems[i++], "tmplItem" ))) {} if ( tmplItem && cloneIndex ) { dmArgs[2] = function( fragClone ) { // Handler called by oldManip when rendered template has been inserted into DOM. jQuery.tmpl.afterManip( this, fragClone, callback ); }; } oldManip.apply( this, dmArgs ); } else { oldManip.apply( this, arguments ); } cloneIndex = 0; if ( !appendToTmplItems ) { jQuery.tmpl.complete( newTmplItems ); } return this; } }); jQuery.extend({ // Return wrapped set of template items, obtained by rendering template against data. tmpl: function( tmpl, data, options, parentItem ) { var ret, topLevel = !parentItem; if ( topLevel ) { // This is a top-level tmpl call (not from a nested template using {{tmpl}}) parentItem = topTmplItem; tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl ); wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level } else if ( !tmpl ) { // The template item is already associated with DOM - this is a refresh. // Re-evaluate rendered template for the parentItem tmpl = parentItem.tmpl; newTmplItems[parentItem.key] = parentItem; parentItem.nodes = []; if ( parentItem.wrapped ) { updateWrapped( parentItem, parentItem.wrapped ); } // Rebuild, without creating a new template item return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) )); } if ( !tmpl ) { return []; // Could throw... } if ( typeof data === "function" ) { data = data.call( parentItem || {} ); } if ( options && options.wrapped ) { updateWrapped( options, options.wrapped ); } ret = jQuery.isArray( data ) ? jQuery.map( data, function( dataItem ) { return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null; }) : [ newTmplItem( options, parentItem, tmpl, data ) ]; return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret; }, // Return rendered template item for an element. tmplItem: function( elem ) { var tmplItem; if ( elem instanceof jQuery ) { elem = elem[0]; } while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {} return tmplItem || topTmplItem; }, // Set: // Use $.template( name, tmpl ) to cache a named template, // where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc. // Use $( "selector" ).template( name ) to provide access by name to a script block template declaration. // Get: // Use $.template( name ) to access a cached template. // Also $( selectorToScriptBlock ).template(), or $.template( null, templateString ) // will return the compiled template, without adding a name reference. // If templateString includes at least one HTML tag, $.template( templateString ) is equivalent // to $.template( null, templateString ) template: function( name, tmpl ) { if (tmpl) { // Compile template and associate with name if ( typeof tmpl === "string" ) { // This is an HTML string being passed directly in. tmpl = buildTmplFn( tmpl ); } else if ( tmpl instanceof jQuery ) { tmpl = tmpl[0] || {}; } if ( tmpl.nodeType ) { // If this is a template block, use cached copy, or generate tmpl function and cache. tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML )); // Issue: In IE, if the container element is not a script block, the innerHTML will remove quotes from attribute values whenever the value does not include white space. // This means that foo="${x}" will not work if the value of x includes white space: foo="${x}" -> foo=value of x. // To correct this, include space in tag: foo="${ x }" -> foo="value of x" } return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl; } // Return named compiled template return name ? (typeof name !== "string" ? jQuery.template( null, name ): (jQuery.template[name] || // If not in map, and not containing at least on HTML tag, treat as a selector. // (If integrated with core, use quickExpr.exec) jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null; }, encode: function( text ) { // Do HTML encoding replacing < > & and ' and " by corresponding entities. return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;"); } }); jQuery.extend( jQuery.tmpl, { tag: { "tmpl": { _default: { $2: "null" }, open: "if($notnull_1){__=__.concat($item.nest($1,$2));}" // tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions) // This means that {{tmpl foo}} treats foo as a template (which IS a function). // Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}. }, "wrap": { _default: { $2: "null" }, open: "$item.calls(__,$1,$2);__=[];", close: "call=$item.calls();__=call._.concat($item.wrap(call,__));" }, "each": { _default: { $2: "$index, $value" }, open: "if($notnull_1){$.each($1a,function($2){with(this){", close: "}});}" }, "if": { open: "if(($notnull_1) && $1a){", close: "}" }, "else": { _default: { $1: "true" }, open: "}else if(($notnull_1) && $1a){" }, "html": { // Unecoded expression evaluation. open: "if($notnull_1){__.push($1a);}" }, "=": { // Encoded expression evaluation. Abbreviated form is ${}. _default: { $1: "$data" }, open: "if($notnull_1){__.push($.encode($1a));}" }, "!": { // Comment tag. Skipped by parser open: "" } }, // This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events complete: function( items ) { newTmplItems = {}; }, // Call this from code which overrides domManip, or equivalent // Manage cloning/storing template items etc. afterManip: function afterManip( elem, fragClone, callback ) { // Provides cloned fragment ready for fixup prior to and after insertion into DOM var content = fragClone.nodeType === 11 ? jQuery.makeArray(fragClone.childNodes) : fragClone.nodeType === 1 ? [fragClone] : []; // Return fragment to original caller (e.g. append) for DOM insertion callback.call( elem, fragClone ); // Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data. storeTmplItems( content ); cloneIndex++; } }); //========================== Private helper functions, used by code above ========================== function build( tmplItem, nested, content ) { // Convert hierarchical content into flat string array // and finally return array of fragments ready for DOM insertion var frag, ret = content ? jQuery.map( content, function( item ) { return (typeof item === "string") ? // Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM. (tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) : // This is a child template item. Build nested template. build( item, tmplItem, item._ctnt ); }) : // If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}. tmplItem; if ( nested ) { return ret; } // top-level template ret = ret.join(""); // Support templates which have initial or final text nodes, or consist only of text // Also support HTML entities within the HTML markup. ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) { frag = jQuery( middle ).get(); storeTmplItems( frag ); if ( before ) { frag = unencode( before ).concat(frag); } if ( after ) { frag = frag.concat(unencode( after )); } }); return frag ? frag : unencode( ret ); } function unencode( text ) { // Use createElement, since createTextNode will not render HTML entities correctly var el = document.createElement( "div" ); el.innerHTML = text; return jQuery.makeArray(el.childNodes); } // Generate a reusable function that will serve to render a template against data function buildTmplFn( markup ) { return new Function("jQuery","$item", // Use the variable __ to hold a string array while building the compiled template. (See https://github.com/jquery/jquery-tmpl/issues#issue/10). "var $=jQuery,call,__=[],$data=$item.data;" + // Introduce the data as local variables using with(){} "with($data){__.push('" + // Convert the template into pure JavaScript jQuery.trim(markup) .replace( /([\\'])/g, "\\$1" ) .replace( /[\r\t\n]/g, " " ) .replace( /\$\{([^\}]*)\}/g, "{{#= $1}}" ) .replace( /\{\{#(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g, function( all, slash, type, fnargs, target, parens, args ) { var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect; if ( !tag ) { throw "Unknown template tag: " + type; } def = tag._default || []; if ( parens && !/\w$/.test(target)) { target += parens; parens = ""; } if ( target ) { target = unescape( target ); args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : ""); // Support for target being things like a.toLowerCase(); // In that case don't call with template item as 'this' pointer. Just evaluate... expr = parens ? (target.indexOf(".") > -1 ? target + unescape( parens ) : ("(" + target + ").call($item" + args)) : target; exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))"; } else { exprAutoFnDetect = expr = def.$1 || "null"; } fnargs = unescape( fnargs ); return "');" + tag[ slash ? "close" : "open" ] .split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" ) .split( "$1a" ).join( exprAutoFnDetect ) .split( "$1" ).join( expr ) .split( "$2" ).join( fnargs || def.$2 || "" ) + "__.push('"; }) + "');}return __;" ); } function updateWrapped( options, wrapped ) { // Build the wrapped content. options._wrap = build( options, true, // Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string. jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()] ).join(""); } function unescape( args ) { return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null; } function outerHtml( elem ) { var div = document.createElement("div"); div.appendChild( elem.cloneNode(true) ); return div.innerHTML; } // Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance. function storeTmplItems( content ) { var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m; for ( i = 0, l = content.length; i < l; i++ ) { if ( (elem = content[i]).nodeType !== 1 ) { continue; } elems = elem.getElementsByTagName("*"); for ( m = elems.length - 1; m >= 0; m-- ) { processItemKey( elems[m] ); } processItemKey( elem ); } function processItemKey( el ) { var pntKey, pntNode = el, pntItem, tmplItem, key; // Ensure that each rendered template inserted into the DOM has its own template item, if ( (key = el.getAttribute( tmplItmAtt ))) { while ( pntNode.parentNode && (pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { } if ( pntKey !== key ) { // The next ancestor with a _tmplitem expando is on a different key than this one. // So this is a top-level element within this template item // Set pntNode to the key of the parentNode, or to 0 if pntNode.parentNode is null, or pntNode is a fragment. pntNode = pntNode.parentNode ? (pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0)) : 0; if ( !(tmplItem = newTmplItems[key]) ) { // The item is for wrapped content, and was copied from the temporary parent wrappedItem. tmplItem = wrappedItems[key]; tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode] ); tmplItem.key = ++itemKey; newTmplItems[itemKey] = tmplItem; } if ( cloneIndex ) { cloneTmplItem( key ); } } el.removeAttribute( tmplItmAtt ); } else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) { // This was a rendered element, cloned during append or appendTo etc. // TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem. cloneTmplItem( tmplItem.key ); newTmplItems[tmplItem.key] = tmplItem; pntNode = jQuery.data( el.parentNode, "tmplItem" ); pntNode = pntNode ? pntNode.key : 0; } if ( tmplItem ) { pntItem = tmplItem; // Find the template item of the parent element. // (Using !=, not !==, since pntItem.key is number, and pntNode may be a string) while ( pntItem && pntItem.key != pntNode ) { // Add this element as a top-level node for this rendered template item, as well as for any // ancestor items between this item and the item of its parent element pntItem.nodes.push( el ); pntItem = pntItem.parent; } // Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering... delete tmplItem._ctnt; delete tmplItem._wrap; // Store template item as jQuery data on the element jQuery.data( el, "tmplItem", tmplItem ); } function cloneTmplItem( key ) { key = key + keySuffix; tmplItem = newClonedItems[key] = (newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent )); } } } //---- Helper functions for template item ---- function tiCalls( content, tmpl, data, options ) { if ( !content ) { return stack.pop(); } stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options }); } function tiNest( tmpl, data, options ) { // nested template, using {{tmpl}} tag return jQuery.tmpl( jQuery.template( tmpl ), data, options, this ); } function tiWrap( call, wrapped ) { // nested template, using {{wrap}} tag var options = call.options || {}; options.wrapped = wrapped; // Apply the template, which may incorporate wrapped content, return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item ); } function tiHtml( filter, textOnly ) { var wrapped = this._wrap; return jQuery.map( jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ), function(e) { return textOnly ? e.innerText || e.textContent : e.outerHTML || outerHtml(e); }); } function tiUpdate() { var coll = this.nodes; jQuery.tmpl( null, null, null, this).insertBefore( coll[0] ); jQuery( coll ).remove(); } })( jQuery );
JavaScript
//及时消息开始 var newMessageRemind={ _step: 0, _title: document.title, _timer: null, //显示新消息提示 show:function(){ var temps = newMessageRemind._title.replace("【   】", "").replace("【新消息】", ""); newMessageRemind._timer = setTimeout(function() { newMessageRemind.show(); //这里写Cookie操作 newMessageRemind._step++; if (newMessageRemind._step == 3) { newMessageRemind._step = 1 }; if (newMessageRemind._step == 1) { document.title = "【   】" + temps }; if (newMessageRemind._step == 2) { document.title = "【新消息】" + temps }; }, 600); return [newMessageRemind._timer, newMessageRemind._title]; }, //取消新消息提示 clear: function(){ clearTimeout(newMessageRemind._timer ); document.title = newMessageRemind._title; //这里写Cookie操作 } }; function clearNewMessageRemind() { newMessageRemind.clear(); } function evdata(userid){ $.ajax({ type: "GET", url: siteUrl + "index.php?app=message&ac=newmsg&userid="+userid, success: function(msg){ if(msg.r == '0'){ $('#newmsg').html('新消息(<font color="red">'+msg.num+'</font>)'); newMessageRemind.show(); }else if(msg.r == '1'){ $('#newmsg').html('<a href="'+siteUrl+'index.php?app=message&ac=ikmail&ts=inbox">新消息</a>'); } } }); } //及时消息结束
JavaScript
/* * This file has been commented to support Visual Studio Intellisense. * You should not use this file at runtime inside the browser--it is only * intended to be used only for design-time IntelliSense. Please use the * standard jQuery library for all production use. * * Comment version: 1.3.2b */ /* * jQuery JavaScript Library v1.3.2 * http://jquery.com/ * * Copyright (c) 2009 John Resig * * 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. * * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) * Revision: 6246 */ (function(){ var // Will speed up references to window, and allows munging its name. window = this, // Will speed up references to undefined, and allows munging its name. undefined, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, jQuery = window.jQuery = window.$ = function(selector, context) { /// <summary> /// 1: $(expression, context) - This function accepts a string containing a CSS selector which is then used to match a set of elements. /// 2: $(html) - Create DOM elements on-the-fly from the provided String of raw HTML. /// 3: $(elements) - Wrap jQuery functionality around a single or multiple DOM Element(s). /// 4: $(callback) - A shorthand for $(document).ready(). /// </summary> /// <param name="selector" type="String"> /// 1: expression - An expression to search with. /// 2: html - A string of HTML to create on the fly. /// 3: elements - DOM element(s) to be encapsulated by a jQuery object. /// 4: callback - The function to execute when the DOM is ready. /// </param> /// <param name="context" type="jQuery"> /// 1: context - A DOM Element, Document or jQuery to use as context. /// </param> /// <field name="selector" Type="Object"> /// The DOM node context originally passed to jQuery() (if none was passed then context will be equal to the document). /// </field> /// <field name="context" Type="String"> /// A selector representing selector originally passed to jQuery(). /// </field> /// <returns type="jQuery" /> // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); }, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/, // Is it a simple selector isSimple = /^.[^:#\[\.,]*$/; jQuery.fn = jQuery.prototype = { init: function( selector, context ) { /// <summary> /// 1: $(expression, context) - This function accepts a string containing a CSS selector which is then used to match a set of elements. /// 2: $(html) - Create DOM elements on-the-fly from the provided String of raw HTML. /// 3: $(elements) - Wrap jQuery functionality around a single or multiple DOM Element(s). /// 4: $(callback) - A shorthand for $(document).ready(). /// </summary> /// <param name="selector" type="String"> /// 1: expression - An expression to search with. /// 2: html - A string of HTML to create on the fly. /// 3: elements - DOM element(s) to be encapsulated by a jQuery object. /// 4: callback - The function to execute when the DOM is ready. /// </param> /// <param name="context" type="jQuery"> /// 1: context - A DOM Element, Document or jQuery to use as context. /// </param> /// <returns type="jQuery" /> // Make sure that a selection was provided selector = selector || document; // Handle $(DOMElement) if ( selector.nodeType ) { this[0] = selector; this.length = 1; this.context = selector; return this; } // Handle HTML strings if (typeof selector === "string") { // Are we dealing with HTML string or an ID? var 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]) selector = jQuery.clean([match[1]], context); // HANDLE: $("#id") else { var elem = document.getElementById(match[3]); // Handle the case where IE and Opera return items // by name instead of ID if (elem && elem.id != match[3]) return jQuery().find(selector); // Otherwise, we inject the element directly into the jQuery object var ret = jQuery(elem || []); ret.context = document; ret.selector = selector; return ret; } // HANDLE: $(expr, [context]) // (which is just equivalent to: $(content).find(expr) } else return jQuery(context).find(selector); // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) return jQuery( document ).ready( selector ); // Make sure that old selector state is passed along if ( selector.selector && selector.context ) { this.selector = selector.selector; this.context = selector.context; } return this.setArray(jQuery.isArray( selector ) ? selector : jQuery.makeArray(selector)); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.3.2", // The number of elements contained in the matched element set size: function() { /// <summary> /// The number of elements currently matched. /// Part of Core /// </summary> /// <returns type="Number" /> return this.length; }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { /// <summary> /// Access a single matched element. num is used to access the /// Nth element matched. /// Part of Core /// </summary> /// <returns type="Element" /> /// <param name="num" type="Number"> /// Access the element in the Nth position. /// </param> return num == undefined ? // Return a 'clean' array Array.prototype.slice.call( this ) : // Return just the object this[ num ]; }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { /// <summary> /// Set the jQuery object to an array of elements, while maintaining /// the stack. /// Part of Core /// </summary> /// <returns type="jQuery" /> /// <param name="elems" type="Elements"> /// An array of elements /// </param> // Build a new jQuery matched element set var ret = jQuery( 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; }, // Force the current matched set of elements to become // the specified array of elements (destroying the stack in the process) // You should use pushStack() in order to do this, but maintain the stack setArray: function( elems ) { /// <summary> /// Set the jQuery object to an array of elements. This operation is /// completely destructive - be sure to use .pushStack() if you wish to maintain /// the jQuery stack. /// Part of Core /// </summary> /// <returns type="jQuery" /> /// <param name="elems" type="Elements"> /// An array of elements /// </param> // Resetting the length to 0, then using the native Array push // is a super-fast way to populate an object with array-like properties this.length = 0; Array.prototype.push.apply( this, elems ); return this; }, // 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 ) { /// <summary> /// Execute a function within the context of every matched element. /// This means that every time the passed-in function is executed /// (which is once for every element matched) the 'this' keyword /// points to the specific element. /// Additionally, the function, when executed, is passed a single /// argument representing the position of the element in the matched /// set. /// Part of Core /// </summary> /// <returns type="jQuery" /> /// <param name="callback" type="Function"> /// A function to execute /// </param> return jQuery.each( this, callback, args ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { /// <summary> /// Searches every matched element for the object and returns /// the index of the element, if found, starting with zero. /// Returns -1 if the object wasn't found. /// Part of Core /// </summary> /// <returns type="Number" /> /// <param name="elem" type="Element"> /// Object to search for /// </param> // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem && elem.jquery ? elem[0] : elem , this ); }, attr: function( name, value, type ) { /// <summary> /// Set a single property to a computed value, on all matched elements. /// Instead of a value, a function is provided, that computes the value. /// Part of DOM/Attributes /// </summary> /// <returns type="jQuery" /> /// <param name="name" type="String"> /// The name of the property to set. /// </param> /// <param name="value" type="Function"> /// A function returning the value to set. /// </param> var options = name; // Look for the case where we're accessing a style value if ( typeof name === "string" ) if ( value === undefined ) return this[0] && jQuery[ type || "attr" ]( this[0], name ); else { options = {}; options[ name ] = value; } // Check to see if we're setting style values return this.each(function(i){ // Set all the styles for ( name in options ) jQuery.attr( type ? this.style : this, name, jQuery.prop( this, options[ name ], type, i, name ) ); }); }, css: function( key, value ) { /// <summary> /// Set a single style property to a value, on all matched elements. /// If a number is provided, it is automatically converted into a pixel value. /// Part of CSS /// </summary> /// <returns type="jQuery" /> /// <param name="key" type="String"> /// The name of the property to set. /// </param> /// <param name="value" type="String"> /// The value to set the property to. /// </param> // ignore negative width and height values if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 ) value = undefined; return this.attr( key, value, "curCSS" ); }, text: function( text ) { /// <summary> /// Set the text contents of all matched elements. /// Similar to html(), but escapes HTML (replace &quot;&lt;&quot; and &quot;&gt;&quot; with their /// HTML entities). /// Part of DOM/Attributes /// </summary> /// <returns type="String" /> /// <param name="text" type="String"> /// The text value to set the contents of the element to. /// </param> if ( typeof text !== "object" && text != null ) return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); var ret = ""; jQuery.each( text || this, function(){ jQuery.each( this.childNodes, function(){ if ( this.nodeType != 8 ) ret += this.nodeType != 1 ? this.nodeValue : jQuery.fn.text( [ this ] ); }); }); return ret; }, wrapAll: function( html ) { /// <summary> /// Wrap all matched elements with a structure of other elements. /// This wrapping process is most useful for injecting additional /// stucture into a document, without ruining the original semantic /// qualities of a document. /// This works by going through the first element /// provided and finding the deepest ancestor element within its /// structure - it is that element that will en-wrap everything else. /// This does not work with elements that contain text. Any necessary text /// must be added after the wrapping is done. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> /// <param name="html" type="Element"> /// A DOM element that will be wrapped around the target. /// </param> if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).clone(); if ( this[0].parentNode ) wrap.insertBefore( this[0] ); wrap.map(function(){ var elem = this; while ( elem.firstChild ) elem = elem.firstChild; return elem; }).append(this); } return this; }, wrapInner: function( html ) { /// <summary> /// Wraps the inner child contents of each matched elemenht (including text nodes) with an HTML structure. /// </summary> /// <param name="html" type="String"> /// A string of HTML or a DOM element that will be wrapped around the target contents. /// </param> /// <returns type="jQuery" /> return this.each(function(){ jQuery( this ).contents().wrapAll( html ); }); }, wrap: function( html ) { /// <summary> /// Wrap all matched elements with a structure of other elements. /// This wrapping process is most useful for injecting additional /// stucture into a document, without ruining the original semantic /// qualities of a document. /// This works by going through the first element /// provided and finding the deepest ancestor element within its /// structure - it is that element that will en-wrap everything else. /// This does not work with elements that contain text. Any necessary text /// must be added after the wrapping is done. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> /// <param name="html" type="Element"> /// A DOM element that will be wrapped around the target. /// </param> return this.each(function(){ jQuery( this ).wrapAll( html ); }); }, append: function() { /// <summary> /// Append content to the inside of every matched element. /// This operation is similar to doing an appendChild to all the /// specified elements, adding them into the document. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> /// <param name="content" type="Content"> /// Content to append to the target /// </param> return this.domManip(arguments, true, function(elem){ if (this.nodeType == 1) this.appendChild( elem ); }); }, prepend: function() { /// <summary> /// Prepend content to the inside of every matched element. /// This operation is the best way to insert elements /// inside, at the beginning, of all matched elements. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> /// <param name="" type="Content"> /// Content to prepend to the target. /// </param> return this.domManip(arguments, true, function(elem){ if (this.nodeType == 1) this.insertBefore( elem, this.firstChild ); }); }, before: function() { /// <summary> /// Insert content before each of the matched elements. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> /// <param name="" type="Content"> /// Content to insert before each target. /// </param> return this.domManip(arguments, false, function(elem){ this.parentNode.insertBefore( elem, this ); }); }, after: function() { /// <summary> /// Insert content after each of the matched elements. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> /// <param name="" type="Content"> /// Content to insert after each target. /// </param> return this.domManip(arguments, false, function(elem){ this.parentNode.insertBefore( elem, this.nextSibling ); }); }, end: function() { /// <summary> /// End the most recent 'destructive' operation, reverting the list of matched elements /// back to its previous state. After an end operation, the list of matched elements will /// revert to the last state of matched elements. /// If there was no destructive operation before, an empty set is returned. /// Part of DOM/Traversing /// </summary> /// <returns type="jQuery" /> return this.prevObject || jQuery( [] ); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: [].push, sort: [].sort, splice: [].splice, find: function( selector ) { /// <summary> /// Searches for all elements that match the specified expression. /// This method is a good way to find additional descendant /// elements with which to process. /// All searching is done using a jQuery expression. The expression can be /// written using CSS 1-3 Selector syntax, or basic XPath. /// Part of DOM/Traversing /// </summary> /// <returns type="jQuery" /> /// <param name="selector" type="String"> /// An expression to search with. /// </param> /// <returns type="jQuery" /> if ( this.length === 1 ) { var ret = this.pushStack( [], "find", selector ); ret.length = 0; jQuery.find( selector, this[0], ret ); return ret; } else { return this.pushStack( jQuery.unique(jQuery.map(this, function(elem){ return jQuery.find( selector, elem ); })), "find", selector ); } }, clone: function( events ) { /// <summary> /// Clone matched DOM Elements and select the clones. /// This is useful for moving copies of the elements to another /// location in the DOM. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> /// <param name="deep" type="Boolean" optional="true"> /// (Optional) Set to false if you don't want to clone all descendant nodes, in addition to the element itself. /// </param> // Do the clone var ret = this.map(function(){ if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { // IE copies events bound via attachEvent when // using cloneNode. Calling detachEvent on the // clone will also remove the events from the orignal // In order to get around this, we use innerHTML. // Unfortunately, this means some modifications to // attributes in IE that are actually only stored // as properties will not be copied (such as the // the name attribute on an input). var html = this.outerHTML; if ( !html ) { var div = this.ownerDocument.createElement("div"); div.appendChild( this.cloneNode(true) ); html = div.innerHTML; } return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")])[0]; } else return this.cloneNode(true); }); // Copy the events from the original to the clone if ( events === true ) { var orig = this.find("*").andSelf(), i = 0; ret.find("*").andSelf().each(function(){ if ( this.nodeName !== orig[i].nodeName ) return; var events = jQuery.data( orig[i], "events" ); for ( var type in events ) { for ( var handler in events[ type ] ) { jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); } } i++; }); } // Return the cloned set return ret; }, filter: function( selector ) { /// <summary> /// Removes all elements from the set of matched elements that do not /// pass the specified filter. This method is used to narrow down /// the results of a search. /// }) /// Part of DOM/Traversing /// </summary> /// <returns type="jQuery" /> /// <param name="selector" type="Function"> /// A function to use for filtering /// </param> /// <returns type="jQuery" /> return this.pushStack( jQuery.isFunction( selector ) && jQuery.grep(this, function(elem, i){ return selector.call( elem, i ); }) || jQuery.multiFilter( selector, jQuery.grep(this, function(elem){ return elem.nodeType === 1; }) ), "filter", selector ); }, closest: function( selector ) { /// <summary> /// Get a set of elements containing the closest parent element that matches the specified selector, the starting element included. /// </summary> /// <returns type="jQuery" /> /// <param name="selector" type="Function"> /// An expression to filter the elements with. /// </param> /// <returns type="jQuery" /> var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null, closer = 0; return this.map(function(){ var cur = this; while ( cur && cur.ownerDocument ) { if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) { jQuery.data(cur, "closest", closer); return cur; } cur = cur.parentNode; closer++; } }); }, not: function( selector ) { /// <summary> /// Removes any elements inside the array of elements from the set /// of matched elements. This method is used to remove one or more /// elements from a jQuery object. /// Part of DOM/Traversing /// </summary> /// <param name="selector" type="jQuery"> /// A set of elements to remove from the jQuery set of matched elements. /// </param> /// <returns type="jQuery" /> if ( typeof selector === "string" ) // test special case where just one selector is passed in if ( isSimple.test( selector ) ) return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector ); else selector = jQuery.multiFilter( selector, this ); var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType; return this.filter(function() { return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector; }); }, add: function( selector ) { /// <summary> /// Adds one or more Elements to the set of matched elements. /// Part of DOM/Traversing /// </summary> /// <param name="elements" type="Element"> /// One or more Elements to add /// </param> /// <returns type="jQuery" /> return this.pushStack( jQuery.unique( jQuery.merge( this.get(), typeof selector === "string" ? jQuery( selector ) : jQuery.makeArray( selector ) ))); }, is: function( selector ) { /// <summary> /// Checks the current selection against an expression and returns true, /// if at least one element of the selection fits the given expression. /// Does return false, if no element fits or the expression is not valid. /// filter(String) is used internally, therefore all rules that apply there /// apply here, too. /// Part of DOM/Traversing /// </summary> /// <returns type="Boolean" /> /// <param name="expr" type="String"> /// The expression with which to filter /// </param> return !!selector && jQuery.multiFilter( selector, this ).length > 0; }, hasClass: function( selector ) { /// <summary> /// Checks the current selection against a class and returns whether at least one selection has a given class. /// </summary> /// <param name="selector" type="String">The class to check against</param> /// <returns type="Boolean">True if at least one element in the selection has the class, otherwise false.</returns> return !!selector && this.is( "." + selector ); }, val: function( value ) { /// <summary> /// Set the value of every matched element. /// Part of DOM/Attributes /// </summary> /// <returns type="jQuery" /> /// <param name="val" type="String"> /// Set the property to the specified value. /// </param> if ( value === undefined ) { var elem = this[0]; if ( elem ) { if( jQuery.nodeName( elem, 'option' ) ) return (elem.attributes.value || {}).specified ? elem.value : elem.text; // We need to handle select boxes special if ( jQuery.nodeName( elem, "select" ) ) { var index = elem.selectedIndex, values = [], options = elem.options, one = elem.type == "select-one"; // Nothing was selected if ( index < 0 ) return null; // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; if ( option.selected ) { // Get the specifc 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 ); } } return values; } // Everything else, we just grab the value return (elem.value || "").replace(/\r/g, ""); } return undefined; } if ( typeof value === "number" ) value += ''; return this.each(function(){ if ( this.nodeType != 1 ) return; if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) ) this.checked = (jQuery.inArray(this.value, value) >= 0 || jQuery.inArray(this.name, value) >= 0); else if ( jQuery.nodeName( this, "select" ) ) { var values = jQuery.makeArray(value); jQuery( "option", this ).each(function(){ this.selected = (jQuery.inArray( this.value, values ) >= 0 || jQuery.inArray( this.text, values ) >= 0); }); if ( !values.length ) this.selectedIndex = -1; } else this.value = value; }); }, html: function( value ) { /// <summary> /// Set the html contents of every matched element. /// This property is not available on XML documents. /// Part of DOM/Attributes /// </summary> /// <returns type="jQuery" /> /// <param name="val" type="String"> /// Set the html contents to the specified value. /// </param> return value === undefined ? (this[0] ? this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") : null) : this.empty().append( value ); }, replaceWith: function( value ) { /// <summary> /// Replaces all matched element with the specified HTML or DOM elements. /// </summary> /// <param name="value" type="String"> /// The content with which to replace the matched elements. /// </param> /// <returns type="jQuery">The element that was just replaced.</returns> return this.after( value ).remove(); }, eq: function( i ) { /// <summary> /// Reduce the set of matched elements to a single element. /// The position of the element in the set of matched elements /// starts at 0 and goes to length - 1. /// Part of Core /// </summary> /// <returns type="jQuery" /> /// <param name="num" type="Number"> /// pos The index of the element that you wish to limit to. /// </param> return this.slice( i, +i + 1 ); }, slice: function() { /// <summary> /// Selects a subset of the matched elements. Behaves exactly like the built-in Array slice method. /// </summary> /// <param name="start" type="Number" integer="true">Where to start the subset (0-based).</param> /// <param name="end" optional="true" type="Number" integer="true">Where to end the subset (not including the end element itself). /// If omitted, ends at the end of the selection</param> /// <returns type="jQuery">The sliced elements</returns> return this.pushStack( Array.prototype.slice.apply( this, arguments ), "slice", Array.prototype.slice.call(arguments).join(",") ); }, map: function( callback ) { /// <summary> /// This member is internal. /// </summary> /// <private /> /// <returns type="jQuery" /> return this.pushStack( jQuery.map(this, function(elem, i){ return callback.call( elem, i, elem ); })); }, andSelf: function() { /// <summary> /// Adds the previous selection to the current selection. /// </summary> /// <returns type="jQuery" /> return this.add( this.prevObject ); }, domManip: function( args, table, callback ) { /// <param name="args" type="Array"> /// Args /// </param> /// <param name="table" type="Boolean"> /// Insert TBODY in TABLEs if one is not found. /// </param> /// <param name="dir" type="Number"> /// If dir&lt;0, process args in reverse order. /// </param> /// <param name="fn" type="Function"> /// The function doing the DOM manipulation. /// </param> /// <returns type="jQuery" /> /// <summary> /// Part of Core /// </summary> if ( this[0] ) { var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(), scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ), first = fragment.firstChild; if ( first ) for ( var i = 0, l = this.length; i < l; i++ ) callback.call( root(this[i], first), this.length > 1 || i > 0 ? fragment.cloneNode(true) : fragment ); if ( scripts ) jQuery.each( scripts, evalScript ); } return this; function root( elem, cur ) { return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } } }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; function evalScript( i, elem ) { /// <summary> /// This method is internal. /// </summary> /// <private /> if ( elem.src ) jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); else jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); if ( elem.parentNode ) elem.parentNode.removeChild( elem ); } function now(){ /// <summary> /// Gets the current date. /// </summary> /// <returns type="Date">The current date.</returns> return +new Date; } jQuery.extend = jQuery.fn.extend = function() { /// <summary> /// Extend one object with one or more others, returning the original, /// modified, object. This is a great utility for simple inheritance. /// jQuery.extend(settings, options); /// var settings = jQuery.extend({}, defaults, options); /// Part of JavaScript /// </summary> /// <param name="target" type="Object"> /// The object to extend /// </param> /// <param name="prop1" type="Object"> /// The object that will be merged into the first. /// </param> /// <param name="propN" type="Object" optional="true" parameterArray="true"> /// (optional) More objects to merge into the first /// </param> /// <returns type="Object" /> // copy reference to target object var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options; // 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 ( var name in options ) { var src = target[ name ], copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) continue; // Recurse if we're merging object values if ( deep && copy && typeof copy === "object" && !copy.nodeType ) target[ name ] = jQuery.extend( deep, // Never move original objects, clone them src || ( copy.length != null ? [ ] : { } ) , copy ); // Don't bring in undefined values else if ( copy !== undefined ) target[ name ] = copy; } // Return the modified object return target; }; // exclude the following css properties to add px var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, // cache defaultView defaultView = document.defaultView || {}, toString = Object.prototype.toString; jQuery.extend({ noConflict: function( deep ) { /// <summary> /// Run this function to give control of the $ variable back /// to whichever library first implemented it. This helps to make /// sure that jQuery doesn't conflict with the $ object /// of other libraries. /// By using this function, you will only be able to access jQuery /// using the 'jQuery' variable. For example, where you used to do /// $(&quot;div p&quot;), you now must do jQuery(&quot;div p&quot;). /// Part of Core /// </summary> /// <returns type="undefined" /> window.$ = _$; if ( deep ) window.jQuery = _jQuery; return jQuery; }, // 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 ) { /// <summary> /// Determines if the parameter passed is a function. /// </summary> /// <param name="obj" type="Object">The object to check</param> /// <returns type="Boolean">True if the parameter is a function; otherwise false.</returns> return toString.call(obj) === "[object Function]"; }, isArray: function(obj) { /// <summary> /// Determine if the parameter passed is an array. /// </summary> /// <param name="obj" type="Object">Object to test whether or not it is an array.</param> /// <returns type="Boolean">True if the parameter is a function; otherwise false.</returns> return toString.call(obj) === "[object Array]"; }, // check if an element is in a (or is an) XML document isXMLDoc: function( elem ) { /// <summary> /// Determines if the parameter passed is an XML document. /// </summary> /// <param name="elem" type="Object">The object to test</param> /// <returns type="Boolean">True if the parameter is an XML document; otherwise false.</returns> return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" || !!elem.ownerDocument && jQuery.isXMLDoc(elem.ownerDocument); }, // Evalulates a script in a global context globalEval: function( data ) { /// <summary> /// Internally evaluates a script in a global context. /// </summary> /// <private /> if ( data && /\S/.test(data) ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; if ( jQuery.support.scriptEval ) script.appendChild( document.createTextNode( data ) ); else script.text = data; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } }, nodeName: function( elem, name ) { /// <summary> /// Checks whether the specified element has the specified DOM node name. /// </summary> /// <param name="elem" type="Element">The element to examine</param> /// <param name="name" type="String">The node name to check</param> /// <returns type="Boolean">True if the specified node name matches the node's DOM node name; otherwise false</returns> return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { /// <summary> /// A generic iterator function, which can be used to seemlessly /// iterate over both objects and arrays. This function is not the same /// as $().each() - which is used to iterate, exclusively, over a jQuery /// object. This function can be used to iterate over anything. /// The callback has two arguments:the key (objects) or index (arrays) as first /// the first, and the value as the second. /// Part of JavaScript /// </summary> /// <param name="obj" type="Object"> /// The object, or array, to iterate over. /// </param> /// <param name="fn" type="Function"> /// The function that will be executed on every object. /// </param> /// <returns type="Object" /> var name, i = 0, length = object.length; if ( args ) { if ( length === undefined ) { 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 ( length === undefined ) { for ( name in object ) if ( callback.call( object[ name ], name, object[ name ] ) === false ) break; } else for ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ){} } return object; }, prop: function( elem, value, type, i, name ) { /// <summary> /// This method is internal. /// </summary> /// <private /> // This member is not documented within the jQuery API: http://docs.jquery.com/action/edit/Internals/jQuery.prop // Handle executable functions if ( jQuery.isFunction( value ) ) value = value.call( elem, i ); // Handle passing in a number to a CSS property return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ? value + "px" : value; }, className: { // internal only, use addClass("class") add: function( elem, classNames ) { /// <summary> /// Internal use only; use addClass('class') /// </summary> /// <private /> jQuery.each((classNames || "").split(/\s+/), function(i, className){ if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) ) elem.className += (elem.className ? " " : "") + className; }); }, // internal only, use removeClass("class") remove: function( elem, classNames ) { /// <summary> /// Internal use only; use removeClass('class') /// </summary> /// <private /> if (elem.nodeType == 1) elem.className = classNames !== undefined ? jQuery.grep(elem.className.split(/\s+/), function(className){ return !jQuery.className.has( classNames, className ); }).join(" ") : ""; }, // internal only, use hasClass("class") has: function( elem, className ) { /// <summary> /// Internal use only; use hasClass('class') /// </summary> /// <private /> return elem && jQuery.inArray(className, (elem.className || elem).toString().split(/\s+/)) > -1; } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { /// <summary> /// Swap in/out style options. /// </summary> var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( var name in options ) elem.style[ name ] = old[ name ]; }, css: function( elem, name, force, extra ) { /// <summary> /// This method is internal only. /// </summary> /// <private /> // This method is undocumented in jQuery API: http://docs.jquery.com/action/edit/Internals/jQuery.css if ( name == "width" || name == "height" ) { var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ]; function getWH() { val = name == "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) return; jQuery.each( which, function() { if ( !extra ) val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; if ( extra === "margin" ) val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0; else val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; }); } if ( elem.offsetWidth !== 0 ) getWH(); else jQuery.swap( elem, props, getWH ); return Math.max(0, Math.round(val)); } return jQuery.curCSS( elem, name, force ); }, curCSS: function( elem, name, force ) { /// <summary> /// This method is internal only. /// </summary> /// <private /> // This method is undocumented in jQuery API: http://docs.jquery.com/action/edit/Internals/jQuery.curCSS var ret, style = elem.style; // We need to handle opacity special in IE if ( name == "opacity" && !jQuery.support.opacity ) { ret = jQuery.attr( style, "opacity" ); return ret == "" ? "1" : ret; } // Make sure we're using the right name for getting the float value if ( name.match( /float/i ) ) name = styleFloat; if ( !force && style && style[ name ] ) ret = style[ name ]; else if ( defaultView.getComputedStyle ) { // Only "float" is needed here if ( name.match( /float/i ) ) name = "float"; name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase(); var computedStyle = defaultView.getComputedStyle( elem, null ); if ( computedStyle ) ret = computedStyle.getPropertyValue( name ); // We should always get a number back from opacity if ( name == "opacity" && ret == "" ) ret = "1"; } else if ( elem.currentStyle ) { var camelCase = name.replace(/\-(\w)/g, function(all, letter){ return letter.toUpperCase(); }); ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; // 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 ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) { // Remember the original values var left = style.left, rsLeft = elem.runtimeStyle.left; // Put in the new values to get a computed value out elem.runtimeStyle.left = elem.currentStyle.left; style.left = ret || 0; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; elem.runtimeStyle.left = rsLeft; } } return ret; }, clean: function( elems, context, fragment ) { /// <summary> /// This method is internal only. /// </summary> /// <private /> // This method is undocumented in the jQuery API: http://docs.jquery.com/action/edit/Internals/jQuery.clean 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; // If a single string is passed in and it's a single tag // just do a createElement and skip the rest if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) { var match = /^<(\w+)\s*\/?>$/.exec(elems[0]); if ( match ) return [ context.createElement( match[1] ) ]; } var ret = [], scripts = [], div = context.createElement("div"); jQuery.each(elems, function(i, elem){ if ( typeof elem === "number" ) elem += ''; if ( !elem ) return; // Convert html string into DOM nodes if ( typeof elem === "string" ) { // Fix "XHTML"-style tags in all browsers elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){ return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ? all : front + "></" + tag + ">"; }); // Trim whitespace, otherwise indexOf won't work as expected var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase(); var wrap = // option or optgroup !tags.indexOf("<opt") && [ 1, "<select multiple='multiple'>", "</select>" ] || !tags.indexOf("<leg") && [ 1, "<fieldset>", "</fieldset>" ] || tags.match(/^<(thead|tbody|tfoot|colg|cap)/) && [ 1, "<table>", "</table>" ] || !tags.indexOf("<tr") && [ 2, "<table><tbody>", "</tbody></table>" ] || // <thead> matched above (!tags.indexOf("<td") || !tags.indexOf("<th")) && [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] || !tags.indexOf("<col") && [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] || // IE can't serialize <link> and <script> tags normally !jQuery.support.htmlSerialize && [ 1, "div<div>", "</div>" ] || [ 0, "", "" ]; // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( wrap[0]-- ) 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 = /<tbody/i.test(elem), tbody = !tags.indexOf("<table") && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] == "<table>" && !hasBody ? div.childNodes : []; for ( var 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 && /^\s/.test( elem ) ) div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild ); elem = jQuery.makeArray( div.childNodes ); } if ( elem.nodeType ) ret.push( elem ); else ret = jQuery.merge( ret, elem ); }); if ( fragment ) { for ( var i = 0; ret[i]; i++ ) { if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); fragment.appendChild( ret[i] ); } } return scripts; } return ret; }, attr: function( elem, name, value ) { /// <summary> /// This method is internal. /// </summary> /// <private /> // don't set attributes on text and comment nodes if (!elem || elem.nodeType == 3 || elem.nodeType == 8) return undefined; var notxml = !jQuery.isXMLDoc( elem ), // Whether we are setting (or getting) set = value !== undefined; // Try to normalize/fix the name name = notxml && jQuery.props[ name ] || name; // Only do all the following if this is a node (faster for style) // IE elem.getAttribute passes even for style if ( elem.tagName ) { // These attributes require special treatment var special = /href|src|style/.test( name ); // Safari mis-reports the default selected property of a hidden option // Accessing the parent's selectedIndex property fixes it if ( name == "selected" && elem.parentNode ) elem.parentNode.selectedIndex; // If applicable, access the attribute via the DOM 0 way if ( name in elem && notxml && !special ) { if ( set ){ // We can't allow the type property to be changed (since it causes problems in IE) if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode ) throw "type property can't be changed"; elem[ name ] = value; } // browsers index elements by id/name on forms, give priority to attributes. if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) return elem.getAttributeNode( name ).nodeValue; // 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/ if ( name == "tabIndex" ) { var attributeNode = elem.getAttributeNode( "tabIndex" ); return attributeNode && attributeNode.specified ? attributeNode.value : elem.nodeName.match(/(button|input|object|select|textarea)/i) ? 0 : elem.nodeName.match(/^(a|area)$/i) && elem.href ? 0 : undefined; } return elem[ name ]; } if ( !jQuery.support.style && notxml && name == "style" ) return jQuery.attr( elem.style, "cssText", value ); if ( set ) // convert the value to a string (all browsers do this but IE) see #1070 elem.setAttribute( name, "" + value ); var attr = !jQuery.support.hrefNormalized && notxml && special // Some attributes require a special call on IE ? elem.getAttribute( name, 2 ) : elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return attr === null ? undefined : attr; } // elem is actually elem.style ... set the style // IE uses filters for opacity if ( !jQuery.support.opacity && name == "opacity" ) { if ( set ) { // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level elem.zoom = 1; // Set the alpha filter to set the opacity elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) + (parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")"); } return elem.filter && elem.filter.indexOf("opacity=") >= 0 ? (parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '': ""; } name = name.replace(/-([a-z])/ig, function(all, letter){ return letter.toUpperCase(); }); if ( set ) elem[ name ] = value; return elem[ name ]; }, trim: function( text ) { /// <summary> /// Remove the whitespace from the beginning and end of a string. /// Part of JavaScript /// </summary> /// <returns type="String" /> /// <param name="text" type="String"> /// The string to trim. /// </param> return (text || "").replace( /^\s+|\s+$/g, "" ); }, makeArray: function( array ) { /// <summary> /// Turns anything into a true array. This is an internal method. /// </summary> /// <param name="array" type="Object">Anything to turn into an actual Array</param> /// <returns type="Array" /> /// <private /> var ret = []; if( array != null ){ var i = array.length; // The window, strings (and functions) also have 'length' if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval ) ret[0] = array; else while( i ) ret[--i] = array[i]; } return ret; }, inArray: function( elem, array ) { /// <summary> /// Determines the index of the first parameter in the array. /// </summary> /// <param name="elem">The value to see if it exists in the array.</param> /// <param name="array" type="Array">The array to look through for the value</param> /// <returns type="Number" integer="true">The 0-based index of the item if it was found, otherwise -1.</returns> for ( var i = 0, length = array.length; i < length; i++ ) // Use === because on IE, window == document if ( array[ i ] === elem ) return i; return -1; }, merge: function( first, second ) { /// <summary> /// Merge two arrays together, removing all duplicates. /// The new array is: All the results from the first array, followed /// by the unique results from the second array. /// Part of JavaScript /// </summary> /// <returns type="Array" /> /// <param name="first" type="Array"> /// The first array to merge. /// </param> /// <param name="second" type="Array"> /// The second array to merge. /// </param> // We have to loop this way because IE & Opera overwrite the length // expando of getElementsByTagName var i = 0, elem, pos = first.length; // Also, we need to make sure that the correct elements are being returned // (IE returns comment nodes in a '*' query) if ( !jQuery.support.getAll ) { while ( (elem = second[ i++ ]) != null ) if ( elem.nodeType != 8 ) first[ pos++ ] = elem; } else while ( (elem = second[ i++ ]) != null ) first[ pos++ ] = elem; return first; }, unique: function( array ) { /// <summary> /// Removes all duplicate elements from an array of elements. /// </summary> /// <param name="array" type="Array&lt;Element&gt;">The array to translate</param> /// <returns type="Array&lt;Element&gt;">The array after translation.</returns> var ret = [], done = {}; try { for ( var i = 0, length = array.length; i < length; i++ ) { var id = jQuery.data( array[ i ] ); if ( !done[ id ] ) { done[ id ] = true; ret.push( array[ i ] ); } } } catch( e ) { ret = array; } return ret; }, grep: function( elems, callback, inv ) { /// <summary> /// Filter items out of an array, by using a filter function. /// The specified function will be passed two arguments: The /// current array item and the index of the item in the array. The /// function must return 'true' to keep the item in the array, /// false to remove it. /// }); /// Part of JavaScript /// </summary> /// <returns type="Array" /> /// <param name="elems" type="Array"> /// array The Array to find items in. /// </param> /// <param name="fn" type="Function"> /// The function to process each item against. /// </param> /// <param name="inv" type="Boolean"> /// Invert the selection - select the opposite of the function. /// </param> var ret = []; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) if ( !inv != !callback( elems[ i ], i ) ) ret.push( elems[ i ] ); return ret; }, map: function( elems, callback ) { /// <summary> /// Translate all items in an array to another array of items. /// The translation function that is provided to this method is /// called for each item in the array and is passed one argument: /// The item to be translated. /// The function can then return the translated value, 'null' /// (to remove the item), or an array of values - which will /// be flattened into the full array. /// Part of JavaScript /// </summary> /// <returns type="Array" /> /// <param name="elems" type="Array"> /// array The Array to translate. /// </param> /// <param name="fn" type="Function"> /// The function to process each item against. /// </param> var ret = []; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, length = elems.length; i < length; i++ ) { var value = callback( elems[ i ], i ); if ( value != null ) ret[ ret.length ] = value; } return ret.concat.apply( [], ret ); } }); // Use of jQuery.browser is deprecated. // It's included for backwards compatibility and plugins, // although they should work to migrate away. var userAgent = navigator.userAgent.toLowerCase(); // Figure out what browser is being used jQuery.browser = { version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1], safari: /webkit/.test( userAgent ), opera: /opera/.test( userAgent ), msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ), mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent ) }; // [vsdoc] The following section has been denormalized from original sources for IntelliSense. // jQuery.each({ // parent: function(elem){return elem.parentNode;}, // parents: function(elem){return jQuery.dir(elem,"parentNode");}, // 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");}, // 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( selector ) { // /// <summary> // /// Get a set of elements containing the unique parents of the matched // /// set of elements. // /// Can be filtered with an optional expressions. // /// Part of DOM/Traversing // /// </summary> // /// <param name="expr" type="String" optional="true"> // /// (optional) An expression to filter the parents with // /// </param> // /// <returns type="jQuery" /> // // var ret = jQuery.map( this, fn ); // // if ( selector && typeof selector == "string" ) // ret = jQuery.multiFilter( selector, ret ); // // return this.pushStack( jQuery.unique( ret ), name, selector ); // }; // }); jQuery.each({ parent: function(elem){return elem.parentNode;} }, function(name, fn){ jQuery.fn[ name ] = function( selector ) { /// <summary> /// Get a set of elements containing the unique parents of the matched /// set of elements. /// Can be filtered with an optional expressions. /// Part of DOM/Traversing /// </summary> /// <param name="expr" type="String" optional="true"> /// (optional) An expression to filter the parents with /// </param> /// <returns type="jQuery" /> var ret = jQuery.map( this, fn ); if ( selector && typeof selector == "string" ) ret = jQuery.multiFilter( selector, ret ); return this.pushStack( jQuery.unique( ret ), name, selector ); }; }); jQuery.each({ parents: function(elem){return jQuery.dir(elem,"parentNode");} }, function(name, fn){ jQuery.fn[ name ] = function( selector ) { /// <summary> /// Get a set of elements containing the unique ancestors of the matched /// set of elements (except for the root element). /// Can be filtered with an optional expressions. /// Part of DOM/Traversing /// </summary> /// <param name="expr" type="String" optional="true"> /// (optional) An expression to filter the ancestors with /// </param> /// <returns type="jQuery" /> var ret = jQuery.map( this, fn ); if ( selector && typeof selector == "string" ) ret = jQuery.multiFilter( selector, ret ); return this.pushStack( jQuery.unique( ret ), name, selector ); }; }); jQuery.each({ next: function(elem){return jQuery.nth(elem,2,"nextSibling");} }, function(name, fn){ jQuery.fn[ name ] = function( selector ) { /// <summary> /// Get a set of elements containing the unique next siblings of each of the /// matched set of elements. /// It only returns the very next sibling, not all next siblings. /// Can be filtered with an optional expressions. /// Part of DOM/Traversing /// </summary> /// <param name="expr" type="String" optional="true"> /// (optional) An expression to filter the next Elements with /// </param> /// <returns type="jQuery" /> var ret = jQuery.map( this, fn ); if ( selector && typeof selector == "string" ) ret = jQuery.multiFilter( selector, ret ); return this.pushStack( jQuery.unique( ret ), name, selector ); }; }); jQuery.each({ prev: function(elem){return jQuery.nth(elem,2,"previousSibling");} }, function(name, fn){ jQuery.fn[ name ] = function( selector ) { /// <summary> /// Get a set of elements containing the unique previous siblings of each of the /// matched set of elements. /// Can be filtered with an optional expressions. /// It only returns the immediately previous sibling, not all previous siblings. /// Part of DOM/Traversing /// </summary> /// <param name="expr" type="String" optional="true"> /// (optional) An expression to filter the previous Elements with /// </param> /// <returns type="jQuery" /> var ret = jQuery.map( this, fn ); if ( selector && typeof selector == "string" ) ret = jQuery.multiFilter( selector, ret ); return this.pushStack( jQuery.unique( ret ), name, selector ); }; }); jQuery.each({ nextAll: function(elem){return jQuery.dir(elem,"nextSibling");} }, function(name, fn){ jQuery.fn[name] = function(selector) { /// <summary> /// Finds all sibling elements after the current element. /// Can be filtered with an optional expressions. /// Part of DOM/Traversing /// </summary> /// <param name="expr" type="String" optional="true"> /// (optional) An expression to filter the next Elements with /// </param> /// <returns type="jQuery" /> var ret = jQuery.map( this, fn ); if ( selector && typeof selector == "string" ) ret = jQuery.multiFilter( selector, ret ); return this.pushStack( jQuery.unique( ret ), name, selector ); }; }); jQuery.each({ prevAll: function(elem){return jQuery.dir(elem,"previousSibling");} }, function(name, fn){ jQuery.fn[ name ] = function( selector ) { /// <summary> /// Finds all sibling elements before the current element. /// Can be filtered with an optional expressions. /// Part of DOM/Traversing /// </summary> /// <param name="expr" type="String" optional="true"> /// (optional) An expression to filter the previous Elements with /// </param> /// <returns type="jQuery" /> var ret = jQuery.map( this, fn ); if ( selector && typeof selector == "string" ) ret = jQuery.multiFilter( selector, ret ); return this.pushStack( jQuery.unique( ret ), name, selector ); }; }); jQuery.each({ siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);} }, function(name, fn){ jQuery.fn[ name ] = function( selector ) { /// <summary> /// Get a set of elements containing all of the unique siblings of each of the /// matched set of elements. /// Can be filtered with an optional expressions. /// Part of DOM/Traversing /// </summary> /// <param name="expr" type="String" optional="true"> /// (optional) An expression to filter the sibling Elements with /// </param> /// <returns type="jQuery" /> var ret = jQuery.map( this, fn ); if ( selector && typeof selector == "string" ) ret = jQuery.multiFilter( selector, ret ); return this.pushStack( jQuery.unique( ret ), name, selector ); }; }); jQuery.each({ children: function(elem){return jQuery.sibling(elem.firstChild);} }, function(name, fn){ jQuery.fn[ name ] = function( selector ) { /// <summary> /// Get a set of elements containing all of the unique children of each of the /// matched set of elements. /// Can be filtered with an optional expressions. /// Part of DOM/Traversing /// </summary> /// <param name="expr" type="String" optional="true"> /// (optional) An expression to filter the child Elements with /// </param> /// <returns type="jQuery" /> var ret = jQuery.map( this, fn ); if ( selector && typeof selector == "string" ) ret = jQuery.multiFilter( selector, ret ); return this.pushStack( jQuery.unique( ret ), name, selector ); }; }); jQuery.each({ contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);} }, function(name, fn){ jQuery.fn[ name ] = function( selector ) { /// <summary>Finds all the child nodes inside the matched elements including text nodes, or the content document if the element is an iframe.</summary> /// <returns type="jQuery" /> var ret = jQuery.map( this, fn ); if ( selector && typeof selector == "string" ) ret = jQuery.multiFilter( selector, ret ); return this.pushStack( jQuery.unique( ret ), name, selector ); }; }); // [vsdoc] The following section has been denormalized from original sources for IntelliSense. // jQuery.each({ // appendTo: "append", // prependTo: "prepend", // insertBefore: "before", // insertAfter: "after", // replaceAll: "replaceWith" // }, function(name, original){ // jQuery.fn[ name ] = function() { // var args = arguments; // // return this.each(function(){ // for ( var i = 0, length = args.length; i < length; i++ ) // jQuery( args[ i ] )[ original ]( this ); // }); // }; // }); jQuery.fn.appendTo = function( selector ) { /// <summary> /// Append all of the matched elements to another, specified, set of elements. /// As of jQuery 1.3.2, returns all of the inserted elements. /// This operation is, essentially, the reverse of doing a regular /// $(A).append(B), in that instead of appending B to A, you're appending /// A to B. /// </summary> /// <param name="selector" type="Selector"> /// target to which the content will be appended. /// </param> /// <returns type="jQuery" /> var ret = [], insert = jQuery( selector ); for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ "append" ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, "appendTo", selector ); }; jQuery.fn.prependTo = function( selector ) { /// <summary> /// Prepend all of the matched elements to another, specified, set of elements. /// As of jQuery 1.3.2, returns all of the inserted elements. /// This operation is, essentially, the reverse of doing a regular /// $(A).prepend(B), in that instead of prepending B to A, you're prepending /// A to B. /// </summary> /// <param name="selector" type="Selector"> /// target to which the content will be appended. /// </param> /// <returns type="jQuery" /> var ret = [], insert = jQuery( selector ); for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ "prepend" ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, "prependTo", selector ); }; jQuery.fn.insertBefore = function( selector ) { /// <summary> /// Insert all of the matched elements before another, specified, set of elements. /// As of jQuery 1.3.2, returns all of the inserted elements. /// This operation is, essentially, the reverse of doing a regular /// $(A).before(B), in that instead of inserting B before A, you're inserting /// A before B. /// </summary> /// <param name="content" type="String"> /// Content after which the selected element(s) is inserted. /// </param> /// <returns type="jQuery" /> var ret = [], insert = jQuery( selector ); for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ "before" ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, "insertBefore", selector ); }; jQuery.fn.insertAfter = function( selector ) { /// <summary> /// Insert all of the matched elements after another, specified, set of elements. /// As of jQuery 1.3.2, returns all of the inserted elements. /// This operation is, essentially, the reverse of doing a regular /// $(A).after(B), in that instead of inserting B after A, you're inserting /// A after B. /// </summary> /// <param name="content" type="String"> /// Content after which the selected element(s) is inserted. /// </param> /// <returns type="jQuery" /> var ret = [], insert = jQuery( selector ); for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ "after" ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, "insertAfter", selector ); }; jQuery.fn.replaceAll = function( selector ) { /// <summary> /// Replaces the elements matched by the specified selector with the matched elements. /// As of jQuery 1.3.2, returns all of the inserted elements. /// </summary> /// <param name="selector" type="Selector">The elements to find and replace the matched elements with.</param> /// <returns type="jQuery" /> var ret = [], insert = jQuery( selector ); for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ "replaceWith" ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, "replaceAll", selector ); }; // [vsdoc] The following section has been denormalized from original sources for IntelliSense. // jQuery.each({ // removeAttr: function( name ) { // jQuery.attr( this, name, "" ); // if (this.nodeType == 1) // this.removeAttribute( name ); // }, // // addClass: function( classNames ) { // jQuery.className.add( this, classNames ); // }, // // removeClass: function( classNames ) { // jQuery.className.remove( this, classNames ); // }, // // toggleClass: function( classNames, state ) { // if( typeof state !== "boolean" ) // state = !jQuery.className.has( this, classNames ); // jQuery.className[ state ? "add" : "remove" ]( this, classNames ); // }, // // remove: function( selector ) { // if ( !selector || jQuery.filter( selector, [ this ] ).length ) { // // Prevent memory leaks // jQuery( "*", this ).add([this]).each(function(){ // jQuery.event.remove(this); // jQuery.removeData(this); // }); // if (this.parentNode) // this.parentNode.removeChild( this ); // } // }, // // empty: function() { // // Remove element nodes and prevent memory leaks // jQuery( ">*", this ).remove(); // // // Remove any remaining nodes // while ( this.firstChild ) // this.removeChild( this.firstChild ); // } // }, function(name, fn){ // jQuery.fn[ name ] = function(){ // return this.each( fn, arguments ); // }; // }); jQuery.fn.removeAttr = function(){ /// <summary> /// Remove an attribute from each of the matched elements. /// Part of DOM/Attributes /// </summary> /// <param name="key" type="String"> /// name The name of the attribute to remove. /// </param> /// <returns type="jQuery" /> return this.each( function( name ) { jQuery.attr( this, name, "" ); if (this.nodeType == 1) this.removeAttribute( name ); }, arguments ); }; jQuery.fn.addClass = function(){ /// <summary> /// Adds the specified class(es) to each of the set of matched elements. /// Part of DOM/Attributes /// </summary> /// <param name="classNames" type="String"> /// lass One or more CSS classes to add to the elements /// </param> /// <returns type="jQuery" /> return this.each( function( classNames ) { jQuery.className.add( this, classNames ); }, arguments ); }; jQuery.fn.removeClass = function(){ /// <summary> /// Removes all or the specified class(es) from the set of matched elements. /// Part of DOM/Attributes /// </summary> /// <param name="cssClasses" type="String" optional="true"> /// (Optional) One or more CSS classes to remove from the elements /// </param> /// <returns type="jQuery" /> return this.each( function( classNames ) { jQuery.className.remove( this, classNames ); }, arguments ); }; jQuery.fn.toggleClass = function(){ /// <summary> /// Adds the specified class if it is not present, removes it if it is /// present. /// Part of DOM/Attributes /// </summary> /// <param name="cssClass" type="String"> /// A CSS class with which to toggle the elements /// </param> /// <returns type="jQuery" /> return this.each( function( classNames, state ) { if( typeof state !== "boolean" ) state = !jQuery.className.has( this, classNames ); jQuery.className[ state ? "add" : "remove" ]( this, classNames ); }, arguments ); }; jQuery.fn.remove = function(){ /// <summary> /// Removes all matched elements from the DOM. This does NOT remove them from the /// jQuery object, allowing you to use the matched elements further. /// Can be filtered with an optional expressions. /// Part of DOM/Manipulation /// </summary> /// <param name="expr" type="String" optional="true"> /// (optional) A jQuery expression to filter elements by. /// </param> /// <returns type="jQuery" /> return this.each( function( selector ) { if ( !selector || jQuery.filter( selector, [ this ] ).length ) { // Prevent memory leaks jQuery( "*", this ).add([this]).each(function(){ jQuery.event.remove(this); jQuery.removeData(this); }); if (this.parentNode) this.parentNode.removeChild( this ); } }, arguments ); }; jQuery.fn.empty = function(){ /// <summary> /// Removes all child nodes from the set of matched elements. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> return this.each( function() { // Remove element nodes and prevent memory leaks jQuery(this).children().remove(); // Remove any remaining nodes while ( this.firstChild ) this.removeChild( this.firstChild ); }, arguments ); }; // Helper function used by the dimensions and offset modules function num(elem, prop) { return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0; } var expando = "jQuery" + now(), uuid = 0, windowData = {}; jQuery.extend({ cache: {}, data: function( elem, name, data ) { elem = elem == window ? windowData : elem; var id = elem[ expando ]; // Compute a unique ID for the element if ( !id ) id = elem[ expando ] = ++uuid; // Only generate the data cache if we're // trying to access or manipulate it if ( name && !jQuery.cache[ id ] ) jQuery.cache[ id ] = {}; // Prevent overriding the named cache with undefined values if ( data !== undefined ) jQuery.cache[ id ][ name ] = data; // Return the named cache data, or the ID for the element return name ? jQuery.cache[ id ][ name ] : id; }, removeData: function( elem, name ) { elem = elem == window ? windowData : elem; var id = elem[ expando ]; // If we want to remove a specific section of the element's data if ( name ) { if ( jQuery.cache[ id ] ) { // Remove the section of cache data delete jQuery.cache[ id ][ name ]; // If we've removed all the data, remove the element's cache name = ""; for ( name in jQuery.cache[ id ] ) break; if ( !name ) jQuery.removeData( elem ); } // Otherwise, we want to remove all of the element's data } else { // Clean up the element expando try { delete elem[ expando ]; } catch(e){ // IE has trouble directly removing the expando // but it's ok with using removeAttribute if ( elem.removeAttribute ) elem.removeAttribute( expando ); } // Completely remove the data cache delete jQuery.cache[ id ]; } }, queue: function( elem, type, data ) { if ( elem ){ type = (type || "fx") + "queue"; var q = jQuery.data( elem, type ); if ( !q || jQuery.isArray(data) ) q = jQuery.data( elem, type, jQuery.makeArray(data) ); else if( data ) q.push( data ); } return q; }, dequeue: function( elem, type ){ var queue = jQuery.queue( elem, type ), fn = queue.shift(); if( !type || type === "fx" ) fn = queue[0]; if( fn !== undefined ) fn.call(elem); } }); jQuery.fn.extend({ data: function( key, value ){ var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); if ( data === undefined && this.length ) data = jQuery.data( this[0], key ); return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){ jQuery.data( this, key, value ); }); }, removeData: function( key ){ return this.each(function(){ jQuery.removeData( this, key ); }); }, queue: function(type, data){ /// <summary> /// 1: queue() - Returns a reference to the first element's queue (which is an array of functions). /// 2: queue(callback) - Adds a new function, to be executed, onto the end of the queue of all matched elements. /// 3: queue(queue) - Replaces the queue of all matched element with this new queue (the array of functions). /// </summary> /// <param name="type" type="Function">The function to add to the queue.</param> /// <returns type="jQuery" /> if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) return jQuery.queue( this[0], type ); return this.each(function(){ var queue = jQuery.queue( this, type, data ); if( type == "fx" && queue.length == 1 ) queue[0].call(this); }); }, dequeue: function(type){ /// <summary> /// Removes a queued function from the front of the queue and executes it. /// </summary> /// <param name="type" type="String" optional="true">The type of queue to access.</param> /// <returns type="jQuery" /> return this.each(function(){ jQuery.dequeue( this, type ); }); } });/*! * Sizzle CSS Selector Engine - v0.9.3 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g, done = 0, toString = Object.prototype.toString; var Sizzle = function(selector, context, results, seed) { results = results || []; context = context || document; if ( context.nodeType !== 1 && context.nodeType !== 9 ) return []; if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, check, mode, extra, prune = true; // Reset the position of the chunker regexp (start from head) chunker.lastIndex = 0; while ( (m = chunker.exec(selector)) !== null ) { parts.push( m[1] ); if ( m[2] ) { extra = RegExp.rightContext; break; } } if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) selector += parts.shift(); set = posProcess( selector, set ); } } } else { var ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && context.parentNode ? context.parentNode : context, isXML(context) ); set = Sizzle.filter( ret.expr, ret.set ); if ( parts.length > 0 ) { checkSet = makeArray(set); } else { prune = false; } while ( parts.length ) { var cur = parts.pop(), pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, isXML(context) ); } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { throw "Syntax error, unrecognized expression: " + (cur || selector); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context.nodeType === 1 ) { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( var 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, context, results, seed ); if ( sortOrder ) { hasDuplicate = false; 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.find = function(expr, context, isXML){ var set, match; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; if ( (match = Expr.match[ type ].exec( expr )) ) { var left = RegExp.leftContext; if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; Sizzle.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound, isXMLFilter = set && set[0] && isXML(set[0]); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.match[ type ].exec( expr )) != null ) { var filter = Expr.filter[ type ], found, item; anyFound = false; if ( curLoop == result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr == old ) { if ( anyFound == null ) { throw "Syntax error, unrecognized expression: " + expr; } else { break; } } old = expr; } return curLoop; }; 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|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/ }, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function(elem){ return elem.getAttribute("href"); } }, relative: { "+": function(checkSet, part, isXML){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.test(part), isPartStrNotTag = isPartStr && !isTag; if ( isTag && !isXML ) { part = part.toUpperCase(); } 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 === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function(checkSet, part, isXML){ var isPartStr = typeof part === "string"; if ( isPartStr && !/\W/.test(part) ) { part = isXML ? part : part.toUpperCase(); for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName === part ? parent : false; } } } else { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var 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 doneName = done++, checkFn = dirCheck; if ( !part.match(/\W/) ) { var nodeCheck = part = isXML ? part : part.toUpperCase(); checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); }, "~": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !part.match(/\W/) ) { var nodeCheck = part = isXML ? part : part.toUpperCase(); 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]); return m ? [m] : []; } }, NAME: function(match, context, isXML){ 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){ return context.getElementsByTagName(match[1]); } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not, isXML){ match = " " + match[1].replace(/\\/g, "") + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) { if ( !inplace ) result.push( elem ); } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ for ( var i = 0; curLoop[i] === false; i++ ){} return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase(); }, CHILD: function(match){ if ( match[1] == "nth" ) { // 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; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function(match, curLoop, inplace, result, not, isXML){ var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } 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 ( match[3].match(chunker).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 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){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON"; }, input: function(elem){ return /input|select|textarea|button/i.test(elem.nodeName); } }, 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 || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var i = 0, l = not.length; i < l; i++ ) { if ( not[i] === elem ) { return false; } } return true; } }, CHILD: function(elem, match){ var type = match[1], node = elem; switch (type) { case 'only': case 'first': while (node = node.previousSibling) { if ( node.nodeType === 1 ) return false; } if ( type == 'first') return true; node = elem; case 'last': while (node = node.nextSibling) { if ( node.nodeType === 1 ) return false; } return true; case 'nth': var first = match[2], last = match[3]; if ( first == 1 && last == 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first == 0 ) { return diff == 0; } else { return ( diff % first == 0 && diff / first >= 0 ); } } }, ID: function(elem, match){ return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function(elem, match){ return (match === "*" && elem.nodeType === 1) || elem.nodeName === match; }, CLASS: function(elem, match){ return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function(elem, match){ var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value != check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function(elem, match, i, array){ var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS; for ( var type in Expr.match ) { Expr.match[ type ] = RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); } var makeArray = function(array, results) { array = Array.prototype.slice.call( array ); 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. try { Array.prototype.slice.call( document.documentElement.childNodes ); // Provide a fallback method if it does not work } catch(e){ makeArray = function(array, results) { var ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var i = 0, l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( var i = 0; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( "sourceIndex" in document.documentElement ) { sortOrder = function( a, b ) { var ret = a.sourceIndex - b.sourceIndex; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( document.createRange ) { sortOrder = function( a, b ) { var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); aRange.selectNode(a); aRange.collapse(true); bRange.selectNode(b); bRange.collapse(true); var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } // [vsdoc] The following function has been modified for IntelliSense. // 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("form"), //// id = "script" + (new Date).getTime(); ////form.innerHTML = "<input name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly ////var root = document.documentElement; ////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 ); })(); // [vsdoc] The following function has been modified for IntelliSense. (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); }; ////} })(); if ( document.querySelectorAll ) (function(){ var oldSizzle = Sizzle, div = document.createElement("div"); 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 && context.nodeType === 9 && !isXML(context) ) { try { return makeArray( context.querySelectorAll(query), extra ); } catch(e){} } return oldSizzle(query, context, extra, seed); }; Sizzle.find = oldSizzle.find; Sizzle.filter = oldSizzle.filter; Sizzle.selectors = oldSizzle.selectors; Sizzle.matches = oldSizzle.matches; })(); if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (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) if ( 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]); } }; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { var sibDir = dir == "previousSibling" && !isXML; for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { if ( sibDir && elem.nodeType === 1 ){ elem.sizcache = doneName; elem.sizset = i; } elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { var sibDir = dir == "previousSibling" && !isXML; for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { if ( sibDir && elem.nodeType === 1 ) { elem.sizcache = doneName; elem.sizset = i; } elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } var contains = document.compareDocumentPosition ? function(a, b){ return a.compareDocumentPosition(b) & 16; } : function(a, b){ return a !== b && (a.contains ? a.contains(b) : true); }; var isXML = function(elem){ return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" || !!elem.ownerDocument && isXML( elem.ownerDocument ); }; var posProcess = function(selector, context){ var tmpSet = [], later = "", match, root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.filter = Sizzle.filter; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; Sizzle.selectors.filters.hidden = function(elem){ return elem.offsetWidth === 0 || elem.offsetHeight === 0; }; Sizzle.selectors.filters.visible = function(elem){ return elem.offsetWidth > 0 || elem.offsetHeight > 0; }; Sizzle.selectors.filters.animated = function(elem){ return jQuery.grep(jQuery.timers, function(fn){ return elem === fn.elem; }).length; }; jQuery.multiFilter = function( expr, elems, not ) { /// <summary> /// This member is internal only. /// </summary> /// <private /> if ( not ) { expr = ":not(" + expr + ")"; } return Sizzle.matches(expr, elems); }; jQuery.dir = function( elem, dir ){ /// <summary> /// This member is internal only. /// </summary> /// <private /> // This member is not documented in the jQuery API: http://docs.jquery.com/Special:Search?ns0=1&search=dir var matched = [], cur = elem[dir]; while ( cur && cur != document ) { if ( cur.nodeType == 1 ) matched.push( cur ); cur = cur[dir]; } return matched; }; jQuery.nth = function(cur, result, dir, elem){ /// <summary> /// This member is internal only. /// </summary> /// <private /> // This member is not documented in the jQuery API: http://docs.jquery.com/Special:Search?ns0=1&search=nth result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) if ( cur.nodeType == 1 && ++num == result ) break; return cur; }; jQuery.sibling = function(n, elem){ /// <summary> /// This member is internal only. /// </summary> /// <private /> // This member is not documented in the jQuery API: http://docs.jquery.com/Special:Search?ns0=1&search=nth var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType == 1 && n != elem ) r.push( n ); } return r; }; return; window.Sizzle = Sizzle; })(); /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function(elem, types, handler, data) { /// <summary> /// This method is internal. /// </summary> /// <private /> if ( elem.nodeType == 3 || elem.nodeType == 8 ) return; // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( elem.setInterval && elem != window ) elem = window; // Make sure that the function being executed has a unique ID if ( !handler.guid ) handler.guid = this.guid++; // if data is passed, bind to handler if ( data !== undefined ) { // Create temporary function pointer to original handler var fn = handler; // Create unique handler function, wrapped around original handler handler = this.proxy( fn ); // Store data in unique handler handler.data = data; } // Init the element's event structure var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}), handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){ // Handle the second event of a trigger and when // an event is called after a page has unloaded return typeof jQuery !== "undefined" && !jQuery.event.triggered ? jQuery.event.handle.apply(arguments.callee.elem, arguments) : undefined; }); // Add elem as a property of the handle function // This is to prevent a memory leak with non-native // event in IE. handle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); jQuery.each(types.split(/\s+/), function(index, type) { // Namespaced event handlers var namespaces = type.split("."); type = namespaces.shift(); handler.type = namespaces.slice().sort().join("."); // Get the current list of functions bound to this event var handlers = events[type]; if ( jQuery.event.specialAll[type] ) jQuery.event.specialAll[type].setup.call(elem, data, namespaces); // Init the event handler queue if (!handlers) { handlers = events[type] = {}; // Check for a special event handler // Only use addEventListener/attachEvent if the special // events handler returns false if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) { // Bind the global event handler to the element if (elem.addEventListener) elem.addEventListener(type, handle, false); else if (elem.attachEvent) elem.attachEvent("on" + type, handle); } } // Add the function to the element's handler list handlers[handler.guid] = handler; // Keep track of which events have been used, for global triggering jQuery.event.global[type] = true; }); // Nullify elem to prevent memory leaks in IE elem = null; }, guid: 1, global: {}, // Detach an event or set of events from an element remove: function(elem, types, handler) { /// <summary> /// This method is internal. /// </summary> /// <private /> // don't do events on text and comment nodes if ( elem.nodeType == 3 || elem.nodeType == 8 ) return; var events = jQuery.data(elem, "events"), ret, index; if ( events ) { // Unbind all events for the element if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") ) for ( var type in events ) this.remove( elem, type + (types || "") ); else { // types is actually an event object here if ( types.type ) { handler = types.handler; types = types.type; } // Handle multiple events seperated by a space // jQuery(...).unbind("mouseover mouseout", fn); jQuery.each(types.split(/\s+/), function(index, type){ // Namespaced event handlers var namespaces = type.split("."); type = namespaces.shift(); var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)"); if ( events[type] ) { // remove the given handler for the given type if ( handler ) delete events[type][handler.guid]; // remove all handlers for the given type else for ( var handle in events[type] ) // Handle the removal of namespaced events if ( namespace.test(events[type][handle].type) ) delete events[type][handle]; if ( jQuery.event.specialAll[type] ) jQuery.event.specialAll[type].teardown.call(elem, namespaces); // remove generic event handler if no more handlers exist for ( ret in events[type] ) break; if ( !ret ) { if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false ) { if (elem.removeEventListener) elem.removeEventListener(type, jQuery.data(elem, "handle"), false); else if (elem.detachEvent) elem.detachEvent("on" + type, jQuery.data(elem, "handle")); } ret = null; delete events[type]; } } }); } // Remove the expando if it's no longer used for ( ret in events ) break; if ( !ret ) { var handle = jQuery.data( elem, "handle" ); if ( handle ) handle.elem = null; jQuery.removeData( elem, "events" ); jQuery.removeData( elem, "handle" ); } } }, // bubbling is internal trigger: function( event, data, elem, bubbling ) { /// <summary> /// This method is internal. /// </summary> /// <private /> // Event object or event type var type = event.type || event; if( !bubbling ){ event = typeof event === "object" ? // jQuery.Event object event[expando] ? event : // Object literal jQuery.extend( jQuery.Event(type), event ) : // Just the event type (string) jQuery.Event(type); if ( type.indexOf("!") >= 0 ) { event.type = type = type.slice(0, -1); event.exclusive = true; } // Handle a global trigger if ( !elem ) { // Don't bubble custom events when global (to avoid too much overhead) event.stopPropagation(); // Only trigger if we've ever bound an event for it if ( this.global[type] ) jQuery.each( jQuery.cache, function(){ if ( this.events && this.events[type] ) jQuery.event.trigger( event, data, this.handle.elem ); }); } // Handle triggering a single element // don't do events on text and comment nodes if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 ) return undefined; // Clean up in case it is reused event.result = undefined; event.target = elem; // Clone the incoming data, if any data = jQuery.makeArray(data); data.unshift( event ); } event.currentTarget = elem; // Trigger the event, it is assumed that "handle" is a function var handle = jQuery.data(elem, "handle"); if ( handle ) handle.apply( elem, data ); // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links) if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false ) event.result = false; // Trigger the native events (except for clicks on links) if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) { this.triggered = true; try { elem[ type ](); // prevent IE from throwing an error for some hidden elements } catch (e) {} } this.triggered = false; if ( !event.isPropagationStopped() ) { var parent = elem.parentNode || elem.ownerDocument; if ( parent ) jQuery.event.trigger(event, data, parent, true); } }, handle: function(event) { /// <summary> /// This method is internal. /// </summary> /// <private /> // returned undefined or false var all, handlers; event = arguments[0] = jQuery.event.fix( event || window.event ); event.currentTarget = this; // Namespaced event handlers var namespaces = event.type.split("."); event.type = namespaces.shift(); // Cache this now, all = true means, any handler all = !namespaces.length && !event.exclusive; var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)"); handlers = ( jQuery.data(this, "events") || {} )[event.type]; for ( var j in handlers ) { var handler = handlers[j]; // Filter the functions by class if ( all || namespace.test(handler.type) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handler; event.data = handler.data; var ret = handler.apply(this, arguments); if( ret !== undefined ){ event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if( event.isImmediatePropagationStopped() ) break; } } }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function(event) { /// <summary> /// This method is internal. /// </summary> /// <private /> if ( event[expando] ) return event; // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ){ prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either // check if target is a textnode (safari) if ( event.target.nodeType == 3 ) event.target = event.target.parentNode; // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0); } // Add which for key events if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) event.which = event.charCode || event.keyCode; // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) event.metaKey = event.ctrlKey; // Add which for click: 1 == left; 2 == middle; 3 == right // Note: button is not normalized, so don't use it if ( !event.which && event.button ) event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); return event; }, proxy: function( fn, proxy ){ /// <summary> /// This method is internal. /// </summary> /// <private /> proxy = proxy || function(){ return fn.apply(this, 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 || this.guid++; // So proxy can be declared as an argument return proxy; }, special: { ready: { /// <summary> /// This method is internal. /// </summary> /// <private /> // Make sure the ready event is setup setup: bindReady, teardown: function() {} } }, specialAll: { live: { setup: function( selector, namespaces ){ jQuery.event.add( this, namespaces[0], liveHandler ); }, teardown: function( namespaces ){ if ( namespaces.length ) { var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)"); jQuery.each( (jQuery.data(this, "events").live || {}), function(){ if ( name.test(this.type) ) remove++; }); if ( remove < 1 ) jQuery.event.remove( this, namespaces[0], liveHandler ); } } } } }; jQuery.Event = function( src ){ // Allow instantiation without the 'new' keyword if( !this.preventDefault ) return new jQuery.Event(src); // Event object if( src && src.type ){ this.originalEvent = src; this.type = src.type; // Event type }else this.type = src; // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = now(); // Mark it as fixed this[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) e.returnValue = false; }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if( !e ) return; // if stopPropagation exists run it on the original event if (e.stopPropagation) e.stopPropagation(); // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation:function(){ this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function(event) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // Traverse up the tree while ( parent && parent != this ) try { parent = parent.parentNode; } catch(e) { parent = this; } if( parent != this ){ // set the correct event type event.type = event.data; // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } }; jQuery.each({ mouseover: 'mouseenter', mouseout: 'mouseleave' }, function( orig, fix ){ jQuery.event.special[ fix ] = { setup: function(){ /// <summary> /// This method is internal. /// </summary> /// <private /> jQuery.event.add( this, orig, withinElement, fix ); }, teardown: function(){ /// <summary> /// This method is internal. /// </summary> /// <private /> jQuery.event.remove( this, orig, withinElement ); } }; }); jQuery.fn.extend({ bind: function( type, data, fn ) { /// <summary> /// Binds a handler to one or more events for each matched element. Can also bind custom events. /// </summary> /// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param> /// <param name="data" optional="true" type="Object">Additional data passed to the event handler as event.data</param> /// <param name="fn" type="Function">A function to bind to the event on each of the set of matched elements. function callback(eventObject) such that this corresponds to the dom element.</param> return type == "unload" ? this.one(type, data, fn) : this.each(function(){ jQuery.event.add( this, type, fn || data, fn && data ); }); }, one: function( type, data, fn ) { /// <summary> /// Binds a handler to one or more events to be executed exactly once for each matched element. /// </summary> /// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param> /// <param name="data" optional="true" type="Object">Additional data passed to the event handler as event.data</param> /// <param name="fn" type="Function">A function to bind to the event on each of the set of matched elements. function callback(eventObject) such that this corresponds to the dom element.</param> var one = jQuery.event.proxy( fn || data, function(event) { jQuery(this).unbind(event, one); return (fn || data).apply( this, arguments ); }); return this.each(function(){ jQuery.event.add( this, type, one, fn && data); }); }, unbind: function( type, fn ) { /// <summary> /// Unbinds a handler from one or more events for each matched element. /// </summary> /// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param> /// <param name="fn" type="Function">A function to bind to the event on each of the set of matched elements. function callback(eventObject) such that this corresponds to the dom element.</param> return this.each(function(){ jQuery.event.remove( this, type, fn ); }); }, trigger: function( type, data ) { /// <summary> /// Triggers a type of event on every matched element. /// </summary> /// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param> /// <param name="data" optional="true" type="Array">Additional data passed to the event handler as additional arguments.</param> /// <param name="fn" type="Function">This parameter is undocumented.</param> return this.each(function(){ jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { /// <summary> /// Triggers all bound event handlers on an element for a specific event type without executing the browser's default actions. /// </summary> /// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param> /// <param name="data" optional="true" type="Array">Additional data passed to the event handler as additional arguments.</param> /// <param name="fn" type="Function">This parameter is undocumented.</param> if( this[0] ){ var event = jQuery.Event(type); event.preventDefault(); event.stopPropagation(); jQuery.event.trigger( event, data, this[0] ); return event.result; } }, toggle: function( fn ) { /// <summary> /// Toggles among two or more function calls every other click. /// </summary> /// <param name="fn" type="Function">The functions among which to toggle execution</param> // Save reference to arguments for access in closure var args = arguments, i = 1; // link all the functions, so any of them can unbind this click handler while( i < args.length ) jQuery.event.proxy( fn, args[i++] ); return this.click( jQuery.event.proxy( fn, function(event) { // Figure out which function to execute this.lastToggle = ( this.lastToggle || 0 ) % i; // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ this.lastToggle++ ].apply( this, arguments ) || false; })); }, hover: function(fnOver, fnOut) { /// <summary> /// Simulates hovering (moving the mouse on or off of an object). /// </summary> /// <param name="fnOver" type="Function">The function to fire when the mouse is moved over a matched element.</param> /// <param name="fnOut" type="Function">The function to fire when the mouse is moved off of a matched element.</param> return this.mouseenter(fnOver).mouseleave(fnOut); }, ready: function(fn) { /// <summary> /// Binds a function to be executed whenever the DOM is ready to be traversed and manipulated. /// </summary> /// <param name="fn" type="Function">The function to be executed when the DOM is ready.</param> // Attach the listeners bindReady(); // If the DOM is already ready if ( jQuery.isReady ) // Execute the function immediately fn.call( document, jQuery ); // Otherwise, remember the function for later else // Add the function to the wait list jQuery.readyList.push( fn ); return this; }, live: function( type, fn ){ /// <summary> /// Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events. /// </summary> /// <param name="type" type="String">An event type</param> /// <param name="fn" type="Function">A function to bind to the event on each of the set of matched elements</param> var proxy = jQuery.event.proxy( fn ); proxy.guid += this.selector + type; jQuery(document).bind( liveConvert(type, this.selector), this.selector, proxy ); return this; }, die: function( type, fn ){ /// <summary> /// This does the opposite of live, it removes a bound live event. /// You can also unbind custom events registered with live. /// If the type is provided, all bound live events of that type are removed. /// If the function that was passed to live is provided as the second argument, only that specific event handler is removed. /// </summary> /// <param name="type" type="String">A live event type to unbind.</param> /// <param name="fn" type="Function">A function to unbind from the event on each of the set of matched elements.</param> jQuery(document).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null ); return this; } }); function liveHandler( event ){ var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"), stop = true, elems = []; jQuery.each(jQuery.data(this, "events").live || [], function(i, fn){ if ( check.test(fn.type) ) { var elem = jQuery(event.target).closest(fn.data)[0]; if ( elem ) elems.push({ elem: elem, fn: fn }); } }); elems.sort(function(a,b) { return jQuery.data(a.elem, "closest") - jQuery.data(b.elem, "closest"); }); jQuery.each(elems, function(){ if ( this.fn.call(this.elem, event, this.fn.data) === false ) return (stop = false); }); return stop; } function liveConvert(type, selector){ return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join("."); } jQuery.extend({ isReady: false, readyList: [], // Handle when the DOM is ready ready: function() { /// <summary> /// This method is internal. /// </summary> /// <private /> // Make sure that the DOM is not already loaded if ( !jQuery.isReady ) { // Remember that the DOM is ready jQuery.isReady = true; // If there are functions bound, to execute if ( jQuery.readyList ) { // Execute all of them jQuery.each( jQuery.readyList, function(){ this.call( document, jQuery ); }); // Reset the list of functions jQuery.readyList = null; } // Trigger any bound ready events jQuery(document).triggerHandler("ready"); } } }); var readyBound = false; function bindReady(){ if ( readyBound ) return; readyBound = true; // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", function(){ document.removeEventListener( "DOMContentLoaded", arguments.callee, false ); 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", function(){ if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", arguments.callee ); jQuery.ready(); } }); // If IE and not an iframe // continually check to see if the document is ready if ( document.documentElement.doScroll && window == window.top ) (function(){ 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( error ) { setTimeout( arguments.callee, 0 ); return; } // and execute any waiting functions jQuery.ready(); })(); } // A fallback to window.onload, that will always work jQuery.event.add( window, "load", jQuery.ready ); } // [vsdoc] The following section has been denormalized from original sources for IntelliSense. jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," + "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," + "change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){ // Handle event binding jQuery.fn[name] = function(fn){ return fn ? this.bind(name, fn) : this.trigger(name); }; }); jQuery.fn["blur"] = function(fn) { /// <summary> /// 1: blur() - Triggers the blur event of each matched element. /// 2: blur(fn) - Binds a function to the blur event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("blur", fn) : this.trigger(name); }; jQuery.fn["focus"] = function(fn) { /// <summary> /// 1: focus() - Triggers the focus event of each matched element. /// 2: focus(fn) - Binds a function to the focus event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("focus", fn) : this.trigger(name); }; jQuery.fn["load"] = function(fn) { /// <summary> /// 1: load() - Triggers the load event of each matched element. /// 2: load(fn) - Binds a function to the load event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("load", fn) : this.trigger(name); }; jQuery.fn["resize"] = function(fn) { /// <summary> /// 1: resize() - Triggers the resize event of each matched element. /// 2: resize(fn) - Binds a function to the resize event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("resize", fn) : this.trigger(name); }; jQuery.fn["scroll"] = function(fn) { /// <summary> /// 1: scroll() - Triggers the scroll event of each matched element. /// 2: scroll(fn) - Binds a function to the scroll event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("scroll", fn) : this.trigger(name); }; jQuery.fn["unload"] = function(fn) { /// <summary> /// 1: unload() - Triggers the unload event of each matched element. /// 2: unload(fn) - Binds a function to the unload event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("unload", fn) : this.trigger(name); }; jQuery.fn["click"] = function(fn) { /// <summary> /// 1: click() - Triggers the click event of each matched element. /// 2: click(fn) - Binds a function to the click event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("click", fn) : this.trigger(name); }; jQuery.fn["dblclick"] = function(fn) { /// <summary> /// 1: dblclick() - Triggers the dblclick event of each matched element. /// 2: dblclick(fn) - Binds a function to the dblclick event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("dblclick", fn) : this.trigger(name); }; jQuery.fn["mousedown"] = function(fn) { /// <summary> /// Binds a function to the mousedown event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("mousedown", fn) : this.trigger(name); }; jQuery.fn["mouseup"] = function(fn) { /// <summary> /// Bind a function to the mouseup event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("mouseup", fn) : this.trigger(name); }; jQuery.fn["mousemove"] = function(fn) { /// <summary> /// Bind a function to the mousemove event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("mousemove", fn) : this.trigger(name); }; jQuery.fn["mouseover"] = function(fn) { /// <summary> /// Bind a function to the mouseover event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("mouseover", fn) : this.trigger(name); }; jQuery.fn["mouseout"] = function(fn) { /// <summary> /// Bind a function to the mouseout event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("mouseout", fn) : this.trigger(name); }; jQuery.fn["mouseenter"] = function(fn) { /// <summary> /// Bind a function to the mouseenter event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("mouseenter", fn) : this.trigger(name); }; jQuery.fn["mouseleave"] = function(fn) { /// <summary> /// Bind a function to the mouseleave event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("mouseleave", fn) : this.trigger(name); }; jQuery.fn["change"] = function(fn) { /// <summary> /// 1: change() - Triggers the change event of each matched element. /// 2: change(fn) - Binds a function to the change event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("change", fn) : this.trigger(name); }; jQuery.fn["select"] = function(fn) { /// <summary> /// 1: select() - Triggers the select event of each matched element. /// 2: select(fn) - Binds a function to the select event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("select", fn) : this.trigger(name); }; jQuery.fn["submit"] = function(fn) { /// <summary> /// 1: submit() - Triggers the submit event of each matched element. /// 2: submit(fn) - Binds a function to the submit event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("submit", fn) : this.trigger(name); }; jQuery.fn["keydown"] = function(fn) { /// <summary> /// 1: keydown() - Triggers the keydown event of each matched element. /// 2: keydown(fn) - Binds a function to the keydown event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("keydown", fn) : this.trigger(name); }; jQuery.fn["keypress"] = function(fn) { /// <summary> /// 1: keypress() - Triggers the keypress event of each matched element. /// 2: keypress(fn) - Binds a function to the keypress event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("keypress", fn) : this.trigger(name); }; jQuery.fn["keyup"] = function(fn) { /// <summary> /// 1: keyup() - Triggers the keyup event of each matched element. /// 2: keyup(fn) - Binds a function to the keyup event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("keyup", fn) : this.trigger(name); }; jQuery.fn["error"] = function(fn) { /// <summary> /// 1: error() - Triggers the error event of each matched element. /// 2: error(fn) - Binds a function to the error event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind("error", fn) : this.trigger(name); }; // Prevent memory leaks in IE // And prevent errors on refresh with events like mouseover in other browsers // Window isn't included so as not to unbind existing unload events jQuery( window ).bind( 'unload', function(){ for ( var id in jQuery.cache ) // Skip the window if ( id != 1 && jQuery.cache[ id ].handle ) jQuery.event.remove( jQuery.cache[ id ].handle.elem ); }); // [vsdoc] The following function has been modified for IntelliSense. // [vsdoc] Stubbing support properties to "false" since we simulate IE. (function(){ jQuery.support = {}; jQuery.support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: false, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: false, // Make sure that you can get all elements in an <object> element // IE 7 always returns no results objectAll: false, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: false, // Get the style information from getAttribute // (IE uses .cssText insted) style: false, // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: false, // Make sure that element opacity exists // (IE uses filter instead) opacity: false, // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: false, // Will be defined later scriptEval: false, noCloneEvent: false, boxModel: false }; })(); // [vsdoc] The following member has been modified for IntelliSense. var styleFloat = "styleFloat"; jQuery.props = { "for": "htmlFor", "class": "className", "float": styleFloat, cssFloat: styleFloat, styleFloat: styleFloat, readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", tabindex: "tabIndex" }; jQuery.fn.extend({ // Keep a copy of the old load _load: jQuery.fn.load, load: function( url, params, callback ) { /// <summary> /// Loads HTML from a remote file and injects it into the DOM. By default performs a GET request, but if parameters are included /// then a POST will be performed. /// </summary> /// <param name="url" type="String">The URL of the HTML page to load.</param> /// <param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param> /// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete. It should map function(responseText, textStatus, XMLHttpRequest) such that this maps the injected DOM element.</param> /// <returns type="jQuery" /> if ( typeof url !== "string" ) return this._load( url ); 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 = null; // Otherwise, build a param string } else if( typeof params === "object" ) { params = jQuery.param( params ); type = "POST"; } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, complete: function(res, status){ // If successful, inject the HTML into all the matched elements if ( status == "success" || status == "notmodified" ) // 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(res.responseText.replace(/<script(.|\s)*?\/script>/g, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result res.responseText ); if( callback ) self.each( callback, [res.responseText, status, res] ); } }); return this; }, serialize: function() { /// <summary> /// Serializes a set of input elements into a string of data. /// </summary> /// <returns type="String">The serialized result</returns> return jQuery.param(this.serializeArray()); }, serializeArray: function() { /// <summary> /// Serializes all forms and form elements but returns a JSON data structure. /// </summary> /// <returns type="String">A JSON data structure representing the serialized items.</returns> return this.map(function(){ return this.elements ? jQuery.makeArray(this.elements) : this; }) .filter(function(){ return this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password|search/i.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}; }) : {name: elem.name, value: val}; }).get(); } }); // [vsdoc] The following section has been denormalized from original sources for IntelliSense. // Attach a bunch of functions for handling common AJAX events // jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){ // jQuery.fn[o] = function(f){ // return this.bind(o, f); // }; // }); jQuery.fn["ajaxStart"] = function(callback) { /// <summary> /// Attach a function to be executed whenever an AJAX request begins and there is none already active. This is an Ajax Event. /// </summary> /// <param name="callback" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return this.bind("ajaxStart", f); }; jQuery.fn["ajaxStop"] = function(callback) { /// <summary> /// Attach a function to be executed whenever all AJAX requests have ended. This is an Ajax Event. /// </summary> /// <param name="callback" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return this.bind("ajaxStop", f); }; jQuery.fn["ajaxComplete"] = function(callback) { /// <summary> /// Attach a function to be executed whenever an AJAX request completes. This is an Ajax Event. /// </summary> /// <param name="callback" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return this.bind("ajaxComplete", f); }; jQuery.fn["ajaxError"] = function(callback) { /// <summary> /// Attach a function to be executed whenever an AJAX request fails. This is an Ajax Event. /// </summary> /// <param name="callback" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return this.bind("ajaxError", f); }; jQuery.fn["ajaxSuccess"] = function(callback) { /// <summary> /// Attach a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event. /// </summary> /// <param name="callback" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return this.bind("ajaxSuccess", f); }; jQuery.fn["ajaxSend"] = function(callback) { /// <summary> /// Attach a function to be executed before an AJAX request is sent. This is an Ajax Event. /// </summary> /// <param name="callback" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return this.bind("ajaxSend", f); }; var jsc = now(); jQuery.extend({ get: function( url, data, callback, type ) { /// <summary> /// Loads a remote page using an HTTP GET request. /// </summary> /// <param name="url" type="String">The URL of the HTML page to load.</param> /// <param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param> /// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete. It should map function(responseText, textStatus) such that this maps the options for this AJAX request.</param> /// <param name="type" optional="true" type="String">Type of data to be returned to callback function. Valid valiues are xml, html, script, json, text, _default.</param> /// <returns type="XMLHttpRequest" /> // shift arguments if data argument was ommited if ( jQuery.isFunction( data ) ) { callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type }); }, getScript: function( url, callback ) { /// <summary> /// Loads and executes a local JavaScript file using an HTTP GET request. /// </summary> /// <param name="url" type="String">The URL of the script to load.</param> /// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete. It should map function(data, textStatus) such that this maps the options for the AJAX request.</param> /// <returns type="XMLHttpRequest" /> return jQuery.get(url, null, callback, "script"); }, getJSON: function( url, data, callback ) { /// <summary> /// Loads JSON data using an HTTP GET request. /// </summary> /// <param name="url" type="String">The URL of the JSON data to load.</param> /// <param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param> /// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete if the data is loaded successfully. It should map function(data, textStatus) such that this maps the options for this AJAX request.</param> /// <returns type="XMLHttpRequest" /> return jQuery.get(url, data, callback, "json"); }, post: function( url, data, callback, type ) { /// <summary> /// Loads a remote page using an HTTP POST request. /// </summary> /// <param name="url" type="String">The URL of the HTML page to load.</param> /// <param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param> /// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete. It should map function(responseText, textStatus) such that this maps the options for this AJAX request.</param> /// <param name="type" optional="true" type="String">Type of data to be returned to callback function. Valid valiues are xml, html, script, json, text, _default.</param> /// <returns type="XMLHttpRequest" /> if ( jQuery.isFunction( data ) ) { callback = data; data = {}; } return jQuery.ajax({ type: "POST", url: url, data: data, success: callback, dataType: type }); }, ajaxSetup: function( settings ) { /// <summary> /// Sets up global settings for AJAX requests. /// </summary> /// <param name="settings" type="Options">A set of key/value pairs that configure the default Ajax request.</param> jQuery.extend( jQuery.ajaxSettings, settings ); }, ajaxSettings: { url: location.href, global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, username: null, password: null, */ // Create the request object; Microsoft failed to properly // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available // This function can be overriden by calling jQuery.ajaxSetup xhr:function(){ return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); }, accepts: { xml: "application/xml, text/xml", html: "text/html", script: "text/javascript, application/javascript", json: "application/json, text/javascript", text: "text/plain", _default: "*/*" } }, // Last-Modified header cache for next request lastModified: {}, ajax: function( s ) { /// <summary> /// Load a remote page using an HTTP request. /// </summary> /// <private /> // Extend the settings, but re-extend 's' so that it can be // checked again later (in the test suite, specifically) s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s)); var jsonp, jsre = /=\?(&|$)/g, status, data, type = s.type.toUpperCase(); // convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) s.data = jQuery.param(s.data); // Handle JSONP Parameter Callbacks if ( s.dataType == "jsonp" ) { if ( type == "GET" ) { if ( !s.url.match(jsre) ) s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?"; } else if ( !s.data || !s.data.match(jsre) ) s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; s.dataType = "json"; } // Build temporary JSONP function if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) { jsonp = "jsonp" + jsc++; // Replace the =? sequence both in the query string and the data if ( s.data ) s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure // that a JSONP style response is executed properly s.dataType = "script"; // Handle JSONP-style loading window[ jsonp ] = function(tmp){ data = tmp; success(); complete(); // Garbage collect window[ jsonp ] = undefined; try{ delete window[ jsonp ]; } catch(e){} if ( head ) head.removeChild( script ); }; } if ( s.dataType == "script" && s.cache == null ) s.cache = false; if ( s.cache === false && type == "GET" ) { var ts = now(); // try replacing _= if it is there var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2"); // if nothing was replaced, add timestamp to the end s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : ""); } // If data is available, append data to url for get requests if ( s.data && type == "GET" ) { s.url += (s.url.match(/\?/) ? "&" : "?") + s.data; // IE likes to send both get and post data, prevent this s.data = null; } // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) jQuery.event.trigger( "ajaxStart" ); // Matches an absolute URL, and saves the domain var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url ); // If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType == "script" && type == "GET" && parts && ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){ var head = document.getElementsByTagName("head")[0]; var script = document.createElement("script"); script.src = s.url; if (s.scriptCharset) script.charset = s.scriptCharset; // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function(){ if ( !done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") ) { done = true; success(); complete(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; head.removeChild( script ); } }; } head.appendChild(script); // We handle everything using the script element injection return undefined; } var requestDone = false; // Create the request object var xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if( s.username ) xhr.open(type, s.url, s.async, s.username, s.password); else xhr.open(type, s.url, s.async); // Need an extra try/catch for cross domain requests in Firefox 3 try { // Set the correct header, if data is being sent if ( s.data ) xhr.setRequestHeader("Content-Type", s.contentType); // Set the If-Modified-Since header, if ifModified mode. if ( s.ifModified ) xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" ); // Set header so the called script knows that it's an XMLHttpRequest xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); // Set the Accepts header for the server, depending on the dataType xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? s.accepts[ s.dataType ] + ", */*" : s.accepts._default ); } catch(e){} // Allow custom headers/mimetypes and early abort if ( s.beforeSend && s.beforeSend(xhr, s) === false ) { // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); // close opended socket xhr.abort(); return false; } if ( s.global ) jQuery.event.trigger("ajaxSend", [xhr, s]); // Wait for a response to come back var onreadystatechange = function(isTimeout){ // The request was aborted, clear the interval and decrement jQuery.active if (xhr.readyState == 0) { if (ival) { // clear poll interval clearInterval(ival); ival = null; // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); } // The transfer is complete and the data is available, or the request timed out } else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) { requestDone = true; // clear poll interval if (ival) { clearInterval(ival); ival = null; } status = isTimeout == "timeout" ? "timeout" : !jQuery.httpSuccess( xhr ) ? "error" : s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" : "success"; if ( status == "success" ) { // Watch for, and catch, XML document parse errors try { // process the data (runs the xml through httpData regardless of callback) data = jQuery.httpData( xhr, s.dataType, s ); } catch(e) { status = "parsererror"; } } // Make sure that the request was successful or notmodified if ( status == "success" ) { // Cache Last-Modified header, if ifModified mode. var modRes; try { modRes = xhr.getResponseHeader("Last-Modified"); } catch(e) {} // swallow exception thrown by FF if header is not available if ( s.ifModified && modRes ) jQuery.lastModified[s.url] = modRes; // JSONP handles its own success callback if ( !jsonp ) success(); } else jQuery.handleError(s, xhr, status); // Fire the complete handlers complete(); if ( isTimeout ) xhr.abort(); // Stop memory leaks if ( s.async ) xhr = null; } }; if ( s.async ) { // don't attach the handler to the request, just poll it instead var ival = setInterval(onreadystatechange, 13); // Timeout checker if ( s.timeout > 0 ) setTimeout(function(){ // Check to see if the request is still happening if ( xhr && !requestDone ) onreadystatechange( "timeout" ); }, s.timeout); } // Send the data try { xhr.send(s.data); } catch(e) { jQuery.handleError(s, xhr, null, e); } // firefox 1.5 doesn't fire statechange for sync requests if ( !s.async ) onreadystatechange(); function success(){ // If a local callback was specified, fire it and pass it the data if ( s.success ) s.success( data, status ); // Fire the global callback if ( s.global ) jQuery.event.trigger( "ajaxSuccess", [xhr, s] ); } function complete(){ // Process result if ( s.complete ) s.complete(xhr, status); // The request was completed if ( s.global ) jQuery.event.trigger( "ajaxComplete", [xhr, s] ); // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); } // return XMLHttpRequest to allow aborting the request etc. return xhr; }, handleError: function( s, xhr, status, e ) { /// <summary> /// This method is internal. /// </summary> /// <private /> // If a local callback was specified, fire it if ( s.error ) s.error( xhr, status, e ); // Fire the global callback if ( s.global ) jQuery.event.trigger( "ajaxError", [xhr, s, e] ); }, // Counter for holding the number of active queries active: 0, // Determines if an XMLHttpRequest was successful or not httpSuccess: function( xhr ) { /// <summary> /// This method is internal. /// </summary> /// <private /> try { // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 return !xhr.status && location.protocol == "file:" || ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223; } catch(e){} return false; }, // Determines if an XMLHttpRequest returns NotModified httpNotModified: function( xhr, url ) { /// <summary> /// This method is internal. /// </summary> /// <private /> try { var xhrRes = xhr.getResponseHeader("Last-Modified"); // Firefox always returns 200. check Last-Modified date return xhr.status == 304 || xhrRes == jQuery.lastModified[url]; } catch(e){} return false; }, httpData: function( xhr, type, s ) { /// <summary> /// This method is internal. /// </summary> /// <private /> var ct = xhr.getResponseHeader("content-type"), xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0, data = xml ? xhr.responseXML : xhr.responseText; if ( xml && data.documentElement.tagName == "parsererror" ) throw "parsererror"; // Allow a pre-filtering function to sanitize the response // s != null is checked to keep backwards compatibility if( s && s.dataFilter ) data = s.dataFilter( data, type ); // The filter can actually parse the response if( typeof data === "string" ){ // If the type is "script", eval it in global context if ( type == "script" ) jQuery.globalEval( data ); // Get the JavaScript object, if JSON is used. if ( type == "json" ) data = window["eval"]("(" + data + ")"); } return data; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a ) { /// <summary> /// This method is internal. Use serialize() instead. /// </summary> /// <param name="a" type="Map">A map of key/value pairs to serialize into a string.</param>' /// <returns type="String" /> /// <private /> var s = [ ]; function add( key, value ){ s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value); }; // If an array was passed in, assume that it is an array // of form elements if ( jQuery.isArray(a) || a.jquery ) // Serialize the form elements jQuery.each( a, function(){ add( this.name, this.value ); }); // Otherwise, assume that it's an object of key/value pairs else // Serialize the key/values for ( var j in a ) // If the value is an array then the key names need to be repeated if ( jQuery.isArray(a[j]) ) jQuery.each( a[j], function(){ add( j, this ); }); else add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] ); // Return the resulting serialization return s.join("&").replace(/%20/g, "+"); } }); var elemdisplay = {}, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ]; function genFx( type, num ){ var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function(){ obj[ this ] = type; }); return obj; } jQuery.fn.extend({ show: function(speed,callback){ /// <summary> /// Show all matched elements using a graceful animation and firing an optional callback after completion. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> if ( speed ) { return this.animate( genFx("show", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ){ var old = jQuery.data(this[i], "olddisplay"); this[i].style.display = old || ""; if ( jQuery.css(this[i], "display") === "none" ) { var tagName = this[i].tagName, display; if ( elemdisplay[ tagName ] ) { display = elemdisplay[ tagName ]; } else { var elem = jQuery("<" + tagName + " />").appendTo("body"); display = elem.css("display"); if ( display === "none" ) display = "block"; elem.remove(); elemdisplay[ tagName ] = display; } jQuery.data(this[i], "olddisplay", display); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var i = 0, l = this.length; i < l; i++ ){ this[i].style.display = jQuery.data(this[i], "olddisplay") || ""; } return this; } }, hide: function(speed,callback){ /// <summary> /// Hides all matched elements using a graceful animation and firing an optional callback after completion. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> if ( speed ) { return this.animate( genFx("hide", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ){ var old = jQuery.data(this[i], "olddisplay"); if ( !old && old !== "none" ) jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display")); } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var i = 0, l = this.length; i < l; i++ ){ this[i].style.display = "none"; } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2 ){ /// <summary> /// Toggles displaying each of the set of matched elements. /// </summary> /// <returns type="jQuery" /> var bool = typeof fn === "boolean"; return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ? this._toggle.apply( this, arguments ) : fn == null || bool ? this.each(function(){ var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }) : this.animate(genFx("toggle", 3), fn, fn2); }, fadeTo: function(speed,to,callback){ /// <summary> /// Fades the opacity of all matched elements to a specified opacity. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> return this.animate({opacity: to}, speed, callback); }, animate: function( prop, speed, easing, callback ) { /// <summary> /// A function for making custom animations. /// </summary> /// <param name="prop" type="Options">A set of style attributes that you wish to animate and to what end.</param> /// <param name="speed" optional="true" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="easing" optional="true" type="String">The name of the easing effect that you want to use. There are two built-in values, 'linear' and 'swing'.</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> var optall = jQuery.speed(speed, easing, callback); return this[ optall.queue === false ? "each" : "queue" ](function(){ var opt = jQuery.extend({}, optall), p, hidden = this.nodeType == 1 && jQuery(this).is(":hidden"), self = this; for ( p in prop ) { if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden ) return opt.complete.call(this); if ( ( p == "height" || p == "width" ) && this.style ) { // Store display property opt.display = jQuery.css(this, "display"); // Make sure that nothing sneaks out opt.overflow = this.style.overflow; } } if ( opt.overflow != null ) this.style.overflow = "hidden"; opt.curAnim = jQuery.extend({}, prop); jQuery.each( prop, function(name, val){ var e = new jQuery.fx( self, opt, name ); if ( /toggle|show|hide/.test(val) ) e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop ); else { var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/), start = e.cur(true) || 0; if ( parts ) { var end = parseFloat(parts[2]), unit = parts[3] || "px"; // We need to compute starting value if ( unit != "px" ) { self.style[ name ] = (end || 1) + unit; start = ((end || 1) / e.cur(true)) * start; self.style[ name ] = start + unit; } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) end = ((parts[1] == "-=" ? -1 : 1) * end) + start; e.custom( start, end, unit ); } else e.custom( start, val, "" ); } }); // For JS strict compliance return true; }); }, stop: function(clearQueue, gotoEnd){ /// <summary> /// Stops all currently animations on the specified elements. /// </summary> /// <param name="clearQueue" optional="true" type="Boolean">True to clear animations that are queued to run.</param> /// <param name="gotoEnd" optional="true" type="Boolean">True to move the element value to the end of its animation target.</param> /// <returns type="jQuery" /> var timers = jQuery.timers; if (clearQueue) this.queue([]); this.each(function(){ // go in reverse order so anything added to the queue during the loop is ignored for ( var i = timers.length - 1; i >= 0; i-- ) if ( timers[i].elem == this ) { if (gotoEnd) // force the next step to be the last timers[i](true); timers.splice(i, 1); } }); // start the next in the queue if the last step wasn't forced if (!gotoEnd) this.dequeue(); return this; } }); // 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" } // }, function( name, props ){ // jQuery.fn[ name ] = function( speed, callback ){ // return this.animate( props, speed, callback ); // }; // }); // [vsdoc] The following section has been denormalized from original sources for IntelliSense. jQuery.fn.slideDown = function( speed, callback ){ /// <summary> /// Reveal all matched elements by adjusting their height. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> return this.animate( genFx("show", 1), speed, callback ); }; jQuery.fn.slideUp = function( speed, callback ){ /// <summary> /// Hiding all matched elements by adjusting their height. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> return this.animate( genFx("hide", 1), speed, callback ); }; jQuery.fn.slideToggle = function( speed, callback ){ /// <summary> /// Toggles the visibility of all matched elements by adjusting their height. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> return this.animate( genFx("toggle", 1), speed, callback ); }; jQuery.fn.fadeIn = function( speed, callback ){ /// <summary> /// Fades in all matched elements by adjusting their opacity. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> return this.animate( { opacity: "show" }, speed, callback ); }; jQuery.fn.fadeOut = function( speed, callback ){ /// <summary> /// Fades the opacity of all matched elements to a specified opacity. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> return this.animate( { opacity: "hide" }, speed, callback ); }; jQuery.extend({ speed: function(speed, easing, fn) { /// <summary> /// This member is internal. /// </summary> /// <private /> var opt = typeof speed === "object" ? 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 : jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function(){ if ( opt.queue !== false ) jQuery(this).dequeue(); if ( jQuery.isFunction( opt.old ) ) opt.old.call( this ); }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { /// <summary> /// This member is internal. /// </summary> /// <private /> return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { /// <summary> /// This member is internal. /// </summary> /// <private /> return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ){ /// <summary> /// This member is internal. /// </summary> /// <private /> this.options = options; this.elem = elem; this.prop = prop; if ( !options.orig ) options.orig = {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function(){ /// <summary> /// This member is internal. /// </summary> /// <private /> if ( this.options.step ) this.options.step.call( this.elem, this.now, this ); (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); // Set display property to block for height/width animations if ( ( this.prop == "height" || this.prop == "width" ) && this.elem.style ) this.elem.style.display = "block"; }, // Get the current size cur: function(force){ /// <summary> /// This member is internal. /// </summary> /// <private /> if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) return this.elem[ this.prop ]; var r = parseFloat(jQuery.css(this.elem, this.prop, force)); return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0; }, // Start an animation from one number to another custom: function(from, to, unit){ this.startTime = now(); this.start = from; this.end = to; this.unit = unit || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; var self = this; function t(gotoEnd){ return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval(function(){ var timers = jQuery.timers; for ( var i = 0; i < timers.length; i++ ) if ( !timers[i]() ) timers.splice(i--, 1); if ( !timers.length ) { clearInterval( timerId ); timerId = undefined; } }, 13); } }, // Simple 'show' function show: function(){ /// <summary> /// Displays each of the set of matched elements if they are hidden. /// </summary> // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop == "width" || this.prop == "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery(this.elem).show(); }, // Simple 'hide' function hide: function(){ /// <summary> /// Hides each of the set of matched elements if they are shown. /// </summary> // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function(gotoEnd){ /// <summary> /// This method is internal. /// </summary> /// <private /> var t = now(); if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; var done = true; for ( var i in this.options.curAnim ) if ( this.options.curAnim[i] !== true ) done = false; if ( done ) { if ( this.options.display != null ) { // Reset the overflow this.elem.style.overflow = this.options.overflow; // Reset the display this.elem.style.display = this.options.display; if ( jQuery.css(this.elem, "display") == "none" ) this.elem.style.display = "block"; } // Hide the element if the "hide" operation was done if ( this.options.hide ) jQuery(this.elem).hide(); // Reset the properties, if the item has been hidden or shown if ( this.options.hide || this.options.show ) for ( var p in this.options.curAnim ) jQuery.attr(this.elem.style, p, this.options.orig[p]); // Execute the complete function this.options.complete.call( this.elem ); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.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, { speeds:{ slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function(fx){ jQuery.attr(fx.elem.style, "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; } } }); if ( document.documentElement["getBoundingClientRect"] ) jQuery.fn.offset = function() { /// <summary> /// Gets the current offset of the first matched element relative to the viewport. /// </summary> /// <returns type="Object">An object with two Integer properties, 'top' and 'left'.</returns> if ( !this[0] ) return { top: 0, left: 0 }; if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] ); var box = this[0].getBoundingClientRect(), doc = this[0].ownerDocument, body = doc.body, docElem = doc.documentElement, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, top = box.top + (self.pageYOffset || jQuery.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop, left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft; return { top: top, left: left }; }; else jQuery.fn.offset = function() { /// <summary> /// Gets the current offset of the first matched element relative to the viewport. /// </summary> /// <returns type="Object">An object with two Integer properties, 'top' and 'left'.</returns> if ( !this[0] ) return { top: 0, left: 0 }; if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] ); jQuery.offset.initialized || jQuery.offset.initialize(); var elem = this[0], offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView.getComputedStyle(elem, null), top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { computedStyle = defaultView.getComputedStyle(elem, null); top -= elem.scrollTop, left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop, left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)) ) top += parseInt( computedStyle.borderTopWidth, 10) || 0, left += parseInt( computedStyle.borderLeftWidth, 10) || 0; prevOffsetParent = offsetParent, offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) top += parseInt( computedStyle.borderTopWidth, 10) || 0, left += parseInt( computedStyle.borderLeftWidth, 10) || 0; prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) top += body.offsetTop, left += body.offsetLeft; if ( prevComputedStyle.position === "fixed" ) top += Math.max(docElem.scrollTop, body.scrollTop), left += Math.max(docElem.scrollLeft, body.scrollLeft); return { top: top, left: left }; }; jQuery.offset = { initialize: function() { if ( this.initialized ) return; var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop, html = '<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"cellpadding="0"cellspacing="0"><tr><td></td></tr></table>'; rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' }; for ( prop in rules ) container.style[prop] = rules[prop]; container.innerHTML = html; body.insertBefore(container, body.firstChild); innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative'; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); body.style.marginTop = '1px'; this.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0); body.style.marginTop = bodyMarginTop; body.removeChild(container); this.initialized = true; }, bodyOffset: function(body) { jQuery.offset.initialized || jQuery.offset.initialize(); var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) top += parseInt( jQuery.curCSS(body, 'marginTop', true), 10 ) || 0, left += parseInt( jQuery.curCSS(body, 'marginLeft', true), 10 ) || 0; return { top: top, left: left }; } }; jQuery.fn.extend({ position: function() { /// <summary> /// Gets the top and left positions of an element relative to its offset parent. /// </summary> /// <returns type="Object">An object with two integer properties, 'top' and 'left'.</returns> var left = 0, top = 0, results; if ( this[0] ) { // Get *real* offsetParent var offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { 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 -= num( this, 'marginTop' ); offset.left -= num( this, 'marginLeft' ); // Add offsetParent borders parentOffset.top += num( offsetParent, 'borderTopWidth' ); parentOffset.left += num( offsetParent, 'borderLeftWidth' ); // Subtract the two offsets results = { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; } return results; }, offsetParent: function() { /// <summary> /// This method is internal. /// </summary> /// <private /> var offsetParent = this[0].offsetParent || document.body; while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') ) offsetParent = offsetParent.offsetParent; return jQuery(offsetParent); } }); // Create scrollLeft and scrollTop methods jQuery.each( ['Left'], function(i, name) { var method = 'scroll' + name; jQuery.fn[ method ] = function(val) { /// <summary> /// Gets and optionally sets the scroll left offset of the first matched element. /// </summary> /// <param name="val" type="Number" integer="true" optional="true">A positive number representing the desired scroll left offset.</param> /// <returns type="Number" integer="true">The scroll left offset of the first matched element.</returns> if (!this[0]) return null; return val !== undefined ? // Set the scroll offset this.each(function() { this == window || this == document ? window.scrollTo( !i ? val : jQuery(window).scrollLeft(), i ? val : jQuery(window).scrollTop() ) : this[ method ] = val; }) : // Return the scroll offset this[0] == window || this[0] == document ? self[ i ? 'pageYOffset' : 'pageXOffset' ] || jQuery.boxModel && document.documentElement[ method ] || document.body[ method ] : this[0][ method ]; }; }); // Create scrollLeft and scrollTop methods jQuery.each( ['Top'], function(i, name) { var method = 'scroll' + name; jQuery.fn[ method ] = function(val) { /// <summary> /// Gets and optionally sets the scroll top offset of the first matched element. /// </summary> /// <param name="val" type="Number" integer="true" optional="true">A positive number representing the desired scroll top offset.</param> /// <returns type="Number" integer="true">The scroll top offset of the first matched element.</returns> if (!this[0]) return null; return val !== undefined ? // Set the scroll offset this.each(function() { this == window || this == document ? window.scrollTo( !i ? val : jQuery(window).scrollLeft(), i ? val : jQuery(window).scrollTop() ) : this[ method ] = val; }) : // Return the scroll offset this[0] == window || this[0] == document ? self[ i ? 'pageYOffset' : 'pageXOffset' ] || jQuery.boxModel && document.documentElement[ method ] || document.body[ method ] : this[0][ method ]; }; }); // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height" ], function(i, name){ var tl = i ? "Left" : "Top", // top or left br = i ? "Right" : "Bottom", // bottom or right lower = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function(){ /// <summary> /// Gets the inner height of the first matched element, excluding border but including padding. /// </summary> /// <returns type="Number" integer="true">The outer height of the first matched element.</returns> return this[0] ? jQuery.css( this[0], lower, false, "padding" ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function(margin) { /// <summary> /// Gets the outer height of the first matched element, including border and padding by default. /// </summary> /// <param name="margins" type="Map">A set of key/value pairs that specify the options for the method.</param> /// <returns type="Number" integer="true">The outer height of the first matched element.</returns> return this[0] ? jQuery.css( this[0], lower, false, margin ? "margin" : "border" ) : null; }; var type = name.toLowerCase(); jQuery.fn[ type ] = function( size ) { /// <summary> /// Set the CSS height of every matched element. If no explicit unit /// was specified (like 'em' or '%') then &quot;px&quot; is added to the width. If no parameter is specified, it gets /// the current computed pixel height of the first matched element. /// Part of CSS /// </summary> /// <returns type="jQuery" type="jQuery" /> /// <param name="cssProperty" type="String"> /// Set the CSS property to the specified value. Omit to get the value of the first matched element. /// </param> // Get window width or height return this[0] == window ? // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] || document.body[ "client" + name ] : // Get document width or height this[0] == document ? // Either scroll[Width/Height] or offset[Width/Height], whichever is greater Math.max( document.documentElement["client" + name], document.body["scroll" + name], document.documentElement["scroll" + name], document.body["offset" + name], document.documentElement["offset" + name] ) : // Get or set width or height on the element size === undefined ? // Get width or height on the element (this.length ? jQuery.css( this[0], type ) : null) : // Set the width or height on the element (default to pixels if value is unitless) this.css( type, typeof size === "string" ? size : size + "px" ); }; }); // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Width" ], function(i, name){ var tl = i ? "Left" : "Top", // top or left br = i ? "Right" : "Bottom", // bottom or right lower = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function(){ /// <summary> /// Gets the inner width of the first matched element, excluding border but including padding. /// </summary> /// <returns type="Number" integer="true">The outer width of the first matched element.</returns> return this[0] ? jQuery.css( this[0], lower, false, "padding" ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function(margin) { /// <summary> /// Gets the outer width of the first matched element, including border and padding by default. /// </summary> /// <param name="margins" type="Map">A set of key/value pairs that specify the options for the method.</param> /// <returns type="Number" integer="true">The outer width of the first matched element.</returns> return this[0] ? jQuery.css( this[0], lower, false, margin ? "margin" : "border" ) : null; }; var type = name.toLowerCase(); jQuery.fn[ type ] = function( size ) { /// <summary> /// Set the CSS width of every matched element. If no explicit unit /// was specified (like 'em' or '%') then &quot;px&quot; is added to the width. If no parameter is specified, it gets /// the current computed pixel width of the first matched element. /// Part of CSS /// </summary> /// <returns type="jQuery" type="jQuery" /> /// <param name="cssProperty" type="String"> /// Set the CSS property to the specified value. Omit to get the value of the first matched element. /// </param> // Get window width or height return this[0] == window ? // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] || document.body[ "client" + name ] : // Get document width or height this[0] == document ? // Either scroll[Width/Height] or offset[Width/Height], whichever is greater Math.max( document.documentElement["client" + name], document.body["scroll" + name], document.documentElement["scroll" + name], document.body["offset" + name], document.documentElement["offset" + name] ) : // Get or set width or height on the element size === undefined ? // Get width or height on the element (this.length ? jQuery.css( this[0], type ) : null) : // Set the width or height on the element (default to pixels if value is unitless) this.css( type, typeof size === "string" ? size : size + "px" ); }; }); })();
JavaScript
function $(str){ return document.getElementById(str); } function CheckAll(obj) { var checkAll = true; var checkList = document.getElementsByTagName("input"); if(obj == 2) { $("cb_All").checked = !$("cb_All").checked; } if(!$("cb_All").checked) checkAll = false; for(var i = 0 ; i < checkList.length ; i++) { if(checkList[i].type == 'checkbox' && checkList[i].id.indexOf("cb_Xoa") >= 0 ) { checkList[i].checked = checkAll; } } } function Message_confirm(Content) { var result = confirm(Content); if(result) { return true; } return false; }
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Store v 2.0 by revaxarts.com /* description: Uses LocalStorage to save information within the Browser /* enviroment /* dependency: jStorage /*----------------------------------------------------------------------*/ $.wl_Store = function (namespace) { if(typeof $.jStorage != 'object') $.error('wl_Store requires the jStorage library'); var namespace = namespace || 'wl_store', save = function (key, value) { return $.jStorage.set(namespace+'_'+key, value); }, get = function (key) { return $.jStorage.get(namespace+'_'+key); }; remove = function (key) { return $.jStorage.deleteKey(namespace+'_'+key); }, flush = function () { return $.jStorage.flush(); }, index = function () { return $.jStorage.index(); }; //public methods return { save: function (key, value) { return save(key, value); }, get: function (key) { return get(key); }, remove: function (key) { return remove(key); }, flush: function () { return flush(); }, index: function () { return index(); } } };
JavaScript
$(document).ready(function() { //for Caching var $content = $('#content'); /*----------------------------------------------------------------------*/ /* preload images /*----------------------------------------------------------------------*/ //$.preload(); /*----------------------------------------------------------------------*/ /* Widgets /*----------------------------------------------------------------------*/ $content.find('div.widgets').wl_Widget(); /*----------------------------------------------------------------------*/ /* All Form Plugins /*----------------------------------------------------------------------*/ //Integers and decimals $content.find('input[type=number].integer').wl_Number(); $content.find('input[type=number].decimal').wl_Number({decimals:2,step:0.5}); //Date and Time fields $content.find('input.date, div.date').wl_Date(); $content.find('input.time').wl_Time(); //Autocompletes (source is required) $content.find('input.autocomplete').wl_Autocomplete({ source: ["ActionScript","AppleScript","Asp","BASIC","C","C++","Clojure","COBOL","ColdFusion","Erlang","Fortran","Groovy","Haskell","Java","JavaScript","Lisp","Perl","PHP","Python","Ruby","Scala","Scheme"] }); //Elastic textareas (autogrow) $content.find('textarea[data-autogrow]').elastic(); //WYSIWYG Editor $content.find('textarea.html').wl_Editor(); //Validation $content.find('input[data-regex]').wl_Valid(); $content.find('input[type=email]').wl_Mail(); $content.find('input[type=url]').wl_URL(); //File Upload $content.find('input[type=file]').wl_File(); //Password and Color $content.find('input[type=password]').wl_Password(); $content.find('input.color').wl_Color(); //Sliders $content.find('div.slider').wl_Slider(); //Multiselects $content.find('select[multiple]').wl_Multiselect(); //The Form is called for the demo with options on line 497 //$content.find('form').wl_Form(); /*----------------------------------------------------------------------*/ /* Alert boxes /*----------------------------------------------------------------------*/ $content.find('div.alert').wl_Alert(); /*----------------------------------------------------------------------*/ /* Breadcrumb /*----------------------------------------------------------------------*/ $content.find('ul.breadcrumb').wl_Breadcrumb(); /*----------------------------------------------------------------------*/ /* datatable plugin /*----------------------------------------------------------------------*/ $content.find("table.datatable").dataTable({ "sPaginationType": "full_numbers" }); /*----------------------------------------------------------------------*/ /* uniform plugin && checkbox plugin (since 1.3.2) /* uniform plugin causes some issues on checkboxes and radios /*----------------------------------------------------------------------*/ $("select, input[type=file]").not('select[multiple]').uniform(); $('input:checkbox, input:radio').checkbox(); /*----------------------------------------------------------------------*/ /* Charts /*----------------------------------------------------------------------*/ $content.find('table.chart').wl_Chart({ onClick: function(value, legend, label, id){ $.msg("value is "+value+" from "+legend+" at "+label+" ("+id+")",{header:'Custom Callback'}); } }); /*----------------------------------------------------------------------*/ /* Fileexplorer /*----------------------------------------------------------------------*/ $content.find('div.fileexplorer').wl_Fileexplorer(); /*----------------------------------------------------------------------*/ /* Calendar (read http://arshaw.com/fullcalendar/docs/ for more info!) /*----------------------------------------------------------------------*/ $content.find('div.calendar').wl_Calendar({ eventSources: [ { url: 'http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/basic' },{ events: [ // put the array in the `events` property { title : 'Fixed Event', start : '2012-02-01' }, { title : 'long fixed Event', start : '2012-02-06', end : '2012-02-14' } ], color: '#f0a8a8', // an option! textColor: '#ffffff' // an option! },{ events: [ // put the array in the `events` property { title : 'Editable', start : '2012-02-09 12:30:00' } ], editable:true, color: '#a2e8a2', // an option! textColor: '#ffffff' // an option! } // any other event sources... ] }); /*----------------------------------------------------------------------*/ /* Gallery /*----------------------------------------------------------------------*/ //defined for the demo on line 518 //$content.find('ul.gallery').wl_Gallery(); /*----------------------------------------------------------------------*/ /* Tipsy Tooltip /*----------------------------------------------------------------------*/ $content.find('input[title]').tipsy({ gravity: function(){return ($(this).data('tooltip-gravity') || config.tooltip.gravity); }, fade: config.tooltip.fade, opacity: config.tooltip.opacity, color: config.tooltip.color, offset: config.tooltip.offset }); /*----------------------------------------------------------------------*/ /* Accordions /*----------------------------------------------------------------------*/ $content.find('div.accordion').accordion({ collapsible:true, autoHeight:false }); /*----------------------------------------------------------------------*/ /* Tabs /*----------------------------------------------------------------------*/ $content.find('div.tab').tabs({ fx: { opacity: 'toggle', duration: 'fast' } }); /*----------------------------------------------------------------------*/ /* Navigation Stuff /*----------------------------------------------------------------------*/ //Top Pageoptions $('#wl_config').click(function(){ var $pageoptions = $('#pageoptions'); if($pageoptions.height() < 200){ $pageoptions.animate({'height':200}); $(this).addClass('active'); }else{ $pageoptions.animate({'height':20}); $(this).removeClass('active'); } return false; }); //Header navigation for smaller screens var $headernav = $('ul#headernav'); $headernav.bind('click',function(){ //if(window.innerWidth > 800) return false; var ul = $headernav.find('ul').eq(0); (ul.is(':hidden')) ? ul.addClass('shown') : ul.removeClass('shown'); }); $headernav.find('ul > li').bind('click',function(event){ event.stopPropagation(); var children = $(this).children('ul'); if(children.length){ (children.is(':hidden')) ? children.addClass('shown') : children.removeClass('shown'); return false; } }); //Search Field Stuff var $searchform = $('#searchform'), $searchfield = $('#search'), livesearch = true; $searchfield .bind({ 'focus.wl': function(){ $searchfield.select().parent().animate({width: '150px'},100); }, 'blur.wl': function(){ $searchfield.parent().animate({width: '90px'},100); if(livesearch)$searchboxresult.fadeOut(); } }); //livesearch is active if(livesearch){ $searchfield.attr('placeholder','Live Search'); var $searchboxresult = $('#searchboxresult'), searchdelay = 800, //delay of search in milliseconds (prevent flooding) searchminimum = 3, //minimum of letter when search should start searchtimeout, searchterm, resulttitle; //insert the container if missing if(!$searchboxresult.length) $searchboxresult = $('<div id="searchboxresult"></div>').insertAfter('#searchbox'); //bind the key event $searchfield .bind({ 'keyup.wl': function(event){ //do nothing if the term hasn't change if(searchterm == $searchfield.val()) return false; //the current search value searchterm = $searchfield.val(); //clear the old timeout and start a new one clearTimeout(searchtimeout); //stop if term is too short if(searchterm.length < searchminimum){ $searchboxresult.fadeOut(); $searchfield.removeClass('load'); return false; } searchtimeout = setTimeout(function(){ $searchfield.addClass('load'); //get results with ajax $.post("search.php", { term: searchterm }, function(data){ $searchfield.removeClass('load'); //search value don't has to be too short if(searchterm.length < searchminimum){ $searchboxresult.fadeOut(); return false; } var count = data.length, html = ''; //we have results if(count){ for(var i = 0; i< count; i++){ resulttitle = ''; if(data[i].text.length > 105){ resulttitle = 'title="'+data[i].text+'"'; data[i].text = $.trim(data[i].text.substr(0,100))+'&hellip;'; } html += '<li><a href="'+data[i].href+'" '+resulttitle+'>'; if(data[i].img) html += '<img src="'+data[i].img+'" width="50">'; html += ''+data[i].text+'</a></li>'; } //no result to this search term }else{ html += '<li><a class="noresult">Nothing found for<br>"'+searchterm+'"</a></li>'; } //insert it and show $searchboxresult.html(html).fadeIn(); }, "json"); },searchdelay); } }); } $searchform .bind('submit.wl',function(){ //do something on submit var query = $searchfield.val(); }); //Main Navigation var $nav = $('#nav'); $nav.delegate('li','click.wl', function(event){ var _this = $(this), _parent = _this.parent(), a = _parent.find('a'); _parent.find('ul').slideUp('fast'); a.removeClass('active'); _this.find('ul:hidden').slideDown('fast'); _this.find('a').eq(0).addClass('active'); event.stopPropagation(); }); /*----------------------------------------------------------------------*/ /* Helpers /*----------------------------------------------------------------------*/ //placholder in inputs is not implemented well in all browsers, so we need to trick this $("[placeholder]").bind('focus.placeholder',function() { var el = $(this); if (el.val() == el.attr("placeholder") && !el.data('uservalue')) { el.val(""); el.removeClass("placeholder"); } }).bind('blur.placeholder',function() { var el = $(this); if (el.val() == "" || el.val() == el.attr("placeholder") && !el.data('uservalue')) { el.addClass("placeholder"); el.val(el.attr("placeholder")); el.data("uservalue",false); }else{ } }).bind('keyup.placeholder',function() { var el = $(this); if (el.val() == "") { el.data("uservalue",false); }else{ el.data("uservalue",true); } }).trigger('blur.placeholder'); /*-----------------------------------------------------------------------------------------------------------------------------*/ /* Following code is for the Demonstration only! /* Get inspired and use it further or just remove it! /*-----------------------------------------------------------------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Callback for Slider /*----------------------------------------------------------------------*/ $content.find('div.slider#slider_callback').wl_Slider({ onSlide:function(value){ $('#slider_callback_bar').width(value+'%').text(value); } }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Rangeslider area how to /* http://revaxarts-themes.com/whitelabel/doc-sliders.html /*----------------------------------------------------------------------*/ $content.find('div.slider#slider_mousewheel').wl_Slider({ onSlide:function(values){ var _this = $('#slider_mousewheel'), _handler = _this.find('a'); _h1 = _handler.eq(0).offset(), _h2 = _handler.eq(1).offset(), value = _h1.left+(_h2.left-_h1.left)/2-_this.offset().left+5; $('#slider_mousewheel_left').width(value); $('#slider_mousewheel_right').width(_this.width()-value); } }); $('#slider_mousewheel_left, #slider_mousewheel_right').bind('mousewheel',function(event,delta){ event.preventDefault(); $.alert('Use the Slider above!\nThis is just for visualisation'); }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Button to clear localStorage /* http://revaxarts-themes.com/whitelabel/widgets.html /*----------------------------------------------------------------------*/ $content.find('.clearLocalStorage').bind('click',function(){ var wl_Store = new $.wl_Store(); if(wl_Store.flush()){ $.msg("LocalStorage as been cleared!"); }; return false; }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* needed for the Store Documentation /* http://revaxarts-themes.com/whitelabel/doc-store.html /*----------------------------------------------------------------------*/ $content.find('#save_store').bind('click',function(){ $.prompt('Storing some values?','This text is for the storage',function(value){ var wl_Store = new $.wl_Store('doc-store'); if(wl_Store.save('testvalue', value)){ $.msg('Your data has been saved!. You can reload the page now!',{live:10000}); }else{ $.msg('Sorry, but a problem while storing your data occurs! Maybe your browser isn\'t supported!',{live:10000}); } }); }); $content.find('#restore_store').bind('click',function(){ var wl_Store = new $.wl_Store('doc-store'); var value = wl_Store.get('testvalue'); if(value){ $.alert('your value is:\n'+value); }else{ $.alert('No value is set!'); } }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Confirm Box for the Form Filler /* http://revaxarts-themes.com/whitelabel/form.html /*----------------------------------------------------------------------*/ $('#formfiller').click(function(){ var _this = this; $.confirm('To fill a form with your data you have to add a query string to the location.\nhttp://domain.tld/path?key=value&key2=value2',function(){ window.location.href = _this.href; }); return false; }); /*----------------------------------------------------------------------*/ /* Toggle to nativ/ajax submit /* http://revaxarts-themes.com/whitelabel/form.html /*----------------------------------------------------------------------*/ $('#formsubmitswitcher').click(function(){ var _this = $(this); if(_this.text() == 'send form natively'){ $content.find('form').wl_Form('set','ajax',false); $.msg('The form will now use the browser native submit method'); _this.text('send form with ajax'); }else{ $content.find('form').wl_Form('set','ajax',true); $.msg('The form will now be sent with an ajax request'); _this.text('send form natively'); } return false; }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* add some Callbacks to the Form /* http://revaxarts-themes.com/whitelabel/form.html /*----------------------------------------------------------------------*/ $content.find('form').wl_Form({ onSuccess: function(data, status){ if(window.console){ console.log(status); console.log(data); }; $.msg("Custom Callback on success\nDevelopers! Check your Console!"); }, onError: function(status, error, jqXHR){ $.msg("Callback on Error\nError Status: "+status+"\nError Msg: "+error); } }); /*----------------------------------------------------------------------*/ /* Gallery with some custom callbacks /* http://revaxarts-themes.com/whitelabel/gallery.html /*----------------------------------------------------------------------*/ $content.find('ul.gallery').wl_Gallery({ onEdit: function(el, href, title){ if(href){ $.confirm('For demonstration I use pixlr to edit images.\nDo you like to continue?',function(){ window.open('http://pixlr.com/editor/?referrer=whitelabel&image='+escape(href)+'&title='+escape(title)+''); }); } }, onDelete: function(el, href, title){ if(href){ $.confirm('Do you really like to delete this?',function(){ el.fadeOut(); }); } }, onMove: function(el, href, title, newOrder){ } }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Message trigger buttons /* http://revaxarts-themes.com/whitelabel/dialogs_and_buttons.html /*----------------------------------------------------------------------*/ $('#message').click(function(){ $.msg("This is a simple Message"); }); $('#message_sticky').click(function(){ $.msg("This Message will stay until you click the cross",{sticky:true}); }); $('#message_header').click(function(){ $.msg("This is with a custom Header",{header:'Custom Header'}); }); $('#message_delay').click(function(){ $.msg("This stays exactly 10 seconds",{live:10000}); }); $('#message_methods').click(function(){ var m = $.msg("This message can be accessed via public methods",{sticky:true}); //do some action with a delay setTimeout(function(){ if(m)m.setHeader('Set a Header'); },3000); setTimeout(function(){ if(m)m.setBody('Set a custom Body'); },5000); setTimeout(function(){ if(m)m.setBody('..and close it with an optional callback function'); },8000); setTimeout(function(){ if(m)m.close(function(){ $.alert('This is the Callback function'); }); },12000); }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Dialog trigger buttons /* http://revaxarts-themes.com/whitelabel/dialogs_and_buttons.html /*----------------------------------------------------------------------*/ $('#dialog').click(function(){ $.alert("This is a simple Message"); }); $('#dialog_confirm').click(function(){ $.confirm("Do you really like to confirm this?", function(){ $.msg("confirmed!"); }, function(){ $.msg("You clicked cancel!"); }); }); $('#dialog_prompt').click(function(){ $.prompt("What do you really like?","Pizza", function(value){ $.msg("So, you like '"+value+"'?"); }, function(){ $.msg("You clicked cancel!"); }); }); $('#dialog_switch').click(function(){ if($.alert.defaults.nativ){ $(this).text('switch to nativ dialogs'); }else{ $(this).text('switch to jQuery Dialogs'); } $.alert.defaults.nativ = !$.alert.defaults.nativ; }); $('#dialog_methods').click(function(){ var a = $.alert("This message can be accessed via public methods"); //do some action with a delay setTimeout(function(){ if(a)a.setHeader('Set a Header'); },3000); setTimeout(function(){ if(a)a.setBody('Set a custom Body'); },5000); setTimeout(function(){ if(a)a.setBody('..and close it with an optional callback function'); },8000); setTimeout(function(){ if(a)a.close(function(){ $.msg('This is the Callback function'); }); },12000); }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Breadcrumb Demos /* http://revaxarts-themes.com/whitelabel/breadcrumb.html /*----------------------------------------------------------------------*/ $('#enablebreadcrumb').click(function(){ $('ul.breadcrumb').eq(4).wl_Breadcrumb('enable'); $.msg('enabled!'); }); $('#disablebreadcrumb').click(function(){ $('ul.breadcrumb').eq(4).wl_Breadcrumb('disable'); $.msg('disabled!'); }); $('ul.breadcrumb').eq(5).wl_Breadcrumb({ onChange:function(element,id){ $.msg(element.text()+' with id '+id); } }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Helps to make current section active in the Mainbar /*----------------------------------------------------------------------*/ var loc = location.pathname.replace(/\/([^.]+)\//g,''); var current = $nav.find('a[href="'+loc+'"]'); if(current.parent().parent().is('#nav')){ current.addClass('active'); }else{ current.parent().parent().parent().find('a').eq(0).addClass('active').next().show(); current.addClass('active'); } /*----------------------------------------------------------------------*/ }); /*----------------------------------------------------------------------*/ /* Autocomplete Function must be available befor wl_Autocomplete is called /*----------------------------------------------------------------------*/ window.myAutocompleteFunction = function(){ return ['Lorem ipsum dolor','sit amet consectetur adipiscing','elit Nulla et justo','est Vestibulum libero','enim adipiscing in','porta mollis sem','Duis lacinia','velit et est rhoncus','mattis Aliquam at','diam eu ipsum','rutrum tincidunt Etiam','nec porta erat Pellentesque','et elit sed sem','bibendum posuere Curabitur id','purus erat vel pretium','erat Ut ultricies semper','quam eu dignissim Cras sed','sapien arcu Phasellus sit amet','venenatis sapien Nulla facilisi','Curabitur ut','bibendum odio Fusce','vitae velit hendrerit','dui convallis tristique','eget nec leo','Vestibulum fermentum leo','ac rutrum interdum mauris','felis sodales arcu','non vehicula odio magna sed','tortor Etiam enim leo','interdum vitae elementum id','laoreet at massa Curabitur nisi dui','lobortis ut rutrum','quis gravida ut velit','Phasellus augue quam gravida non','vulputate vel tempus sit amet','nunc Proin convallis tristique purus']; };
JavaScript
/* * File: jquery.dataTables.js * Version: 1.8.1 * Description: Paginate, search and sort HTML tables * Author: Allan Jardine (www.sprymedia.co.uk) * Created: 28/3/2008 * Language: Javascript * License: GPL v2 or BSD 3 point style * Project: Mtaala * Contact: allan.jardine@sprymedia.co.uk * * Copyright 2008-2011 Allan Jardine, all rights reserved. * * This source file is free software, under either the GPL v2 license or a * BSD style license, as supplied with this software. * * This source file is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details. * * For details please refer to: http://www.datatables.net */ /* * When considering jsLint, we need to allow eval() as it it is used for reading cookies */ /*jslint evil: true, undef: true, browser: true */ /*globals $, jQuery,_fnExternApiFunc,_fnInitalise,_fnInitComplete,_fnLanguageProcess,_fnAddColumn,_fnColumnOptions,_fnAddData,_fnCreateTr,_fnGatherData,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAjaxUpdate,_fnAjaxUpdateDraw,_fnAddOptionsHtml,_fnFeatureHtmlTable,_fnScrollDraw,_fnAjustColumnSizing,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnBuildSearchArray,_fnBuildSearchRow,_fnFilterCreateSearch,_fnDataToSearch,_fnSort,_fnSortAttachListener,_fnSortingClasses,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnFeatureHtmlLength,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnNodeToDataIndex,_fnVisbleColumns,_fnCalculateEnd,_fnConvertToWidth,_fnCalculateColumnWidths,_fnScrollingWidthAdjust,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnArrayCmp,_fnDetectType,_fnSettingsFromNode,_fnGetDataMaster,_fnGetTrNodes,_fnGetTdNodes,_fnEscapeRegex,_fnDeleteIndex,_fnReOrderIndex,_fnColumnOrdering,_fnLog,_fnClearTable,_fnSaveState,_fnLoadState,_fnCreateCookie,_fnReadCookie,_fnDetectHeader,_fnGetUniqueThs,_fnScrollBarWidth,_fnApplyToChildren,_fnMap,_fnGetRowData,_fnGetCellData,_fnSetCellData,_fnGetObjectDataFn,_fnSetObjectDataFn*/ (function($, window, document) { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - DataTables variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Variable: dataTableSettings * Purpose: Store the settings for each dataTables instance * Scope: jQuery.fn */ $.fn.dataTableSettings = []; var _aoSettings = $.fn.dataTableSettings; /* Short reference for fast internal lookup */ /* * Variable: dataTableExt * Purpose: Container for customisable parts of DataTables * Scope: jQuery.fn */ $.fn.dataTableExt = {}; var _oExt = $.fn.dataTableExt; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - DataTables extensible objects * * The _oExt object is used to provide an area where user dfined plugins can be * added to DataTables. The following properties of the object are used: * oApi - Plug-in API functions * aTypes - Auto-detection of types * oSort - Sorting functions used by DataTables (based on the type) * oPagination - Pagination functions for different input styles * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Variable: sVersion * Purpose: Version string for plug-ins to check compatibility * Scope: jQuery.fn.dataTableExt * Notes: Allowed format is a.b.c.d.e where: * a:int, b:int, c:int, d:string(dev|beta), e:int. d and e are optional */ _oExt.sVersion = "1.8.1"; /* * Variable: sErrMode * Purpose: How should DataTables report an error. Can take the value 'alert' or 'throw' * Scope: jQuery.fn.dataTableExt */ _oExt.sErrMode = "alert"; /* * Variable: iApiIndex * Purpose: Index for what 'this' index API functions should use * Scope: jQuery.fn.dataTableExt */ _oExt.iApiIndex = 0; /* * Variable: oApi * Purpose: Container for plugin API functions * Scope: jQuery.fn.dataTableExt */ _oExt.oApi = { }; /* * Variable: aFiltering * Purpose: Container for plugin filtering functions * Scope: jQuery.fn.dataTableExt */ _oExt.afnFiltering = [ ]; /* * Variable: aoFeatures * Purpose: Container for plugin function functions * Scope: jQuery.fn.dataTableExt * Notes: Array of objects with the following parameters: * fnInit: Function for initialisation of Feature. Takes oSettings and returns node * cFeature: Character that will be matched in sDom - case sensitive * sFeature: Feature name - just for completeness :-) */ _oExt.aoFeatures = [ ]; /* * Variable: ofnSearch * Purpose: Container for custom filtering functions * Scope: jQuery.fn.dataTableExt * Notes: This is an object (the name should match the type) for custom filtering function, * which can be used for live DOM checking or formatted text filtering */ _oExt.ofnSearch = { }; /* * Variable: afnSortData * Purpose: Container for custom sorting data source functions * Scope: jQuery.fn.dataTableExt * Notes: Array (associative) of functions which is run prior to a column of this * 'SortDataType' being sorted upon. * Function input parameters: * object:oSettings- DataTables settings object * int:iColumn - Target column number * Return value: Array of data which exactly matched the full data set size for the column to * be sorted upon */ _oExt.afnSortData = [ ]; /* * Variable: oStdClasses * Purpose: Storage for the various classes that DataTables uses * Scope: jQuery.fn.dataTableExt */ _oExt.oStdClasses = { /* Two buttons buttons */ "sPagePrevEnabled": "paginate_enabled_previous", "sPagePrevDisabled": "paginate_disabled_previous", "sPageNextEnabled": "paginate_enabled_next", "sPageNextDisabled": "paginate_disabled_next", "sPageJUINext": "", "sPageJUIPrev": "", /* Full numbers paging buttons */ "sPageButton": "paginate_button", "sPageButtonActive": "paginate_active", "sPageButtonStaticDisabled": "paginate_button paginate_button_disabled", "sPageFirst": "first", "sPagePrevious": "previous", "sPageNext": "next", "sPageLast": "last", /* Stripping classes */ "sStripOdd": "odd", "sStripEven": "even", /* Empty row */ "sRowEmpty": "dataTables_empty", /* Features */ "sWrapper": "dataTables_wrapper", "sFilter": "dataTables_filter", "sInfo": "dataTables_info", "sPaging": "dataTables_paginate paging_", /* Note that the type is postfixed */ "sLength": "dataTables_length", "sProcessing": "dataTables_processing", /* Sorting */ "sSortAsc": "sorting_asc", "sSortDesc": "sorting_desc", "sSortable": "sorting", /* Sortable in both directions */ "sSortableAsc": "sorting_asc_disabled", "sSortableDesc": "sorting_desc_disabled", "sSortableNone": "sorting_disabled", "sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */ "sSortJUIAsc": "", "sSortJUIDesc": "", "sSortJUI": "", "sSortJUIAscAllowed": "", "sSortJUIDescAllowed": "", "sSortJUIWrapper": "", "sSortIcon": "", /* Scrolling */ "sScrollWrapper": "dataTables_scroll", "sScrollHead": "dataTables_scrollHead", "sScrollHeadInner": "dataTables_scrollHeadInner", "sScrollBody": "dataTables_scrollBody", "sScrollFoot": "dataTables_scrollFoot", "sScrollFootInner": "dataTables_scrollFootInner", /* Misc */ "sFooterTH": "" }; /* * Variable: oJUIClasses * Purpose: Storage for the various classes that DataTables uses - jQuery UI suitable * Scope: jQuery.fn.dataTableExt */ _oExt.oJUIClasses = { /* Two buttons buttons */ "sPagePrevEnabled": "fg-button ui-button ui-state-default ui-corner-left", "sPagePrevDisabled": "fg-button ui-button ui-state-default ui-corner-left ui-state-disabled", "sPageNextEnabled": "fg-button ui-button ui-state-default ui-corner-right", "sPageNextDisabled": "fg-button ui-button ui-state-default ui-corner-right ui-state-disabled", "sPageJUINext": "ui-icon ui-icon-circle-arrow-e", "sPageJUIPrev": "ui-icon ui-icon-circle-arrow-w", /* Full numbers paging buttons */ "sPageButton": "fg-button ui-button ui-state-default", "sPageButtonActive": "fg-button ui-button ui-state-default ui-state-disabled", "sPageButtonStaticDisabled": "fg-button ui-button ui-state-default ui-state-disabled", "sPageFirst": "first ui-corner-tl ui-corner-bl", "sPagePrevious": "previous", "sPageNext": "next", "sPageLast": "last ui-corner-tr ui-corner-br", /* Stripping classes */ "sStripOdd": "odd", "sStripEven": "even", /* Empty row */ "sRowEmpty": "dataTables_empty", /* Features */ "sWrapper": "dataTables_wrapper", "sFilter": "dataTables_filter", "sInfo": "dataTables_info", "sPaging": "dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi "+ "ui-buttonset-multi paging_", /* Note that the type is postfixed */ "sLength": "dataTables_length", "sProcessing": "dataTables_processing", /* Sorting */ "sSortAsc": "ui-state-default", "sSortDesc": "ui-state-default", "sSortable": "ui-state-default", "sSortableAsc": "ui-state-default", "sSortableDesc": "ui-state-default", "sSortableNone": "ui-state-default", "sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */ "sSortJUIAsc": "css_right ui-icon ui-icon-triangle-1-n", "sSortJUIDesc": "css_right ui-icon ui-icon-triangle-1-s", "sSortJUI": "css_right ui-icon ui-icon-carat-2-n-s", "sSortJUIAscAllowed": "css_right ui-icon ui-icon-carat-1-n", "sSortJUIDescAllowed": "css_right ui-icon ui-icon-carat-1-s", "sSortJUIWrapper": "DataTables_sort_wrapper", "sSortIcon": "DataTables_sort_icon", /* Scrolling */ "sScrollWrapper": "dataTables_scroll", "sScrollHead": "dataTables_scrollHead ui-state-default", "sScrollHeadInner": "dataTables_scrollHeadInner", "sScrollBody": "dataTables_scrollBody", "sScrollFoot": "dataTables_scrollFoot ui-state-default", "sScrollFootInner": "dataTables_scrollFootInner", /* Misc */ "sFooterTH": "ui-state-default" }; /* * Variable: oPagination * Purpose: Container for the various type of pagination that dataTables supports * Scope: jQuery.fn.dataTableExt */ _oExt.oPagination = { /* * Variable: two_button * Purpose: Standard two button (forward/back) pagination * Scope: jQuery.fn.dataTableExt.oPagination */ "two_button": { /* * Function: oPagination.two_button.fnInit * Purpose: Initalise dom elements required for pagination with forward/back buttons only * Returns: - * Inputs: object:oSettings - dataTables settings object * node:nPaging - the DIV which contains this pagination control * function:fnCallbackDraw - draw function which must be called on update */ "fnInit": function ( oSettings, nPaging, fnCallbackDraw ) { var nPrevious, nNext, nPreviousInner, nNextInner; /* Store the next and previous elements in the oSettings object as they can be very * usful for automation - particularly testing */ if ( !oSettings.bJUI ) { nPrevious = document.createElement( 'div' ); nNext = document.createElement( 'div' ); } else { nPrevious = document.createElement( 'a' ); nNext = document.createElement( 'a' ); nNextInner = document.createElement('span'); nNextInner.className = oSettings.oClasses.sPageJUINext; nNext.appendChild( nNextInner ); nPreviousInner = document.createElement('span'); nPreviousInner.className = oSettings.oClasses.sPageJUIPrev; nPrevious.appendChild( nPreviousInner ); } nPrevious.className = oSettings.oClasses.sPagePrevDisabled; nNext.className = oSettings.oClasses.sPageNextDisabled; nPrevious.title = oSettings.oLanguage.oPaginate.sPrevious; nNext.title = oSettings.oLanguage.oPaginate.sNext; nPaging.appendChild( nPrevious ); nPaging.appendChild( nNext ); $(nPrevious).bind( 'click.DT', function() { if ( oSettings.oApi._fnPageChange( oSettings, "previous" ) ) { /* Only draw when the page has actually changed */ fnCallbackDraw( oSettings ); } } ); $(nNext).bind( 'click.DT', function() { if ( oSettings.oApi._fnPageChange( oSettings, "next" ) ) { fnCallbackDraw( oSettings ); } } ); /* Take the brutal approach to cancelling text selection */ $(nPrevious).bind( 'selectstart.DT', function () { return false; } ); $(nNext).bind( 'selectstart.DT', function () { return false; } ); /* ID the first elements only */ if ( oSettings.sTableId !== '' && typeof oSettings.aanFeatures.p == "undefined" ) { nPaging.setAttribute( 'id', oSettings.sTableId+'_paginate' ); nPrevious.setAttribute( 'id', oSettings.sTableId+'_previous' ); nNext.setAttribute( 'id', oSettings.sTableId+'_next' ); } }, /* * Function: oPagination.two_button.fnUpdate * Purpose: Update the two button pagination at the end of the draw * Returns: - * Inputs: object:oSettings - dataTables settings object * function:fnCallbackDraw - draw function to call on page change */ "fnUpdate": function ( oSettings, fnCallbackDraw ) { if ( !oSettings.aanFeatures.p ) { return; } /* Loop over each instance of the pager */ var an = oSettings.aanFeatures.p; for ( var i=0, iLen=an.length ; i<iLen ; i++ ) { if ( an[i].childNodes.length !== 0 ) { an[i].childNodes[0].className = ( oSettings._iDisplayStart === 0 ) ? oSettings.oClasses.sPagePrevDisabled : oSettings.oClasses.sPagePrevEnabled; an[i].childNodes[1].className = ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() ) ? oSettings.oClasses.sPageNextDisabled : oSettings.oClasses.sPageNextEnabled; } } } }, /* * Variable: iFullNumbersShowPages * Purpose: Change the number of pages which can be seen * Scope: jQuery.fn.dataTableExt.oPagination */ "iFullNumbersShowPages": 5, /* * Variable: full_numbers * Purpose: Full numbers pagination * Scope: jQuery.fn.dataTableExt.oPagination */ "full_numbers": { /* * Function: oPagination.full_numbers.fnInit * Purpose: Initalise dom elements required for pagination with a list of the pages * Returns: - * Inputs: object:oSettings - dataTables settings object * node:nPaging - the DIV which contains this pagination control * function:fnCallbackDraw - draw function which must be called on update */ "fnInit": function ( oSettings, nPaging, fnCallbackDraw ) { var nFirst = document.createElement( 'span' ); var nPrevious = document.createElement( 'span' ); var nList = document.createElement( 'span' ); var nNext = document.createElement( 'span' ); var nLast = document.createElement( 'span' ); nFirst.innerHTML = oSettings.oLanguage.oPaginate.sFirst; nPrevious.innerHTML = oSettings.oLanguage.oPaginate.sPrevious; nNext.innerHTML = oSettings.oLanguage.oPaginate.sNext; nLast.innerHTML = oSettings.oLanguage.oPaginate.sLast; var oClasses = oSettings.oClasses; nFirst.className = oClasses.sPageButton+" "+oClasses.sPageFirst; nPrevious.className = oClasses.sPageButton+" "+oClasses.sPagePrevious; nNext.className= oClasses.sPageButton+" "+oClasses.sPageNext; nLast.className = oClasses.sPageButton+" "+oClasses.sPageLast; nPaging.appendChild( nFirst ); nPaging.appendChild( nPrevious ); nPaging.appendChild( nList ); nPaging.appendChild( nNext ); nPaging.appendChild( nLast ); $(nFirst).bind( 'click.DT', function () { if ( oSettings.oApi._fnPageChange( oSettings, "first" ) ) { fnCallbackDraw( oSettings ); } } ); $(nPrevious).bind( 'click.DT', function() { if ( oSettings.oApi._fnPageChange( oSettings, "previous" ) ) { fnCallbackDraw( oSettings ); } } ); $(nNext).bind( 'click.DT', function() { if ( oSettings.oApi._fnPageChange( oSettings, "next" ) ) { fnCallbackDraw( oSettings ); } } ); $(nLast).bind( 'click.DT', function() { if ( oSettings.oApi._fnPageChange( oSettings, "last" ) ) { fnCallbackDraw( oSettings ); } } ); /* Take the brutal approach to cancelling text selection */ $('span', nPaging) .bind( 'mousedown.DT', function () { return false; } ) .bind( 'selectstart.DT', function () { return false; } ); /* ID the first elements only */ if ( oSettings.sTableId !== '' && typeof oSettings.aanFeatures.p == "undefined" ) { nPaging.setAttribute( 'id', oSettings.sTableId+'_paginate' ); nFirst.setAttribute( 'id', oSettings.sTableId+'_first' ); nPrevious.setAttribute( 'id', oSettings.sTableId+'_previous' ); nNext.setAttribute( 'id', oSettings.sTableId+'_next' ); nLast.setAttribute( 'id', oSettings.sTableId+'_last' ); } }, /* * Function: oPagination.full_numbers.fnUpdate * Purpose: Update the list of page buttons shows * Returns: - * Inputs: object:oSettings - dataTables settings object * function:fnCallbackDraw - draw function to call on page change */ "fnUpdate": function ( oSettings, fnCallbackDraw ) { if ( !oSettings.aanFeatures.p ) { return; } var iPageCount = _oExt.oPagination.iFullNumbersShowPages; var iPageCountHalf = Math.floor(iPageCount / 2); var iPages = Math.ceil((oSettings.fnRecordsDisplay()) / oSettings._iDisplayLength); var iCurrentPage = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1; var sList = ""; var iStartButton, iEndButton, i, iLen; var oClasses = oSettings.oClasses; /* Pages calculation */ if (iPages < iPageCount) { iStartButton = 1; iEndButton = iPages; } else { if (iCurrentPage <= iPageCountHalf) { iStartButton = 1; iEndButton = iPageCount; } else { if (iCurrentPage >= (iPages - iPageCountHalf)) { iStartButton = iPages - iPageCount + 1; iEndButton = iPages; } else { iStartButton = iCurrentPage - Math.ceil(iPageCount / 2) + 1; iEndButton = iStartButton + iPageCount - 1; } } } /* Build the dynamic list */ for ( i=iStartButton ; i<=iEndButton ; i++ ) { if ( iCurrentPage != i ) { sList += '<span class="'+oClasses.sPageButton+'">'+i+'</span>'; } else { sList += '<span class="'+oClasses.sPageButtonActive+'">'+i+'</span>'; } } /* Loop over each instance of the pager */ var an = oSettings.aanFeatures.p; var anButtons, anStatic, nPaginateList; var fnClick = function(e) { /* Use the information in the element to jump to the required page */ var iTarget = (this.innerHTML * 1) - 1; oSettings._iDisplayStart = iTarget * oSettings._iDisplayLength; fnCallbackDraw( oSettings ); e.preventDefault(); }; var fnFalse = function () { return false; }; for ( i=0, iLen=an.length ; i<iLen ; i++ ) { if ( an[i].childNodes.length === 0 ) { continue; } /* Build up the dynamic list forst - html and listeners */ var qjPaginateList = $('span:eq(2)', an[i]); qjPaginateList.html( sList ); $('span', qjPaginateList).bind( 'click.DT', fnClick ).bind( 'mousedown.DT', fnFalse ) .bind( 'selectstart.DT', fnFalse ); /* Update the 'premanent botton's classes */ anButtons = an[i].getElementsByTagName('span'); anStatic = [ anButtons[0], anButtons[1], anButtons[anButtons.length-2], anButtons[anButtons.length-1] ]; $(anStatic).removeClass( oClasses.sPageButton+" "+oClasses.sPageButtonActive+" "+oClasses.sPageButtonStaticDisabled ); if ( iCurrentPage == 1 ) { anStatic[0].className += " "+oClasses.sPageButtonStaticDisabled; anStatic[1].className += " "+oClasses.sPageButtonStaticDisabled; } else { anStatic[0].className += " "+oClasses.sPageButton; anStatic[1].className += " "+oClasses.sPageButton; } if ( iPages === 0 || iCurrentPage == iPages || oSettings._iDisplayLength == -1 ) { anStatic[2].className += " "+oClasses.sPageButtonStaticDisabled; anStatic[3].className += " "+oClasses.sPageButtonStaticDisabled; } else { anStatic[2].className += " "+oClasses.sPageButton; anStatic[3].className += " "+oClasses.sPageButton; } } } } }; /* * Variable: oSort * Purpose: Wrapper for the sorting functions that can be used in DataTables * Scope: jQuery.fn.dataTableExt * Notes: The functions provided in this object are basically standard javascript sort * functions - they expect two inputs which they then compare and then return a priority * result. For each sort method added, two functions need to be defined, an ascending sort and * a descending sort. */ _oExt.oSort = { /* * text sorting */ "string-asc": function ( a, b ) { if ( typeof a != 'string' ) { a = ''; } if ( typeof b != 'string' ) { b = ''; } var x = a.toLowerCase(); var y = b.toLowerCase(); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }, "string-desc": function ( a, b ) { if ( typeof a != 'string' ) { a = ''; } if ( typeof b != 'string' ) { b = ''; } var x = a.toLowerCase(); var y = b.toLowerCase(); return ((x < y) ? 1 : ((x > y) ? -1 : 0)); }, /* * html sorting (ignore html tags) */ "html-asc": function ( a, b ) { var x = a.replace( /<.*?>/g, "" ).toLowerCase(); var y = b.replace( /<.*?>/g, "" ).toLowerCase(); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }, "html-desc": function ( a, b ) { var x = a.replace( /<.*?>/g, "" ).toLowerCase(); var y = b.replace( /<.*?>/g, "" ).toLowerCase(); return ((x < y) ? 1 : ((x > y) ? -1 : 0)); }, /* * date sorting */ "date-asc": function ( a, b ) { var x = Date.parse( a ); var y = Date.parse( b ); if ( isNaN(x) || x==="" ) { x = Date.parse( "01/01/1970 00:00:00" ); } if ( isNaN(y) || y==="" ) { y = Date.parse( "01/01/1970 00:00:00" ); } return x - y; }, "date-desc": function ( a, b ) { var x = Date.parse( a ); var y = Date.parse( b ); if ( isNaN(x) || x==="" ) { x = Date.parse( "01/01/1970 00:00:00" ); } if ( isNaN(y) || y==="" ) { y = Date.parse( "01/01/1970 00:00:00" ); } return y - x; }, /* * numerical sorting */ "numeric-asc": function ( a, b ) { var x = (a=="-" || a==="") ? 0 : a*1; var y = (b=="-" || b==="") ? 0 : b*1; return x - y; }, "numeric-desc": function ( a, b ) { var x = (a=="-" || a==="") ? 0 : a*1; var y = (b=="-" || b==="") ? 0 : b*1; return y - x; } }; /* * Variable: aTypes * Purpose: Container for the various type of type detection that dataTables supports * Scope: jQuery.fn.dataTableExt * Notes: The functions in this array are expected to parse a string to see if it is a data * type that it recognises. If so then the function should return the name of the type (a * corresponding sort function should be defined!), if the type is not recognised then the * function should return null such that the parser and move on to check the next type. * Note that ordering is important in this array - the functions are processed linearly, * starting at index 0. * Note that the input for these functions is always a string! It cannot be any other data * type */ _oExt.aTypes = [ /* * Function: - * Purpose: Check to see if a string is numeric * Returns: string:'numeric' or null * Inputs: mixed:sText - string to check */ function ( sData ) { /* Allow zero length strings as a number */ if ( typeof sData == 'number' ) { return 'numeric'; } else if ( typeof sData != 'string' ) { return null; } var sValidFirstChars = "0123456789-"; var sValidChars = "0123456789."; var Char; var bDecimal = false; /* Check for a valid first char (no period and allow negatives) */ Char = sData.charAt(0); if (sValidFirstChars.indexOf(Char) == -1) { return null; } /* Check all the other characters are valid */ for ( var i=1 ; i<sData.length ; i++ ) { Char = sData.charAt(i); if (sValidChars.indexOf(Char) == -1) { return null; } /* Only allowed one decimal place... */ if ( Char == "." ) { if ( bDecimal ) { return null; } bDecimal = true; } } return 'numeric'; }, /* * Function: - * Purpose: Check to see if a string is actually a formatted date * Returns: string:'date' or null * Inputs: string:sText - string to check */ function ( sData ) { var iParse = Date.parse(sData); if ( (iParse !== null && !isNaN(iParse)) || (typeof sData == 'string' && sData.length === 0) ) { return 'date'; } return null; }, /* * Function: - * Purpose: Check to see if a string should be treated as an HTML string * Returns: string:'html' or null * Inputs: string:sText - string to check */ function ( sData ) { if ( typeof sData == 'string' && sData.indexOf('<') != -1 && sData.indexOf('>') != -1 ) { return 'html'; } return null; } ]; /* * Function: fnVersionCheck * Purpose: Check a version string against this version of DataTables. Useful for plug-ins * Returns: bool:true -this version of DataTables is greater or equal to the required version * false -this version of DataTales is not suitable * Inputs: string:sVersion - the version to check against. May be in the following formats: * "a", "a.b" or "a.b.c" * Notes: This function will only check the first three parts of a version string. It is * assumed that beta and dev versions will meet the requirements. This might change in future */ _oExt.fnVersionCheck = function( sVersion ) { /* This is cheap, but very effective */ var fnZPad = function (Zpad, count) { while(Zpad.length < count) { Zpad += '0'; } return Zpad; }; var aThis = _oExt.sVersion.split('.'); var aThat = sVersion.split('.'); var sThis = '', sThat = ''; for ( var i=0, iLen=aThat.length ; i<iLen ; i++ ) { sThis += fnZPad( aThis[i], 3 ); sThat += fnZPad( aThat[i], 3 ); } return parseInt(sThis, 10) >= parseInt(sThat, 10); }; /* * Variable: _oExternConfig * Purpose: Store information for DataTables to access globally about other instances * Scope: jQuery.fn.dataTableExt */ _oExt._oExternConfig = { /* int:iNextUnique - next unique number for an instance */ "iNextUnique": 0 }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - DataTables prototype * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Function: dataTable * Purpose: DataTables information * Returns: - * Inputs: object:oInit - initalisation options for the table */ $.fn.dataTable = function( oInit ) { /* * Function: classSettings * Purpose: Settings container function for all 'class' properties which are required * by dataTables * Returns: - * Inputs: - */ function classSettings () { this.fnRecordsTotal = function () { if ( this.oFeatures.bServerSide ) { return parseInt(this._iRecordsTotal, 10); } else { return this.aiDisplayMaster.length; } }; this.fnRecordsDisplay = function () { if ( this.oFeatures.bServerSide ) { return parseInt(this._iRecordsDisplay, 10); } else { return this.aiDisplay.length; } }; this.fnDisplayEnd = function () { if ( this.oFeatures.bServerSide ) { if ( this.oFeatures.bPaginate === false || this._iDisplayLength == -1 ) { return this._iDisplayStart+this.aiDisplay.length; } else { return Math.min( this._iDisplayStart+this._iDisplayLength, this._iRecordsDisplay ); } } else { return this._iDisplayEnd; } }; /* * Variable: oInstance * Purpose: The DataTables object for this table * Scope: jQuery.dataTable.classSettings */ this.oInstance = null; /* * Variable: sInstance * Purpose: Unique idendifier for each instance of the DataTables object * Scope: jQuery.dataTable.classSettings */ this.sInstance = null; /* * Variable: oFeatures * Purpose: Indicate the enablement of key dataTable features * Scope: jQuery.dataTable.classSettings */ this.oFeatures = { "bPaginate": true, "bLengthChange": true, "bFilter": true, "bSort": true, "bInfo": true, "bAutoWidth": true, "bProcessing": false, "bSortClasses": true, "bStateSave": false, "bServerSide": false, "bDeferRender": false }; /* * Variable: oScroll * Purpose: Container for scrolling options * Scope: jQuery.dataTable.classSettings */ this.oScroll = { "sX": "", "sXInner": "", "sY": "", "bCollapse": false, "bInfinite": false, "iLoadGap": 100, "iBarWidth": 0, "bAutoCss": true }; /* * Variable: aanFeatures * Purpose: Array referencing the nodes which are used for the features * Scope: jQuery.dataTable.classSettings * Notes: The parameters of this object match what is allowed by sDom - i.e. * 'l' - Length changing * 'f' - Filtering input * 't' - The table! * 'i' - Information * 'p' - Pagination * 'r' - pRocessing */ this.aanFeatures = []; /* * Variable: oLanguage * Purpose: Store the language strings used by dataTables * Scope: jQuery.dataTable.classSettings * Notes: The words in the format _VAR_ are variables which are dynamically replaced * by javascript */ this.oLanguage = { "sProcessing": "Processing...", "sLengthMenu": "Show _MENU_ entries", "sZeroRecords": "No matching records found", "sEmptyTable": "No data available in table", "sLoadingRecords": "Loading...", "sInfo": "Showing _START_ to _END_ of _TOTAL_ entries", "sInfoEmpty": "Showing 0 to 0 of 0 entries", "sInfoFiltered": "(filtered from _MAX_ total entries)", "sInfoPostFix": "", "sSearch": "Search:", "sUrl": "", "oPaginate": { "sFirst": "First", "sPrevious": "Previous", "sNext": "Next", "sLast": "Last" }, "fnInfoCallback": null }; /* * Variable: aoData * Purpose: Store data information * Scope: jQuery.dataTable.classSettings * Notes: This is an array of objects with the following parameters: * int: _iId - internal id for tracking * array: _aData - internal data - used for sorting / filtering etc * node: nTr - display node * array node: _anHidden - hidden TD nodes * string: _sRowStripe */ this.aoData = []; /* * Variable: aiDisplay * Purpose: Array of indexes which are in the current display (after filtering etc) * Scope: jQuery.dataTable.classSettings */ this.aiDisplay = []; /* * Variable: aiDisplayMaster * Purpose: Array of indexes for display - no filtering * Scope: jQuery.dataTable.classSettings */ this.aiDisplayMaster = []; /* * Variable: aoColumns * Purpose: Store information about each column that is in use * Scope: jQuery.dataTable.classSettings */ this.aoColumns = []; /* * Variable: aoHeader * Purpose: Store information about the table's header * Scope: jQuery.dataTable.classSettings */ this.aoHeader = []; /* * Variable: aoFooter * Purpose: Store information about the table's footer * Scope: jQuery.dataTable.classSettings */ this.aoFooter = []; /* * Variable: iNextId * Purpose: Store the next unique id to be used for a new row * Scope: jQuery.dataTable.classSettings */ this.iNextId = 0; /* * Variable: asDataSearch * Purpose: Search data array for regular expression searching * Scope: jQuery.dataTable.classSettings */ this.asDataSearch = []; /* * Variable: oPreviousSearch * Purpose: Store the previous search incase we want to force a re-search * or compare the old search to a new one * Scope: jQuery.dataTable.classSettings */ this.oPreviousSearch = { "sSearch": "", "bRegex": false, "bSmart": true }; /* * Variable: aoPreSearchCols * Purpose: Store the previous search for each column * Scope: jQuery.dataTable.classSettings */ this.aoPreSearchCols = []; /* * Variable: aaSorting * Purpose: Sorting information * Scope: jQuery.dataTable.classSettings * Notes: Index 0 - column number * Index 1 - current sorting direction * Index 2 - index of asSorting for this column */ this.aaSorting = [ [0, 'asc', 0] ]; /* * Variable: aaSortingFixed * Purpose: Sorting information that is always applied * Scope: jQuery.dataTable.classSettings */ this.aaSortingFixed = null; /* * Variable: asStripClasses * Purpose: Classes to use for the striping of a table * Scope: jQuery.dataTable.classSettings */ this.asStripClasses = []; /* * Variable: asDestoryStrips * Purpose: If restoring a table - we should restore it's striping classes as well * Scope: jQuery.dataTable.classSettings */ this.asDestoryStrips = []; /* * Variable: sDestroyWidth * Purpose: If restoring a table - we should restore it's width * Scope: jQuery.dataTable.classSettings */ this.sDestroyWidth = 0; /* * Variable: fnRowCallback * Purpose: Call this function every time a row is inserted (draw) * Scope: jQuery.dataTable.classSettings */ this.fnRowCallback = null; /* * Variable: fnHeaderCallback * Purpose: Callback function for the header on each draw * Scope: jQuery.dataTable.classSettings */ this.fnHeaderCallback = null; /* * Variable: fnFooterCallback * Purpose: Callback function for the footer on each draw * Scope: jQuery.dataTable.classSettings */ this.fnFooterCallback = null; /* * Variable: aoDrawCallback * Purpose: Array of callback functions for draw callback functions * Scope: jQuery.dataTable.classSettings * Notes: Each array element is an object with the following parameters: * function:fn - function to call * string:sName - name callback (feature). useful for arranging array */ this.aoDrawCallback = []; /* * Variable: fnPreDrawCallback * Purpose: Callback function for just before the table is redrawn. A return of false * will be used to cancel the draw. * Scope: jQuery.dataTable.classSettings */ this.fnPreDrawCallback = null; /* * Variable: fnInitComplete * Purpose: Callback function for when the table has been initalised * Scope: jQuery.dataTable.classSettings */ this.fnInitComplete = null; /* * Variable: sTableId * Purpose: Cache the table ID for quick access * Scope: jQuery.dataTable.classSettings */ this.sTableId = ""; /* * Variable: nTable * Purpose: Cache the table node for quick access * Scope: jQuery.dataTable.classSettings */ this.nTable = null; /* * Variable: nTHead * Purpose: Permanent ref to the thead element * Scope: jQuery.dataTable.classSettings */ this.nTHead = null; /* * Variable: nTFoot * Purpose: Permanent ref to the tfoot element - if it exists * Scope: jQuery.dataTable.classSettings */ this.nTFoot = null; /* * Variable: nTBody * Purpose: Permanent ref to the tbody element * Scope: jQuery.dataTable.classSettings */ this.nTBody = null; /* * Variable: nTableWrapper * Purpose: Cache the wrapper node (contains all DataTables controlled elements) * Scope: jQuery.dataTable.classSettings */ this.nTableWrapper = null; /* * Variable: bDeferLoading * Purpose: Indicate if when using server-side processing the loading of data * should be deferred until the second draw * Scope: jQuery.dataTable.classSettings */ this.bDeferLoading = false; /* * Variable: bInitialised * Purpose: Indicate if all required information has been read in * Scope: jQuery.dataTable.classSettings */ this.bInitialised = false; /* * Variable: aoOpenRows * Purpose: Information about open rows * Scope: jQuery.dataTable.classSettings * Notes: Has the parameters 'nTr' and 'nParent' */ this.aoOpenRows = []; /* * Variable: sDom * Purpose: Dictate the positioning that the created elements will take * Scope: jQuery.dataTable.classSettings * Notes: * The following options are allowed: * 'l' - Length changing * 'f' - Filtering input * 't' - The table! * 'i' - Information * 'p' - Pagination * 'r' - pRocessing * The following constants are allowed: * 'H' - jQueryUI theme "header" classes * 'F' - jQueryUI theme "footer" classes * The following syntax is expected: * '<' and '>' - div elements * '<"class" and '>' - div with a class * Examples: * '<"wrapper"flipt>', '<lf<t>ip>' */ this.sDom = 'lfrtip'; /* * Variable: sPaginationType * Purpose: Note which type of sorting should be used * Scope: jQuery.dataTable.classSettings */ this.sPaginationType = "two_button"; /* * Variable: iCookieDuration * Purpose: The cookie duration (for bStateSave) in seconds - default 2 hours * Scope: jQuery.dataTable.classSettings */ this.iCookieDuration = 60 * 60 * 2; /* * Variable: sCookiePrefix * Purpose: The cookie name prefix * Scope: jQuery.dataTable.classSettings */ this.sCookiePrefix = "SpryMedia_DataTables_"; /* * Variable: fnCookieCallback * Purpose: Callback function for cookie creation * Scope: jQuery.dataTable.classSettings */ this.fnCookieCallback = null; /* * Variable: aoStateSave * Purpose: Array of callback functions for state saving * Scope: jQuery.dataTable.classSettings * Notes: Each array element is an object with the following parameters: * function:fn - function to call. Takes two parameters, oSettings and the JSON string to * save that has been thus far created. Returns a JSON string to be inserted into a * json object (i.e. '"param": [ 0, 1, 2]') * string:sName - name of callback */ this.aoStateSave = []; /* * Variable: aoStateLoad * Purpose: Array of callback functions for state loading * Scope: jQuery.dataTable.classSettings * Notes: Each array element is an object with the following parameters: * function:fn - function to call. Takes two parameters, oSettings and the object stored. * May return false to cancel state loading. * string:sName - name of callback */ this.aoStateLoad = []; /* * Variable: oLoadedState * Purpose: State that was loaded from the cookie. Useful for back reference * Scope: jQuery.dataTable.classSettings */ this.oLoadedState = null; /* * Variable: sAjaxSource * Purpose: Source url for AJAX data for the table * Scope: jQuery.dataTable.classSettings */ this.sAjaxSource = null; /* * Variable: sAjaxDataProp * Purpose: Property from a given object from which to read the table data from. This can * be an empty string (when not server-side processing), in which case it is * assumed an an array is given directly. * Scope: jQuery.dataTable.classSettings */ this.sAjaxDataProp = 'aaData'; /* * Variable: bAjaxDataGet * Purpose: Note if draw should be blocked while getting data * Scope: jQuery.dataTable.classSettings */ this.bAjaxDataGet = true; /* * Variable: jqXHR * Purpose: The last jQuery XHR object that was used for server-side data gathering. * This can be used for working with the XHR information in one of the callbacks * Scope: jQuery.dataTable.classSettings */ this.jqXHR = null; /* * Variable: fnServerData * Purpose: Function to get the server-side data - can be overruled by the developer * Scope: jQuery.dataTable.classSettings */ this.fnServerData = function ( url, data, callback, settings ) { settings.jqXHR = $.ajax( { "url": url, "data": data, "success": callback, "dataType": "json", "cache": false, "error": function (xhr, error, thrown) { if ( error == "parsererror" ) { alert( "DataTables warning: JSON data from server could not be parsed. "+ "This is caused by a JSON formatting error." ); } } } ); }; /* * Variable: fnFormatNumber * Purpose: Format numbers for display * Scope: jQuery.dataTable.classSettings */ this.fnFormatNumber = function ( iIn ) { if ( iIn < 1000 ) { /* A small optimisation for what is likely to be the vast majority of use cases */ return iIn; } else { var s=(iIn+""), a=s.split(""), out="", iLen=s.length; for ( var i=0 ; i<iLen ; i++ ) { if ( i%3 === 0 && i !== 0 ) { out = ','+out; } out = a[iLen-i-1]+out; } } return out; }; /* * Variable: aLengthMenu * Purpose: List of options that can be used for the user selectable length menu * Scope: jQuery.dataTable.classSettings * Note: This varaible can take for form of a 1D array, in which case the value and the * displayed value in the menu are the same, or a 2D array in which case the value comes * from the first array, and the displayed value to the end user comes from the second * array. 2D example: [ [ 10, 25, 50, 100, -1 ], [ 10, 25, 50, 100, 'All' ] ]; */ this.aLengthMenu = [ 10, 25, 50, 100 ]; /* * Variable: iDraw * Purpose: Counter for the draws that the table does. Also used as a tracker for * server-side processing * Scope: jQuery.dataTable.classSettings */ this.iDraw = 0; /* * Variable: bDrawing * Purpose: Indicate if a redraw is being done - useful for Ajax * Scope: jQuery.dataTable.classSettings */ this.bDrawing = 0; /* * Variable: iDrawError * Purpose: Last draw error * Scope: jQuery.dataTable.classSettings */ this.iDrawError = -1; /* * Variable: _iDisplayLength, _iDisplayStart, _iDisplayEnd * Purpose: Display length variables * Scope: jQuery.dataTable.classSettings * Notes: These variable must NOT be used externally to get the data length. Rather, use * the fnRecordsTotal() (etc) functions. */ this._iDisplayLength = 10; this._iDisplayStart = 0; this._iDisplayEnd = 10; /* * Variable: _iRecordsTotal, _iRecordsDisplay * Purpose: Display length variables used for server side processing * Scope: jQuery.dataTable.classSettings * Notes: These variable must NOT be used externally to get the data length. Rather, use * the fnRecordsTotal() (etc) functions. */ this._iRecordsTotal = 0; this._iRecordsDisplay = 0; /* * Variable: bJUI * Purpose: Should we add the markup needed for jQuery UI theming? * Scope: jQuery.dataTable.classSettings */ this.bJUI = false; /* * Variable: oClasses * Purpose: Should we add the markup needed for jQuery UI theming? * Scope: jQuery.dataTable.classSettings */ this.oClasses = _oExt.oStdClasses; /* * Variable: bFiltered and bSorted * Purpose: Flags to allow callback functions to see what actions have been performed * Scope: jQuery.dataTable.classSettings */ this.bFiltered = false; this.bSorted = false; /* * Variable: bSortCellsTop * Purpose: Indicate that if multiple rows are in the header and there is more than one * unique cell per column, if the top one (true) or bottom one (false) should * be used for sorting / title by DataTables * Scope: jQuery.dataTable.classSettings */ this.bSortCellsTop = false; /* * Variable: oInit * Purpose: Initialisation object that is used for the table * Scope: jQuery.dataTable.classSettings */ this.oInit = null; } /* * Variable: oApi * Purpose: Container for publicly exposed 'private' functions * Scope: jQuery.dataTable */ this.oApi = {}; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - API functions * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Function: fnDraw * Purpose: Redraw the table * Returns: - * Inputs: bool:bComplete - Refilter and resort (if enabled) the table before the draw. * Optional: default - true */ this.fnDraw = function( bComplete ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); if ( typeof bComplete != 'undefined' && bComplete === false ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } else { _fnReDraw( oSettings ); } }; /* * Function: fnFilter * Purpose: Filter the input based on data * Returns: - * Inputs: string:sInput - string to filter the table on * int:iColumn - optional - column to limit filtering to * bool:bRegex - optional - treat as regular expression or not - default false * bool:bSmart - optional - perform smart filtering or not - default true * bool:bShowGlobal - optional - show the input global filter in it's input box(es) * - default true */ this.fnFilter = function( sInput, iColumn, bRegex, bSmart, bShowGlobal ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); if ( !oSettings.oFeatures.bFilter ) { return; } if ( typeof bRegex == 'undefined' ) { bRegex = false; } if ( typeof bSmart == 'undefined' ) { bSmart = true; } if ( typeof bShowGlobal == 'undefined' ) { bShowGlobal = true; } if ( typeof iColumn == "undefined" || iColumn === null ) { /* Global filter */ _fnFilterComplete( oSettings, { "sSearch":sInput, "bRegex": bRegex, "bSmart": bSmart }, 1 ); if ( bShowGlobal && typeof oSettings.aanFeatures.f != 'undefined' ) { var n = oSettings.aanFeatures.f; for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { $('input', n[i]).val( sInput ); } } } else { /* Single column filter */ oSettings.aoPreSearchCols[ iColumn ].sSearch = sInput; oSettings.aoPreSearchCols[ iColumn ].bRegex = bRegex; oSettings.aoPreSearchCols[ iColumn ].bSmart = bSmart; _fnFilterComplete( oSettings, oSettings.oPreviousSearch, 1 ); } }; /* * Function: fnSettings * Purpose: Get the settings for a particular table for extern. manipulation * Returns: - * Inputs: - */ this.fnSettings = function( nNode ) { return _fnSettingsFromNode( this[_oExt.iApiIndex] ); }; /* * Function: fnVersionCheck * Notes: The function is the same as the 'static' function provided in the ext variable */ this.fnVersionCheck = _oExt.fnVersionCheck; /* * Function: fnSort * Purpose: Sort the table by a particular row * Returns: - * Inputs: int:iCol - the data index to sort on. Note that this will * not match the 'display index' if you have hidden data entries */ this.fnSort = function( aaSort ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); oSettings.aaSorting = aaSort; _fnSort( oSettings ); }; /* * Function: fnSortListener * Purpose: Attach a sort listener to an element for a given column * Returns: - * Inputs: node:nNode - the element to attach the sort listener to * int:iColumn - the column that a click on this node will sort on * function:fnCallback - callback function when sort is run - optional */ this.fnSortListener = function( nNode, iColumn, fnCallback ) { _fnSortAttachListener( _fnSettingsFromNode( this[_oExt.iApiIndex] ), nNode, iColumn, fnCallback ); }; /* * Function: fnAddData * Purpose: Add new row(s) into the table * Returns: array int: array of indexes (aoData) which have been added (zero length on error) * Inputs: array:mData - the data to be added. The length must match * the original data from the DOM * or * array array:mData - 2D array of data to be added * bool:bRedraw - redraw the table or not - default true * Notes: Warning - the refilter here will cause the table to redraw * starting at zero * Notes: Thanks to Yekimov Denis for contributing the basis for this function! */ this.fnAddData = function( mData, bRedraw ) { if ( mData.length === 0 ) { return []; } var aiReturn = []; var iTest; /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); /* Check if we want to add multiple rows or not */ if ( typeof mData[0] == "object" ) { for ( var i=0 ; i<mData.length ; i++ ) { iTest = _fnAddData( oSettings, mData[i] ); if ( iTest == -1 ) { return aiReturn; } aiReturn.push( iTest ); } } else { iTest = _fnAddData( oSettings, mData ); if ( iTest == -1 ) { return aiReturn; } aiReturn.push( iTest ); } oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); if ( typeof bRedraw == 'undefined' || bRedraw ) { _fnReDraw( oSettings ); } return aiReturn; }; /* * Function: fnDeleteRow * Purpose: Remove a row for the table * Returns: array:aReturn - the row that was deleted * Inputs: mixed:mTarget - * int: - index of aoData to be deleted, or * node(TR): - TR element you want to delete * function:fnCallBack - callback function - default null * bool:bRedraw - redraw the table or not - default true */ this.fnDeleteRow = function( mTarget, fnCallBack, bRedraw ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); var i, iAODataIndex; iAODataIndex = (typeof mTarget == 'object') ? _fnNodeToDataIndex(oSettings, mTarget) : mTarget; /* Return the data array from this row */ var oData = oSettings.aoData.splice( iAODataIndex, 1 ); /* Remove the target row from the search array */ var iDisplayIndex = $.inArray( iAODataIndex, oSettings.aiDisplay ); oSettings.asDataSearch.splice( iDisplayIndex, 1 ); /* Delete from the display arrays */ _fnDeleteIndex( oSettings.aiDisplayMaster, iAODataIndex ); _fnDeleteIndex( oSettings.aiDisplay, iAODataIndex ); /* If there is a user callback function - call it */ if ( typeof fnCallBack == "function" ) { fnCallBack.call( this, oSettings, oData ); } /* Check for an 'overflow' they case for dislaying the table */ if ( oSettings._iDisplayStart >= oSettings.aiDisplay.length ) { oSettings._iDisplayStart -= oSettings._iDisplayLength; if ( oSettings._iDisplayStart < 0 ) { oSettings._iDisplayStart = 0; } } if ( typeof bRedraw == 'undefined' || bRedraw ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } return oData; }; /* * Function: fnClearTable * Purpose: Quickly and simply clear a table * Returns: - * Inputs: bool:bRedraw - redraw the table or not - default true * Notes: Thanks to Yekimov Denis for contributing the basis for this function! */ this.fnClearTable = function( bRedraw ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); _fnClearTable( oSettings ); if ( typeof bRedraw == 'undefined' || bRedraw ) { _fnDraw( oSettings ); } }; /* * Function: fnOpen * Purpose: Open a display row (append a row after the row in question) * Returns: node:nNewRow - the row opened * Inputs: node:nTr - the table row to 'open' * string|node|jQuery:mHtml - the HTML to put into the row * string:sClass - class to give the new TD cell */ this.fnOpen = function( nTr, mHtml, sClass ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); /* the old open one if there is one */ this.fnClose( nTr ); var nNewRow = document.createElement("tr"); var nNewCell = document.createElement("td"); nNewRow.appendChild( nNewCell ); nNewCell.className = sClass; nNewCell.colSpan = _fnVisbleColumns( oSettings ); if( typeof mHtml.jquery != 'undefined' || typeof mHtml == "object" ) { nNewCell.appendChild( mHtml ); } else { nNewCell.innerHTML = mHtml; } /* If the nTr isn't on the page at the moment - then we don't insert at the moment */ var nTrs = $('tr', oSettings.nTBody); if ( $.inArray(nTr, nTrs) != -1 ) { $(nNewRow).insertAfter(nTr); } oSettings.aoOpenRows.push( { "nTr": nNewRow, "nParent": nTr } ); return nNewRow; }; /* * Function: fnClose * Purpose: Close a display row * Returns: int: 0 (success) or 1 (failed) * Inputs: node:nTr - the table row to 'close' */ this.fnClose = function( nTr ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); for ( var i=0 ; i<oSettings.aoOpenRows.length ; i++ ) { if ( oSettings.aoOpenRows[i].nParent == nTr ) { var nTrParent = oSettings.aoOpenRows[i].nTr.parentNode; if ( nTrParent ) { /* Remove it if it is currently on display */ nTrParent.removeChild( oSettings.aoOpenRows[i].nTr ); } oSettings.aoOpenRows.splice( i, 1 ); return 0; } } return 1; }; /* * Function: fnGetData * Purpose: Return an array with the data which is used to make up the table * Returns: array array string: 2d data array ([row][column]) or array string: 1d data array * or string if both row and column are given * Inputs: mixed:mRow - optional - if not present, then the full 2D array for the table * if given then: * int: - return data object for aoData entry of this index * node(TR): - return data object for this TR element * int:iCol - optional - the column that you want the data of. This will take into * account mDataProp and return the value DataTables uses for this column */ this.fnGetData = function( mRow, iCol ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); if ( typeof mRow != 'undefined' ) { var iRow = (typeof mRow == 'object') ? _fnNodeToDataIndex(oSettings, mRow) : mRow; if ( typeof iCol != 'undefined' ) { return _fnGetCellData( oSettings, iRow, iCol, '' ); } return (typeof oSettings.aoData[iRow] != 'undefined') ? oSettings.aoData[iRow]._aData : null; } return _fnGetDataMaster( oSettings ); }; /* * Function: fnGetNodes * Purpose: Return an array with the TR nodes used for drawing the table * Returns: array node: TR elements * or * node (if iRow specified) * Inputs: int:iRow - optional - if present then the array returned will be the node for * the row with the index 'iRow' */ this.fnGetNodes = function( iRow ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); if ( typeof iRow != 'undefined' ) { return (typeof oSettings.aoData[iRow] != 'undefined') ? oSettings.aoData[iRow].nTr : null; } return _fnGetTrNodes( oSettings ); }; /* * Function: fnGetPosition * Purpose: Get the array indexes of a particular cell from it's DOM element * Returns: int: - row index, or array[ int, int, int ]: - row index, column index (visible) * and column index including hidden columns * Inputs: node:nNode - this can either be a TR, TD or TH in the table's body, the return is * dependent on this input */ this.fnGetPosition = function( nNode ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); var sNodeName = nNode.nodeName.toUpperCase(); if ( sNodeName == "TR" ) { return _fnNodeToDataIndex(oSettings, nNode); } else if ( sNodeName == "TD" || sNodeName == "TH" ) { var iDataIndex = _fnNodeToDataIndex(oSettings, nNode.parentNode); var anCells = _fnGetTdNodes( oSettings, iDataIndex ); for ( var i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( anCells[i] == nNode ) { return [ iDataIndex, _fnColumnIndexToVisible(oSettings, i ), i ]; } } } return null; }; /* * Function: fnUpdate * Purpose: Update a table cell or row - this method will accept either a single value to * update the cell with, an array of values with one element for each column or * an object in the same format as the original data source. The function is * self-referencing in order to make the multi column updates easier. * Returns: int: 0 okay, 1 error * Inputs: object | array string | string:mData - data to update the cell/row with * mixed:mRow - * int: - index of aoData to be updated, or * node(TR): - TR element you want to update * int:iColumn - the column to update - optional (not used of mData is an array or object) * bool:bRedraw - redraw the table or not - default true * bool:bAction - perform predraw actions or not (you will want this as 'true' if * you have bRedraw as true) - default true */ this.fnUpdate = function( mData, mRow, iColumn, bRedraw, bAction ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); var iVisibleColumn, i, iLen, sDisplay; var iRow = (typeof mRow == 'object') ? _fnNodeToDataIndex(oSettings, mRow) : mRow; if ( $.isArray(mData) && typeof mData == 'object' ) { /* Array update - update the whole row */ oSettings.aoData[iRow]._aData = mData.slice(); for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { this.fnUpdate( _fnGetCellData( oSettings, iRow, i ), iRow, i, false, false ); } } else if ( typeof mData == 'object' ) { /* Object update - update the whole row - assume the developer gets the object right */ oSettings.aoData[iRow]._aData = $.extend( true, {}, mData ); for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { this.fnUpdate( _fnGetCellData( oSettings, iRow, i ), iRow, i, false, false ); } } else { /* Individual cell update */ sDisplay = mData; _fnSetCellData( oSettings, iRow, iColumn, sDisplay ); if ( oSettings.aoColumns[iColumn].fnRender !== null ) { sDisplay = oSettings.aoColumns[iColumn].fnRender( { "iDataRow": iRow, "iDataColumn": iColumn, "aData": oSettings.aoData[iRow]._aData, "oSettings": oSettings } ); if ( oSettings.aoColumns[iColumn].bUseRendered ) { _fnSetCellData( oSettings, iRow, iColumn, sDisplay ); } } if ( oSettings.aoData[iRow].nTr !== null ) { /* Do the actual HTML update */ _fnGetTdNodes( oSettings, iRow )[iColumn].innerHTML = sDisplay; } } /* Modify the search index for this row (strictly this is likely not needed, since fnReDraw * will rebuild the search array - however, the redraw might be disabled by the user) */ var iDisplayIndex = $.inArray( iRow, oSettings.aiDisplay ); oSettings.asDataSearch[iDisplayIndex] = _fnBuildSearchRow( oSettings, _fnGetRowData( oSettings, iRow, 'filter' ) ); /* Perform pre-draw actions */ if ( typeof bAction == 'undefined' || bAction ) { _fnAjustColumnSizing( oSettings ); } /* Redraw the table */ if ( typeof bRedraw == 'undefined' || bRedraw ) { _fnReDraw( oSettings ); } return 0; }; /* * Function: fnShowColoumn * Purpose: Show a particular column * Returns: - * Inputs: int:iCol - the column whose display should be changed * bool:bShow - show (true) or hide (false) the column * bool:bRedraw - redraw the table or not - default true */ this.fnSetColumnVis = function ( iCol, bShow, bRedraw ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); var i, iLen; var iColumns = oSettings.aoColumns.length; var nTd, nCell, anTrs, jqChildren, bAppend, iBefore; /* No point in doing anything if we are requesting what is already true */ if ( oSettings.aoColumns[iCol].bVisible == bShow ) { return; } /* Show the column */ if ( bShow ) { var iInsert = 0; for ( i=0 ; i<iCol ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { iInsert++; } } /* Need to decide if we should use appendChild or insertBefore */ bAppend = (iInsert >= _fnVisbleColumns( oSettings )); /* Which coloumn should we be inserting before? */ if ( !bAppend ) { for ( i=iCol ; i<iColumns ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { iBefore = i; break; } } } for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( oSettings.aoData[i].nTr !== null ) { if ( bAppend ) { oSettings.aoData[i].nTr.appendChild( oSettings.aoData[i]._anHidden[iCol] ); } else { oSettings.aoData[i].nTr.insertBefore( oSettings.aoData[i]._anHidden[iCol], _fnGetTdNodes( oSettings, i )[iBefore] ); } } } } else { /* Remove a column from display */ for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( oSettings.aoData[i].nTr !== null ) { nTd = _fnGetTdNodes( oSettings, i )[iCol]; oSettings.aoData[i]._anHidden[iCol] = nTd; nTd.parentNode.removeChild( nTd ); } } } /* Clear to set the visible flag */ oSettings.aoColumns[iCol].bVisible = bShow; /* Redraw the header and footer based on the new column visibility */ _fnDrawHead( oSettings, oSettings.aoHeader ); if ( oSettings.nTFoot ) { _fnDrawHead( oSettings, oSettings.aoFooter ); } /* If there are any 'open' rows, then we need to alter the colspan for this col change */ for ( i=0, iLen=oSettings.aoOpenRows.length ; i<iLen ; i++ ) { oSettings.aoOpenRows[i].nTr.colSpan = _fnVisbleColumns( oSettings ); } /* Do a redraw incase anything depending on the table columns needs it * (built-in: scrolling) */ if ( typeof bRedraw == 'undefined' || bRedraw ) { _fnAjustColumnSizing( oSettings ); _fnDraw( oSettings ); } _fnSaveState( oSettings ); }; /* * Function: fnPageChange * Purpose: Change the pagination * Returns: - * Inputs: string:sAction - paging action to take: "first", "previous", "next" or "last" * bool:bRedraw - redraw the table or not - optional - default true */ this.fnPageChange = function ( sAction, bRedraw ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); _fnPageChange( oSettings, sAction ); _fnCalculateEnd( oSettings ); if ( typeof bRedraw == 'undefined' || bRedraw ) { _fnDraw( oSettings ); } }; /* * Function: fnDestroy * Purpose: Destructor for the DataTable * Returns: - * Inputs: - */ this.fnDestroy = function ( ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); var nOrig = oSettings.nTableWrapper.parentNode; var nBody = oSettings.nTBody; var i, iLen; /* Flag to note that the table is currently being destoryed - no action should be taken */ oSettings.bDestroying = true; /* Restore hidden columns */ for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { if ( oSettings.aoColumns[i].bVisible === false ) { this.fnSetColumnVis( i, true ); } } /* Blitz all DT events */ $(oSettings.nTableWrapper).find('*').andSelf().unbind('.DT'); /* If there is an 'empty' indicator row, remove it */ $('tbody>tr>td.'+oSettings.oClasses.sRowEmpty, oSettings.nTable).parent().remove(); /* When scrolling we had to break the table up - restore it */ if ( oSettings.nTable != oSettings.nTHead.parentNode ) { $('>thead', oSettings.nTable).remove(); oSettings.nTable.appendChild( oSettings.nTHead ); } if ( oSettings.nTFoot && oSettings.nTable != oSettings.nTFoot.parentNode ) { $('>tfoot', oSettings.nTable).remove(); oSettings.nTable.appendChild( oSettings.nTFoot ); } /* Remove the DataTables generated nodes, events and classes */ oSettings.nTable.parentNode.removeChild( oSettings.nTable ); $(oSettings.nTableWrapper).remove(); oSettings.aaSorting = []; oSettings.aaSortingFixed = []; _fnSortingClasses( oSettings ); $(_fnGetTrNodes( oSettings )).removeClass( oSettings.asStripClasses.join(' ') ); if ( !oSettings.bJUI ) { $('th', oSettings.nTHead).removeClass( [ _oExt.oStdClasses.sSortable, _oExt.oStdClasses.sSortableAsc, _oExt.oStdClasses.sSortableDesc, _oExt.oStdClasses.sSortableNone ].join(' ') ); } else { $('th', oSettings.nTHead).removeClass( [ _oExt.oStdClasses.sSortable, _oExt.oJUIClasses.sSortableAsc, _oExt.oJUIClasses.sSortableDesc, _oExt.oJUIClasses.sSortableNone ].join(' ') ); $('th span.'+_oExt.oJUIClasses.sSortIcon, oSettings.nTHead).remove(); $('th', oSettings.nTHead).each( function () { var jqWrapper = $('div.'+_oExt.oJUIClasses.sSortJUIWrapper, this); var kids = jqWrapper.contents(); $(this).append( kids ); jqWrapper.remove(); } ); } /* Add the TR elements back into the table in their original order */ if ( oSettings.nTableReinsertBefore ) { nOrig.insertBefore( oSettings.nTable, oSettings.nTableReinsertBefore ); } else { nOrig.appendChild( oSettings.nTable ); } for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( oSettings.aoData[i].nTr !== null ) { nBody.appendChild( oSettings.aoData[i].nTr ); } } /* Restore the width of the original table */ if ( oSettings.oFeatures.bAutoWidth === true ) { oSettings.nTable.style.width = _fnStringToCss(oSettings.sDestroyWidth); } /* If the were originally odd/even type classes - then we add them back here. Note * this is not fool proof (for example if not all rows as odd/even classes - but * it's a good effort without getting carried away */ $('>tr:even', nBody).addClass( oSettings.asDestoryStrips[0] ); $('>tr:odd', nBody).addClass( oSettings.asDestoryStrips[1] ); /* Remove the settings object from the settings array */ for ( i=0, iLen=_aoSettings.length ; i<iLen ; i++ ) { if ( _aoSettings[i] == oSettings ) { _aoSettings.splice( i, 1 ); } } /* End it all */ oSettings = null; }; /* * Function: fnAjustColumnSizing * Purpose: Update tale sizing based on content. This would most likely be used for scrolling * and will typically need a redraw after it. * Returns: - * Inputs: bool:bRedraw - redraw the table or not, you will typically want to - default true */ this.fnAdjustColumnSizing = function ( bRedraw ) { var oSettings = _fnSettingsFromNode(this[_oExt.iApiIndex]); _fnAjustColumnSizing( oSettings ); if ( typeof bRedraw == 'undefined' || bRedraw ) { this.fnDraw( false ); } else if ( oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "" ) { /* If not redrawing, but scrolling, we want to apply the new column sizes anyway */ this.oApi._fnScrollDraw(oSettings); } }; /* * Plugin API functions * * This call will add the functions which are defined in _oExt.oApi to the * DataTables object, providing a rather nice way to allow plug-in API functions. Note that * this is done here, so that API function can actually override the built in API functions if * required for a particular purpose. */ /* * Function: _fnExternApiFunc * Purpose: Create a wrapper function for exporting an internal func to an external API func * Returns: function: - wrapped function * Inputs: string:sFunc - API function name */ function _fnExternApiFunc (sFunc) { return function() { var aArgs = [_fnSettingsFromNode(this[_oExt.iApiIndex])].concat( Array.prototype.slice.call(arguments) ); return _oExt.oApi[sFunc].apply( this, aArgs ); }; } for ( var sFunc in _oExt.oApi ) { if ( sFunc ) { /* * Function: anon * Purpose: Wrap the plug-in API functions in order to provide the settings as 1st arg * and execute in this scope * Returns: - * Inputs: - */ this[sFunc] = _fnExternApiFunc(sFunc); } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Local functions * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Initalisation */ /* * Function: _fnInitalise * Purpose: Draw the table for the first time, adding all required features * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnInitalise ( oSettings ) { var i, iLen, iAjaxStart=oSettings.iInitDisplayStart; /* Ensure that the table data is fully initialised */ if ( oSettings.bInitialised === false ) { setTimeout( function(){ _fnInitalise( oSettings ); }, 200 ); return; } /* Show the display HTML options */ _fnAddOptionsHtml( oSettings ); /* Build and draw the header / footer for the table */ _fnBuildHead( oSettings ); _fnDrawHead( oSettings, oSettings.aoHeader ); if ( oSettings.nTFoot ) { _fnDrawHead( oSettings, oSettings.aoFooter ); } /* Okay to show that something is going on now */ _fnProcessingDisplay( oSettings, true ); /* Calculate sizes for columns */ if ( oSettings.oFeatures.bAutoWidth ) { _fnCalculateColumnWidths( oSettings ); } for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { if ( oSettings.aoColumns[i].sWidth !== null ) { oSettings.aoColumns[i].nTh.style.width = _fnStringToCss( oSettings.aoColumns[i].sWidth ); } } /* If there is default sorting required - let's do it. The sort function will do the * drawing for us. Otherwise we draw the table regardless of the Ajax source - this allows * the table to look initialised for Ajax sourcing data (show 'loading' message possibly) */ if ( oSettings.oFeatures.bSort ) { _fnSort( oSettings ); } else if ( oSettings.oFeatures.bFilter ) { _fnFilterComplete( oSettings, oSettings.oPreviousSearch ); } else { oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } /* if there is an ajax source load the data */ if ( oSettings.sAjaxSource !== null && !oSettings.oFeatures.bServerSide ) { oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, [], function(json) { var aData = json; if ( oSettings.sAjaxDataProp !== "" ) { var fnDataSrc = _fnGetObjectDataFn( oSettings.sAjaxDataProp ); aData = fnDataSrc( json ); } /* Got the data - add it to the table */ for ( i=0 ; i<aData.length ; i++ ) { _fnAddData( oSettings, aData[i] ); } /* Reset the init display for cookie saving. We've already done a filter, and * therefore cleared it before. So we need to make it appear 'fresh' */ oSettings.iInitDisplayStart = iAjaxStart; if ( oSettings.oFeatures.bSort ) { _fnSort( oSettings ); } else { oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } _fnProcessingDisplay( oSettings, false ); _fnInitComplete( oSettings, json ); }, oSettings ); return; } /* Server-side processing initialisation complete is done at the end of _fnDraw */ if ( !oSettings.oFeatures.bServerSide ) { _fnProcessingDisplay( oSettings, false ); _fnInitComplete( oSettings ); } } /* * Function: _fnInitalise * Purpose: Draw the table for the first time, adding all required features * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnInitComplete ( oSettings, json ) { oSettings._bInitComplete = true; if ( typeof oSettings.fnInitComplete == 'function' ) { if ( typeof json != 'undefined' ) { oSettings.fnInitComplete.call( oSettings.oInstance, oSettings, json ); } else { oSettings.fnInitComplete.call( oSettings.oInstance, oSettings ); } } } /* * Function: _fnLanguageProcess * Purpose: Copy language variables from remote object to a local one * Returns: - * Inputs: object:oSettings - dataTables settings object * object:oLanguage - Language information * bool:bInit - init once complete */ function _fnLanguageProcess( oSettings, oLanguage, bInit ) { _fnMap( oSettings.oLanguage, oLanguage, 'sProcessing' ); _fnMap( oSettings.oLanguage, oLanguage, 'sLengthMenu' ); _fnMap( oSettings.oLanguage, oLanguage, 'sEmptyTable' ); _fnMap( oSettings.oLanguage, oLanguage, 'sLoadingRecords' ); _fnMap( oSettings.oLanguage, oLanguage, 'sZeroRecords' ); _fnMap( oSettings.oLanguage, oLanguage, 'sInfo' ); _fnMap( oSettings.oLanguage, oLanguage, 'sInfoEmpty' ); _fnMap( oSettings.oLanguage, oLanguage, 'sInfoFiltered' ); _fnMap( oSettings.oLanguage, oLanguage, 'sInfoPostFix' ); _fnMap( oSettings.oLanguage, oLanguage, 'sSearch' ); if ( typeof oLanguage.oPaginate != 'undefined' ) { _fnMap( oSettings.oLanguage.oPaginate, oLanguage.oPaginate, 'sFirst' ); _fnMap( oSettings.oLanguage.oPaginate, oLanguage.oPaginate, 'sPrevious' ); _fnMap( oSettings.oLanguage.oPaginate, oLanguage.oPaginate, 'sNext' ); _fnMap( oSettings.oLanguage.oPaginate, oLanguage.oPaginate, 'sLast' ); } /* Backwards compatibility - if there is no sEmptyTable given, then use the same as * sZeroRecords - assuming that is given. */ if ( typeof oLanguage.sEmptyTable == 'undefined' && typeof oLanguage.sZeroRecords != 'undefined' ) { _fnMap( oSettings.oLanguage, oLanguage, 'sZeroRecords', 'sEmptyTable' ); } /* Likewise with loading records */ if ( typeof oLanguage.sLoadingRecords == 'undefined' && typeof oLanguage.sZeroRecords != 'undefined' ) { _fnMap( oSettings.oLanguage, oLanguage, 'sZeroRecords', 'sLoadingRecords' ); } if ( bInit ) { _fnInitalise( oSettings ); } } /* * Function: _fnAddColumn * Purpose: Add a column to the list used for the table with default values * Returns: - * Inputs: object:oSettings - dataTables settings object * node:nTh - the th element for this column */ function _fnAddColumn( oSettings, nTh ) { var iCol = oSettings.aoColumns.length; var oCol = { "sType": null, "_bAutoType": true, "bVisible": true, "bSearchable": true, "bSortable": true, "asSorting": [ 'asc', 'desc' ], "sSortingClass": oSettings.oClasses.sSortable, "sSortingClassJUI": oSettings.oClasses.sSortJUI, "sTitle": nTh ? nTh.innerHTML : '', "sName": '', "sWidth": null, "sWidthOrig": null, "sClass": null, "fnRender": null, "bUseRendered": true, "iDataSort": iCol, "mDataProp": iCol, "fnGetData": null, "fnSetData": null, "sSortDataType": 'std', "sDefaultContent": null, "sContentPadding": "", "nTh": nTh ? nTh : document.createElement('th'), "nTf": null }; oSettings.aoColumns.push( oCol ); /* Add a column specific filter */ if ( typeof oSettings.aoPreSearchCols[ iCol ] == 'undefined' || oSettings.aoPreSearchCols[ iCol ] === null ) { oSettings.aoPreSearchCols[ iCol ] = { "sSearch": "", "bRegex": false, "bSmart": true }; } else { /* Don't require that the user must specify bRegex and / or bSmart */ if ( typeof oSettings.aoPreSearchCols[ iCol ].bRegex == 'undefined' ) { oSettings.aoPreSearchCols[ iCol ].bRegex = true; } if ( typeof oSettings.aoPreSearchCols[ iCol ].bSmart == 'undefined' ) { oSettings.aoPreSearchCols[ iCol ].bSmart = true; } } /* Use the column options function to initialise classes etc */ _fnColumnOptions( oSettings, iCol, null ); } /* * Function: _fnColumnOptions * Purpose: Apply options for a column * Returns: - * Inputs: object:oSettings - dataTables settings object * int:iCol - column index to consider * object:oOptions - object with sType, bVisible and bSearchable */ function _fnColumnOptions( oSettings, iCol, oOptions ) { var oCol = oSettings.aoColumns[ iCol ]; /* User specified column options */ if ( typeof oOptions != 'undefined' && oOptions !== null ) { if ( typeof oOptions.sType != 'undefined' ) { oCol.sType = oOptions.sType; oCol._bAutoType = false; } _fnMap( oCol, oOptions, "bVisible" ); _fnMap( oCol, oOptions, "bSearchable" ); _fnMap( oCol, oOptions, "bSortable" ); _fnMap( oCol, oOptions, "sTitle" ); _fnMap( oCol, oOptions, "sName" ); _fnMap( oCol, oOptions, "sWidth" ); _fnMap( oCol, oOptions, "sWidth", "sWidthOrig" ); _fnMap( oCol, oOptions, "sClass" ); _fnMap( oCol, oOptions, "fnRender" ); _fnMap( oCol, oOptions, "bUseRendered" ); _fnMap( oCol, oOptions, "iDataSort" ); _fnMap( oCol, oOptions, "mDataProp" ); _fnMap( oCol, oOptions, "asSorting" ); _fnMap( oCol, oOptions, "sSortDataType" ); _fnMap( oCol, oOptions, "sDefaultContent" ); _fnMap( oCol, oOptions, "sContentPadding" ); } /* Cache the data get and set functions for speed */ oCol.fnGetData = _fnGetObjectDataFn( oCol.mDataProp ); oCol.fnSetData = _fnSetObjectDataFn( oCol.mDataProp ); /* Feature sorting overrides column specific when off */ if ( !oSettings.oFeatures.bSort ) { oCol.bSortable = false; } /* Check that the class assignment is correct for sorting */ if ( !oCol.bSortable || ($.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) == -1) ) { oCol.sSortingClass = oSettings.oClasses.sSortableNone; oCol.sSortingClassJUI = ""; } else if ( oCol.bSortable || ($.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) == -1) ) { oCol.sSortingClass = oSettings.oClasses.sSortable; oCol.sSortingClassJUI = oSettings.oClasses.sSortJUI; } else if ( $.inArray('asc', oCol.asSorting) != -1 && $.inArray('desc', oCol.asSorting) == -1 ) { oCol.sSortingClass = oSettings.oClasses.sSortableAsc; oCol.sSortingClassJUI = oSettings.oClasses.sSortJUIAscAllowed; } else if ( $.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) != -1 ) { oCol.sSortingClass = oSettings.oClasses.sSortableDesc; oCol.sSortingClassJUI = oSettings.oClasses.sSortJUIDescAllowed; } } /* * Function: _fnAddData * Purpose: Add a data array to the table, creating DOM node etc * Returns: int: - >=0 if successful (index of new aoData entry), -1 if failed * Inputs: object:oSettings - dataTables settings object * array:aData - data array to be added * Notes: There are two basic methods for DataTables to get data to display - a JS array * (which is dealt with by this function), and the DOM, which has it's own optimised * function (_fnGatherData). Be careful to make the same changes here as there and vice-versa */ function _fnAddData ( oSettings, aDataSupplied ) { var oCol; /* Take an independent copy of the data source so we can bash it about as we wish */ var aDataIn = (typeof aDataSupplied.length == 'number') ? aDataSupplied.slice() : $.extend( true, {}, aDataSupplied ); /* Create the object for storing information about this new row */ var iRow = oSettings.aoData.length; var oData = { "nTr": null, "_iId": oSettings.iNextId++, "_aData": aDataIn, "_anHidden": [], "_sRowStripe": "" }; oSettings.aoData.push( oData ); /* Create the cells */ var nTd, sThisType; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { oCol = oSettings.aoColumns[i]; /* Use rendered data for filtering/sorting */ if ( typeof oCol.fnRender == 'function' && oCol.bUseRendered && oCol.mDataProp !== null ) { _fnSetCellData( oSettings, iRow, i, oCol.fnRender( { "iDataRow": iRow, "iDataColumn": i, "aData": oData._aData, "oSettings": oSettings } ) ); } /* See if we should auto-detect the column type */ if ( oCol._bAutoType && oCol.sType != 'string' ) { /* Attempt to auto detect the type - same as _fnGatherData() */ var sVarType = _fnGetCellData( oSettings, iRow, i, 'type' ); if ( sVarType !== null && sVarType !== '' ) { sThisType = _fnDetectType( sVarType ); if ( oCol.sType === null ) { oCol.sType = sThisType; } else if ( oCol.sType != sThisType ) { /* String is always the 'fallback' option */ oCol.sType = 'string'; } } } } /* Add to the display array */ oSettings.aiDisplayMaster.push( iRow ); /* Create the DOM imformation */ if ( !oSettings.oFeatures.bDeferRender ) { _fnCreateTr( oSettings, iRow ); } return iRow; } /* * Function: _fnCreateTr * Purpose: Create a new TR element (and it's TD children) for a row * Returns: void * Inputs: object:oSettings - dataTables settings object * int:iRow - Row to consider */ function _fnCreateTr ( oSettings, iRow ) { var oData = oSettings.aoData[iRow]; var nTd; if ( oData.nTr === null ) { oData.nTr = document.createElement('tr'); /* Special parameters can be given by the data source to be used on the row */ if ( typeof oData._aData.DT_RowId != 'undefined' ) { oData.nTr.setAttribute( 'id', oData._aData.DT_RowId ); } if ( typeof oData._aData.DT_RowClass != 'undefined' ) { $(oData.nTr).addClass( oData._aData.DT_RowClass ); } /* Process each column */ for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { var oCol = oSettings.aoColumns[i]; nTd = document.createElement('td'); /* Render if needed - if bUseRendered is true then we already have the rendered * value in the data source - so can just use that */ if ( typeof oCol.fnRender == 'function' && (!oCol.bUseRendered || oCol.mDataProp === null) ) { nTd.innerHTML = oCol.fnRender( { "iDataRow": iRow, "iDataColumn": i, "aData": oData._aData, "oSettings": oSettings } ); } else { nTd.innerHTML = _fnGetCellData( oSettings, iRow, i, 'display' ); } /* Add user defined class */ if ( oCol.sClass !== null ) { nTd.className = oCol.sClass; } if ( oCol.bVisible ) { oData.nTr.appendChild( nTd ); oData._anHidden[i] = null; } else { oData._anHidden[i] = nTd; } } } } /* * Function: _fnGatherData * Purpose: Read in the data from the target table from the DOM * Returns: - * Inputs: object:oSettings - dataTables settings object * Notes: This is a optimised version of _fnAddData (more or less) for reading information * from the DOM. The basic actions must be identical in the two functions. */ function _fnGatherData( oSettings ) { var iLoop, i, iLen, j, jLen, jInner, nTds, nTrs, nTd, aLocalData, iThisIndex, iRow, iRows, iColumn, iColumns, sNodeName; /* * Process by row first * Add the data object for the whole table - storing the tr node. Note - no point in getting * DOM based data if we are going to go and replace it with Ajax source data. */ if ( oSettings.bDeferLoading || oSettings.sAjaxSource === null ) { nTrs = oSettings.nTBody.childNodes; for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { if ( nTrs[i].nodeName.toUpperCase() == "TR" ) { iThisIndex = oSettings.aoData.length; oSettings.aoData.push( { "nTr": nTrs[i], "_iId": oSettings.iNextId++, "_aData": [], "_anHidden": [], "_sRowStripe": '' } ); oSettings.aiDisplayMaster.push( iThisIndex ); nTds = nTrs[i].childNodes; jInner = 0; for ( j=0, jLen=nTds.length ; j<jLen ; j++ ) { sNodeName = nTds[j].nodeName.toUpperCase(); if ( sNodeName == "TD" || sNodeName == "TH" ) { _fnSetCellData( oSettings, iThisIndex, jInner, $.trim(nTds[j].innerHTML) ); jInner++; } } } } } /* Gather in the TD elements of the Table - note that this is basically the same as * fnGetTdNodes, but that function takes account of hidden columns, which we haven't yet * setup! */ nTrs = _fnGetTrNodes( oSettings ); nTds = []; for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { for ( j=0, jLen=nTrs[i].childNodes.length ; j<jLen ; j++ ) { nTd = nTrs[i].childNodes[j]; sNodeName = nTd.nodeName.toUpperCase(); if ( sNodeName == "TD" || sNodeName == "TH" ) { nTds.push( nTd ); } } } /* Sanity check */ if ( nTds.length != nTrs.length * oSettings.aoColumns.length ) { _fnLog( oSettings, 1, "Unexpected number of TD elements. Expected "+ (nTrs.length * oSettings.aoColumns.length)+" and got "+nTds.length+". DataTables does "+ "not support rowspan / colspan in the table body, and there must be one cell for each "+ "row/column combination." ); } /* Now process by column */ for ( iColumn=0, iColumns=oSettings.aoColumns.length ; iColumn<iColumns ; iColumn++ ) { /* Get the title of the column - unless there is a user set one */ if ( oSettings.aoColumns[iColumn].sTitle === null ) { oSettings.aoColumns[iColumn].sTitle = oSettings.aoColumns[iColumn].nTh.innerHTML; } var bAutoType = oSettings.aoColumns[iColumn]._bAutoType, bRender = typeof oSettings.aoColumns[iColumn].fnRender == 'function', bClass = oSettings.aoColumns[iColumn].sClass !== null, bVisible = oSettings.aoColumns[iColumn].bVisible, nCell, sThisType, sRendered, sValType; /* A single loop to rule them all (and be more efficient) */ if ( bAutoType || bRender || bClass || !bVisible ) { for ( iRow=0, iRows=oSettings.aoData.length ; iRow<iRows ; iRow++ ) { nCell = nTds[ (iRow*iColumns) + iColumn ]; /* Type detection */ if ( bAutoType && oSettings.aoColumns[iColumn].sType != 'string' ) { sValType = _fnGetCellData( oSettings, iRow, iColumn, 'type' ); if ( sValType !== '' ) { sThisType = _fnDetectType( sValType ); if ( oSettings.aoColumns[iColumn].sType === null ) { oSettings.aoColumns[iColumn].sType = sThisType; } else if ( oSettings.aoColumns[iColumn].sType != sThisType ) { /* String is always the 'fallback' option */ oSettings.aoColumns[iColumn].sType = 'string'; } } } /* Rendering */ if ( bRender ) { sRendered = oSettings.aoColumns[iColumn].fnRender( { "iDataRow": iRow, "iDataColumn": iColumn, "aData": oSettings.aoData[iRow]._aData, "oSettings": oSettings } ); nCell.innerHTML = sRendered; if ( oSettings.aoColumns[iColumn].bUseRendered ) { /* Use the rendered data for filtering/sorting */ _fnSetCellData( oSettings, iRow, iColumn, sRendered ); } } /* Classes */ if ( bClass ) { nCell.className += ' '+oSettings.aoColumns[iColumn].sClass; } /* Column visability */ if ( !bVisible ) { oSettings.aoData[iRow]._anHidden[iColumn] = nCell; nCell.parentNode.removeChild( nCell ); } else { oSettings.aoData[iRow]._anHidden[iColumn] = null; } } } } } /* * Function: _fnBuildHead * Purpose: Create the HTML header for the table * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnBuildHead( oSettings ) { var i, nTh, iLen, j, jLen; var anTr = oSettings.nTHead.getElementsByTagName('tr'); var iThs = oSettings.nTHead.getElementsByTagName('th').length; var iCorrector = 0; var jqChildren; /* If there is a header in place - then use it - otherwise it's going to get nuked... */ if ( iThs !== 0 ) { /* We've got a thead from the DOM, so remove hidden columns and apply width to vis cols */ for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { nTh = oSettings.aoColumns[i].nTh; if ( oSettings.aoColumns[i].sClass !== null ) { $(nTh).addClass( oSettings.aoColumns[i].sClass ); } /* Set the title of the column if it is user defined (not what was auto detected) */ if ( oSettings.aoColumns[i].sTitle != nTh.innerHTML ) { nTh.innerHTML = oSettings.aoColumns[i].sTitle; } } } else { /* We don't have a header in the DOM - so we are going to have to create one */ var nTr = document.createElement( "tr" ); for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { nTh = oSettings.aoColumns[i].nTh; nTh.innerHTML = oSettings.aoColumns[i].sTitle; if ( oSettings.aoColumns[i].sClass !== null ) { $(nTh).addClass( oSettings.aoColumns[i].sClass ); } nTr.appendChild( nTh ); } $(oSettings.nTHead).html( '' )[0].appendChild( nTr ); _fnDetectHeader( oSettings.aoHeader, oSettings.nTHead ); } /* Add the extra markup needed by jQuery UI's themes */ if ( oSettings.bJUI ) { for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { nTh = oSettings.aoColumns[i].nTh; var nDiv = document.createElement('div'); nDiv.className = oSettings.oClasses.sSortJUIWrapper; $(nTh).contents().appendTo(nDiv); var nSpan = document.createElement('span'); nSpan.className = oSettings.oClasses.sSortIcon; nDiv.appendChild( nSpan ); nTh.appendChild( nDiv ); } } /* Add sort listener */ var fnNoSelect = function (e) { this.onselectstart = function() { return false; }; return false; }; if ( oSettings.oFeatures.bSort ) { for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bSortable !== false ) { _fnSortAttachListener( oSettings, oSettings.aoColumns[i].nTh, i ); /* Take the brutal approach to cancelling text selection in header */ $(oSettings.aoColumns[i].nTh).bind( 'mousedown.DT', fnNoSelect ); } else { $(oSettings.aoColumns[i].nTh).addClass( oSettings.oClasses.sSortableNone ); } } } /* Deal with the footer - add classes if required */ if ( oSettings.oClasses.sFooterTH !== "" ) { $('>tr>th', oSettings.nTFoot).addClass( oSettings.oClasses.sFooterTH ); } /* Cache the footer elements */ if ( oSettings.nTFoot !== null ) { var anCells = _fnGetUniqueThs( oSettings, null, oSettings.aoFooter ); for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { if ( typeof anCells[i] != 'undefined' ) { oSettings.aoColumns[i].nTf = anCells[i]; } } } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Drawing functions */ /* * Function: _fnDrawHead * Purpose: Draw the header (or footer) element based on the column visibility states. The * methodology here is to use the layout array from _fnDetectHeader, modified for * the instantaneous column visibility, to construct the new layout. The grid is * traversed over cell at a time in a rows x columns grid fashion, although each * cell insert can cover multiple elements in the grid - which is tracks using the * aApplied array. Cell inserts in the grid will only occur where there isn't * already a cell in that position. * Returns: - * Inputs: object:oSettings - dataTables settings object * array objects:aoSource - Layout array from _fnDetectHeader * boolean:bIncludeHidden - If true then include the hidden columns in the calc, * - optional: default false */ function _fnDrawHead( oSettings, aoSource, bIncludeHidden ) { var i, iLen, j, jLen, k, kLen; var aoLocal = []; var aApplied = []; var iColumns = oSettings.aoColumns.length; var iRowspan, iColspan; if ( typeof bIncludeHidden == 'undefined' ) { bIncludeHidden = false; } /* Make a copy of the master layout array, but without the visible columns in it */ for ( i=0, iLen=aoSource.length ; i<iLen ; i++ ) { aoLocal[i] = aoSource[i].slice(); aoLocal[i].nTr = aoSource[i].nTr; /* Remove any columns which are currently hidden */ for ( j=iColumns-1 ; j>=0 ; j-- ) { if ( !oSettings.aoColumns[j].bVisible && !bIncludeHidden ) { aoLocal[i].splice( j, 1 ); } } /* Prep the applied array - it needs an element for each row */ aApplied.push( [] ); } for ( i=0, iLen=aoLocal.length ; i<iLen ; i++ ) { /* All cells are going to be replaced, so empty out the row */ if ( aoLocal[i].nTr ) { for ( k=0, kLen=aoLocal[i].nTr.childNodes.length ; k<kLen ; k++ ) { aoLocal[i].nTr.removeChild( aoLocal[i].nTr.childNodes[0] ); } } for ( j=0, jLen=aoLocal[i].length ; j<jLen ; j++ ) { iRowspan = 1; iColspan = 1; /* Check to see if there is already a cell (row/colspan) covering our target * insert point. If there is, then there is nothing to do. */ if ( typeof aApplied[i][j] == 'undefined' ) { aoLocal[i].nTr.appendChild( aoLocal[i][j].cell ); aApplied[i][j] = 1; /* Expand the cell to cover as many rows as needed */ while ( typeof aoLocal[i+iRowspan] != 'undefined' && aoLocal[i][j].cell == aoLocal[i+iRowspan][j].cell ) { aApplied[i+iRowspan][j] = 1; iRowspan++; } /* Expand the cell to cover as many columns as needed */ while ( typeof aoLocal[i][j+iColspan] != 'undefined' && aoLocal[i][j].cell == aoLocal[i][j+iColspan].cell ) { /* Must update the applied array over the rows for the columns */ for ( k=0 ; k<iRowspan ; k++ ) { aApplied[i+k][j+iColspan] = 1; } iColspan++; } /* Do the actual expansion in the DOM */ aoLocal[i][j].cell.setAttribute('rowspan', iRowspan); aoLocal[i][j].cell.setAttribute('colspan', iColspan); } } } } /* * Function: _fnDraw * Purpose: Insert the required TR nodes into the table for display * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnDraw( oSettings ) { var i, iLen; var anRows = []; var iRowCount = 0; var bRowError = false; var iStrips = oSettings.asStripClasses.length; var iOpenRows = oSettings.aoOpenRows.length; /* Provide a pre-callback function which can be used to cancel the draw is false is returned */ if ( oSettings.fnPreDrawCallback !== null && oSettings.fnPreDrawCallback.call( oSettings.oInstance, oSettings ) === false ) { return; } oSettings.bDrawing = true; /* Check and see if we have an initial draw position from state saving */ if ( typeof oSettings.iInitDisplayStart != 'undefined' && oSettings.iInitDisplayStart != -1 ) { if ( oSettings.oFeatures.bServerSide ) { oSettings._iDisplayStart = oSettings.iInitDisplayStart; } else { oSettings._iDisplayStart = (oSettings.iInitDisplayStart >= oSettings.fnRecordsDisplay()) ? 0 : oSettings.iInitDisplayStart; } oSettings.iInitDisplayStart = -1; _fnCalculateEnd( oSettings ); } /* Server-side processing draw intercept */ if ( oSettings.bDeferLoading ) { oSettings.bDeferLoading = false; oSettings.iDraw++; } else if ( !oSettings.oFeatures.bServerSide ) { oSettings.iDraw++; } else if ( !oSettings.bDestroying && !_fnAjaxUpdate( oSettings ) ) { return; } if ( oSettings.aiDisplay.length !== 0 ) { var iStart = oSettings._iDisplayStart; var iEnd = oSettings._iDisplayEnd; if ( oSettings.oFeatures.bServerSide ) { iStart = 0; iEnd = oSettings.aoData.length; } for ( var j=iStart ; j<iEnd ; j++ ) { var aoData = oSettings.aoData[ oSettings.aiDisplay[j] ]; if ( aoData.nTr === null ) { _fnCreateTr( oSettings, oSettings.aiDisplay[j] ); } var nRow = aoData.nTr; /* Remove the old stripping classes and then add the new one */ if ( iStrips !== 0 ) { var sStrip = oSettings.asStripClasses[ iRowCount % iStrips ]; if ( aoData._sRowStripe != sStrip ) { $(nRow).removeClass( aoData._sRowStripe ).addClass( sStrip ); aoData._sRowStripe = sStrip; } } /* Custom row callback function - might want to manipule the row */ if ( typeof oSettings.fnRowCallback == "function" ) { nRow = oSettings.fnRowCallback.call( oSettings.oInstance, nRow, oSettings.aoData[ oSettings.aiDisplay[j] ]._aData, iRowCount, j ); if ( !nRow && !bRowError ) { _fnLog( oSettings, 0, "A node was not returned by fnRowCallback" ); bRowError = true; } } anRows.push( nRow ); iRowCount++; /* If there is an open row - and it is attached to this parent - attach it on redraw */ if ( iOpenRows !== 0 ) { for ( var k=0 ; k<iOpenRows ; k++ ) { if ( nRow == oSettings.aoOpenRows[k].nParent ) { anRows.push( oSettings.aoOpenRows[k].nTr ); } } } } } else { /* Table is empty - create a row with an empty message in it */ anRows[ 0 ] = document.createElement( 'tr' ); if ( typeof oSettings.asStripClasses[0] != 'undefined' ) { anRows[ 0 ].className = oSettings.asStripClasses[0]; } var sZero = oSettings.oLanguage.sZeroRecords.replace( '_MAX_', oSettings.fnFormatNumber(oSettings.fnRecordsTotal()) ); if ( oSettings.iDraw == 1 && oSettings.sAjaxSource !== null && !oSettings.oFeatures.bServerSide ) { sZero = oSettings.oLanguage.sLoadingRecords; } else if ( typeof oSettings.oLanguage.sEmptyTable != 'undefined' && oSettings.fnRecordsTotal() === 0 ) { sZero = oSettings.oLanguage.sEmptyTable; } var nTd = document.createElement( 'td' ); nTd.setAttribute( 'valign', "top" ); nTd.colSpan = _fnVisbleColumns( oSettings ); nTd.className = oSettings.oClasses.sRowEmpty; nTd.innerHTML = sZero; anRows[ iRowCount ].appendChild( nTd ); } /* Callback the header and footer custom funcation if there is one */ if ( typeof oSettings.fnHeaderCallback == 'function' ) { oSettings.fnHeaderCallback.call( oSettings.oInstance, $('>tr', oSettings.nTHead)[0], _fnGetDataMaster( oSettings ), oSettings._iDisplayStart, oSettings.fnDisplayEnd(), oSettings.aiDisplay ); } if ( typeof oSettings.fnFooterCallback == 'function' ) { oSettings.fnFooterCallback.call( oSettings.oInstance, $('>tr', oSettings.nTFoot)[0], _fnGetDataMaster( oSettings ), oSettings._iDisplayStart, oSettings.fnDisplayEnd(), oSettings.aiDisplay ); } /* * Need to remove any old row from the display - note we can't just empty the tbody using * $().html('') since this will unbind the jQuery event handlers (even although the node * still exists!) - equally we can't use innerHTML, since IE throws an exception. */ var nAddFrag = document.createDocumentFragment(), nRemoveFrag = document.createDocumentFragment(), nBodyPar, nTrs; if ( oSettings.nTBody ) { nBodyPar = oSettings.nTBody.parentNode; nRemoveFrag.appendChild( oSettings.nTBody ); /* When doing infinite scrolling, only remove child rows when sorting, filtering or start * up. When not infinite scroll, always do it. */ if ( !oSettings.oScroll.bInfinite || !oSettings._bInitComplete || oSettings.bSorted || oSettings.bFiltered ) { nTrs = oSettings.nTBody.childNodes; for ( i=nTrs.length-1 ; i>=0 ; i-- ) { nTrs[i].parentNode.removeChild( nTrs[i] ); } } /* Put the draw table into the dom */ for ( i=0, iLen=anRows.length ; i<iLen ; i++ ) { nAddFrag.appendChild( anRows[i] ); } oSettings.nTBody.appendChild( nAddFrag ); if ( nBodyPar !== null ) { nBodyPar.appendChild( oSettings.nTBody ); } } /* Call all required callback functions for the end of a draw */ for ( i=oSettings.aoDrawCallback.length-1 ; i>=0 ; i-- ) { oSettings.aoDrawCallback[i].fn.call( oSettings.oInstance, oSettings ); } /* Draw is complete, sorting and filtering must be as well */ oSettings.bSorted = false; oSettings.bFiltered = false; oSettings.bDrawing = false; if ( oSettings.oFeatures.bServerSide ) { _fnProcessingDisplay( oSettings, false ); if ( typeof oSettings._bInitComplete == 'undefined' ) { _fnInitComplete( oSettings ); } } } /* * Function: _fnReDraw * Purpose: Redraw the table - taking account of the various features which are enabled * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnReDraw( oSettings ) { if ( oSettings.oFeatures.bSort ) { /* Sorting will refilter and draw for us */ _fnSort( oSettings, oSettings.oPreviousSearch ); } else if ( oSettings.oFeatures.bFilter ) { /* Filtering will redraw for us */ _fnFilterComplete( oSettings, oSettings.oPreviousSearch ); } else { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } } /* * Function: _fnAjaxUpdate * Purpose: Update the table using an Ajax call * Returns: bool: block the table drawing or not * Inputs: object:oSettings - dataTables settings object */ function _fnAjaxUpdate( oSettings ) { if ( oSettings.bAjaxDataGet ) { _fnProcessingDisplay( oSettings, true ); var iColumns = oSettings.aoColumns.length; var aoData = [], mDataProp; var i; /* Paging and general */ oSettings.iDraw++; aoData.push( { "name": "sEcho", "value": oSettings.iDraw } ); aoData.push( { "name": "iColumns", "value": iColumns } ); aoData.push( { "name": "sColumns", "value": _fnColumnOrdering(oSettings) } ); aoData.push( { "name": "iDisplayStart", "value": oSettings._iDisplayStart } ); aoData.push( { "name": "iDisplayLength", "value": oSettings.oFeatures.bPaginate !== false ? oSettings._iDisplayLength : -1 } ); for ( i=0 ; i<iColumns ; i++ ) { mDataProp = oSettings.aoColumns[i].mDataProp; aoData.push( { "name": "mDataProp_"+i, "value": typeof(mDataProp)=="function" ? 'function' : mDataProp } ); } /* Filtering */ if ( oSettings.oFeatures.bFilter !== false ) { aoData.push( { "name": "sSearch", "value": oSettings.oPreviousSearch.sSearch } ); aoData.push( { "name": "bRegex", "value": oSettings.oPreviousSearch.bRegex } ); for ( i=0 ; i<iColumns ; i++ ) { aoData.push( { "name": "sSearch_"+i, "value": oSettings.aoPreSearchCols[i].sSearch } ); aoData.push( { "name": "bRegex_"+i, "value": oSettings.aoPreSearchCols[i].bRegex } ); aoData.push( { "name": "bSearchable_"+i, "value": oSettings.aoColumns[i].bSearchable } ); } } /* Sorting */ if ( oSettings.oFeatures.bSort !== false ) { var iFixed = oSettings.aaSortingFixed !== null ? oSettings.aaSortingFixed.length : 0; var iUser = oSettings.aaSorting.length; aoData.push( { "name": "iSortingCols", "value": iFixed+iUser } ); for ( i=0 ; i<iFixed ; i++ ) { aoData.push( { "name": "iSortCol_"+i, "value": oSettings.aaSortingFixed[i][0] } ); aoData.push( { "name": "sSortDir_"+i, "value": oSettings.aaSortingFixed[i][1] } ); } for ( i=0 ; i<iUser ; i++ ) { aoData.push( { "name": "iSortCol_"+(i+iFixed), "value": oSettings.aaSorting[i][0] } ); aoData.push( { "name": "sSortDir_"+(i+iFixed), "value": oSettings.aaSorting[i][1] } ); } for ( i=0 ; i<iColumns ; i++ ) { aoData.push( { "name": "bSortable_"+i, "value": oSettings.aoColumns[i].bSortable } ); } } oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, aoData, function(json) { _fnAjaxUpdateDraw( oSettings, json ); }, oSettings ); return false; } else { return true; } } /* * Function: _fnAjaxUpdateDraw * Purpose: Data the data from the server (nuking the old) and redraw the table * Returns: - * Inputs: object:oSettings - dataTables settings object * object:json - json data return from the server. * The following must be defined: * iTotalRecords, iTotalDisplayRecords, aaData * The following may be defined: * sColumns */ function _fnAjaxUpdateDraw ( oSettings, json ) { if ( typeof json.sEcho != 'undefined' ) { /* Protect against old returns over-writing a new one. Possible when you get * very fast interaction, and later queires are completed much faster */ if ( json.sEcho*1 < oSettings.iDraw ) { return; } else { oSettings.iDraw = json.sEcho * 1; } } if ( !oSettings.oScroll.bInfinite || (oSettings.oScroll.bInfinite && (oSettings.bSorted || oSettings.bFiltered)) ) { _fnClearTable( oSettings ); } oSettings._iRecordsTotal = json.iTotalRecords; oSettings._iRecordsDisplay = json.iTotalDisplayRecords; /* Determine if reordering is required */ var sOrdering = _fnColumnOrdering(oSettings); var bReOrder = (typeof json.sColumns != 'undefined' && sOrdering !== "" && json.sColumns != sOrdering ); if ( bReOrder ) { var aiIndex = _fnReOrderIndex( oSettings, json.sColumns ); } var fnDataSrc = _fnGetObjectDataFn( oSettings.sAjaxDataProp ); var aData = fnDataSrc( json ); for ( var i=0, iLen=aData.length ; i<iLen ; i++ ) { if ( bReOrder ) { /* If we need to re-order, then create a new array with the correct order and add it */ var aDataSorted = []; for ( var j=0, jLen=oSettings.aoColumns.length ; j<jLen ; j++ ) { aDataSorted.push( aData[i][ aiIndex[j] ] ); } _fnAddData( oSettings, aDataSorted ); } else { /* No re-order required, sever got it "right" - just straight add */ _fnAddData( oSettings, aData[i] ); } } oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); oSettings.bAjaxDataGet = false; _fnDraw( oSettings ); oSettings.bAjaxDataGet = true; _fnProcessingDisplay( oSettings, false ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Options (features) HTML */ /* * Function: _fnAddOptionsHtml * Purpose: Add the options to the page HTML for the table * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnAddOptionsHtml ( oSettings ) { /* * Create a temporary, empty, div which we can later on replace with what we have generated * we do it this way to rendering the 'options' html offline - speed :-) */ var nHolding = document.createElement( 'div' ); oSettings.nTable.parentNode.insertBefore( nHolding, oSettings.nTable ); /* * All DataTables are wrapped in a div */ oSettings.nTableWrapper = document.createElement( 'div' ); oSettings.nTableWrapper.className = oSettings.oClasses.sWrapper; if ( oSettings.sTableId !== '' ) { oSettings.nTableWrapper.setAttribute( 'id', oSettings.sTableId+'_wrapper' ); } oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling; /* Track where we want to insert the option */ var nInsertNode = oSettings.nTableWrapper; /* Loop over the user set positioning and place the elements as needed */ var aDom = oSettings.sDom.split(''); var nTmp, iPushFeature, cOption, nNewNode, cNext, sAttr, j; for ( var i=0 ; i<aDom.length ; i++ ) { iPushFeature = 0; cOption = aDom[i]; if ( cOption == '<' ) { /* New container div */ nNewNode = document.createElement( 'div' ); /* Check to see if we should append an id and/or a class name to the container */ cNext = aDom[i+1]; if ( cNext == "'" || cNext == '"' ) { sAttr = ""; j = 2; while ( aDom[i+j] != cNext ) { sAttr += aDom[i+j]; j++; } /* Replace jQuery UI constants */ if ( sAttr == "H" ) { sAttr = "fg-toolbar ui-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix"; } else if ( sAttr == "F" ) { sAttr = "fg-toolbar ui-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"; } /* The attribute can be in the format of "#id.class", "#id" or "class" This logic * breaks the string into parts and applies them as needed */ if ( sAttr.indexOf('.') != -1 ) { var aSplit = sAttr.split('.'); nNewNode.setAttribute('id', aSplit[0].substr(1, aSplit[0].length-1) ); nNewNode.className = aSplit[1]; } else if ( sAttr.charAt(0) == "#" ) { nNewNode.setAttribute('id', sAttr.substr(1, sAttr.length-1) ); } else { nNewNode.className = sAttr; } i += j; /* Move along the position array */ } nInsertNode.appendChild( nNewNode ); nInsertNode = nNewNode; } else if ( cOption == '>' ) { /* End container div */ nInsertNode = nInsertNode.parentNode; } else if ( cOption == 'l' && oSettings.oFeatures.bPaginate && oSettings.oFeatures.bLengthChange ) { /* Length */ nTmp = _fnFeatureHtmlLength( oSettings ); iPushFeature = 1; } else if ( cOption == 'f' && oSettings.oFeatures.bFilter ) { /* Filter */ nTmp = _fnFeatureHtmlFilter( oSettings ); iPushFeature = 1; } else if ( cOption == 'r' && oSettings.oFeatures.bProcessing ) { /* pRocessing */ nTmp = _fnFeatureHtmlProcessing( oSettings ); iPushFeature = 1; } else if ( cOption == 't' ) { /* Table */ nTmp = _fnFeatureHtmlTable( oSettings ); iPushFeature = 1; } else if ( cOption == 'i' && oSettings.oFeatures.bInfo ) { /* Info */ nTmp = _fnFeatureHtmlInfo( oSettings ); iPushFeature = 1; } else if ( cOption == 'p' && oSettings.oFeatures.bPaginate ) { /* Pagination */ nTmp = _fnFeatureHtmlPaginate( oSettings ); iPushFeature = 1; } else if ( _oExt.aoFeatures.length !== 0 ) { /* Plug-in features */ var aoFeatures = _oExt.aoFeatures; for ( var k=0, kLen=aoFeatures.length ; k<kLen ; k++ ) { if ( cOption == aoFeatures[k].cFeature ) { nTmp = aoFeatures[k].fnInit( oSettings ); if ( nTmp ) { iPushFeature = 1; } break; } } } /* Add to the 2D features array */ if ( iPushFeature == 1 && nTmp !== null ) { if ( typeof oSettings.aanFeatures[cOption] != 'object' ) { oSettings.aanFeatures[cOption] = []; } oSettings.aanFeatures[cOption].push( nTmp ); nInsertNode.appendChild( nTmp ); } } /* Built our DOM structure - replace the holding div with what we want */ nHolding.parentNode.replaceChild( oSettings.nTableWrapper, nHolding ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: Filtering */ /* * Function: _fnFeatureHtmlTable * Purpose: Add any control elements for the table - specifically scrolling * Returns: node: - Node to add to the DOM * Inputs: object:oSettings - dataTables settings object */ function _fnFeatureHtmlTable ( oSettings ) { /* Chack if scrolling is enabled or not - if not then leave the DOM unaltered */ if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY === "" ) { return oSettings.nTable; } /* * The HTML structure that we want to generate in this function is: * div - nScroller * div - nScrollHead * div - nScrollHeadInner * table - nScrollHeadTable * thead - nThead * div - nScrollBody * table - oSettings.nTable * thead - nTheadSize * tbody - nTbody * div - nScrollFoot * div - nScrollFootInner * table - nScrollFootTable * tfoot - nTfoot */ var nScroller = document.createElement('div'), nScrollHead = document.createElement('div'), nScrollHeadInner = document.createElement('div'), nScrollBody = document.createElement('div'), nScrollFoot = document.createElement('div'), nScrollFootInner = document.createElement('div'), nScrollHeadTable = oSettings.nTable.cloneNode(false), nScrollFootTable = oSettings.nTable.cloneNode(false), nThead = oSettings.nTable.getElementsByTagName('thead')[0], nTfoot = oSettings.nTable.getElementsByTagName('tfoot').length === 0 ? null : oSettings.nTable.getElementsByTagName('tfoot')[0], oClasses = (typeof oInit.bJQueryUI != 'undefined' && oInit.bJQueryUI) ? _oExt.oJUIClasses : _oExt.oStdClasses; nScrollHead.appendChild( nScrollHeadInner ); nScrollFoot.appendChild( nScrollFootInner ); nScrollBody.appendChild( oSettings.nTable ); nScroller.appendChild( nScrollHead ); nScroller.appendChild( nScrollBody ); nScrollHeadInner.appendChild( nScrollHeadTable ); nScrollHeadTable.appendChild( nThead ); if ( nTfoot !== null ) { nScroller.appendChild( nScrollFoot ); nScrollFootInner.appendChild( nScrollFootTable ); nScrollFootTable.appendChild( nTfoot ); } nScroller.className = oClasses.sScrollWrapper; nScrollHead.className = oClasses.sScrollHead; nScrollHeadInner.className = oClasses.sScrollHeadInner; nScrollBody.className = oClasses.sScrollBody; nScrollFoot.className = oClasses.sScrollFoot; nScrollFootInner.className = oClasses.sScrollFootInner; if ( oSettings.oScroll.bAutoCss ) { nScrollHead.style.overflow = "hidden"; nScrollHead.style.position = "relative"; nScrollFoot.style.overflow = "hidden"; nScrollBody.style.overflow = "auto"; } nScrollHead.style.border = "0"; nScrollHead.style.width = "100%"; nScrollFoot.style.border = "0"; nScrollHeadInner.style.width = "150%"; /* will be overwritten */ /* Modify attributes to respect the clones */ nScrollHeadTable.removeAttribute('id'); nScrollHeadTable.style.marginLeft = "0"; oSettings.nTable.style.marginLeft = "0"; if ( nTfoot !== null ) { nScrollFootTable.removeAttribute('id'); nScrollFootTable.style.marginLeft = "0"; } /* Move any caption elements from the body to the header */ var nCaptions = $('>caption', oSettings.nTable); for ( var i=0, iLen=nCaptions.length ; i<iLen ; i++ ) { nScrollHeadTable.appendChild( nCaptions[i] ); } /* * Sizing */ /* When xscrolling add the width and a scroller to move the header with the body */ if ( oSettings.oScroll.sX !== "" ) { nScrollHead.style.width = _fnStringToCss( oSettings.oScroll.sX ); nScrollBody.style.width = _fnStringToCss( oSettings.oScroll.sX ); if ( nTfoot !== null ) { nScrollFoot.style.width = _fnStringToCss( oSettings.oScroll.sX ); } /* When the body is scrolled, then we also want to scroll the headers */ $(nScrollBody).scroll( function (e) { nScrollHead.scrollLeft = this.scrollLeft; if ( nTfoot !== null ) { nScrollFoot.scrollLeft = this.scrollLeft; } } ); } /* When yscrolling, add the height */ if ( oSettings.oScroll.sY !== "" ) { nScrollBody.style.height = _fnStringToCss( oSettings.oScroll.sY ); } /* Redraw - align columns across the tables */ oSettings.aoDrawCallback.push( { "fn": _fnScrollDraw, "sName": "scrolling" } ); /* Infinite scrolling event handlers */ if ( oSettings.oScroll.bInfinite ) { $(nScrollBody).scroll( function() { /* Use a blocker to stop scrolling from loading more data while other data is still loading */ if ( !oSettings.bDrawing ) { /* Check if we should load the next data set */ if ( $(this).scrollTop() + $(this).height() > $(oSettings.nTable).height() - oSettings.oScroll.iLoadGap ) { /* Only do the redraw if we have to - we might be at the end of the data */ if ( oSettings.fnDisplayEnd() < oSettings.fnRecordsDisplay() ) { _fnPageChange( oSettings, 'next' ); _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } } } } ); } oSettings.nScrollHead = nScrollHead; oSettings.nScrollFoot = nScrollFoot; return nScroller; } /* * Function: _fnScrollDraw * Purpose: Update the various tables for resizing * Returns: node: - Node to add to the DOM * Inputs: object:o - dataTables settings object * Notes: It's a bit of a pig this function, but basically the idea to: * 1. Re-create the table inside the scrolling div * 2. Take live measurements from the DOM * 3. Apply the measurements * 4. Clean up */ function _fnScrollDraw ( o ) { var nScrollHeadInner = o.nScrollHead.getElementsByTagName('div')[0], nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0], nScrollBody = o.nTable.parentNode, i, iLen, j, jLen, anHeadToSize, anHeadSizers, anFootSizers, anFootToSize, oStyle, iVis, iWidth, aApplied=[], iSanityWidth; /* * 1. Re-create the table inside the scrolling div */ /* Remove the old minimised thead and tfoot elements in the inner table */ var nTheadSize = o.nTable.getElementsByTagName('thead'); if ( nTheadSize.length > 0 ) { o.nTable.removeChild( nTheadSize[0] ); } if ( o.nTFoot !== null ) { /* Remove the old minimised footer element in the cloned header */ var nTfootSize = o.nTable.getElementsByTagName('tfoot'); if ( nTfootSize.length > 0 ) { o.nTable.removeChild( nTfootSize[0] ); } } /* Clone the current header and footer elements and then place it into the inner table */ nTheadSize = o.nTHead.cloneNode(true); o.nTable.insertBefore( nTheadSize, o.nTable.childNodes[0] ); if ( o.nTFoot !== null ) { nTfootSize = o.nTFoot.cloneNode(true); o.nTable.insertBefore( nTfootSize, o.nTable.childNodes[1] ); } /* * 2. Take live measurements from the DOM - do not alter the DOM itself! */ /* Remove old sizing and apply the calculated column widths * Get the unique column headers in the newly created (cloned) header. We want to apply the * calclated sizes to this header */ if ( o.oScroll.sX === "" ) { nScrollBody.style.width = '100%'; nScrollHeadInner.parentNode.style.width = '100%'; } var nThs = _fnGetUniqueThs( o, nTheadSize ); for ( i=0, iLen=nThs.length ; i<iLen ; i++ ) { iVis = _fnVisibleToColumnIndex( o, i ); nThs[i].style.width = o.aoColumns[iVis].sWidth; } if ( o.nTFoot !== null ) { _fnApplyToChildren( function(n) { n.style.width = ""; }, nTfootSize.getElementsByTagName('tr') ); } /* Size the table as a whole */ iSanityWidth = $(o.nTable).outerWidth(); if ( o.oScroll.sX === "" ) { /* No x scrolling */ o.nTable.style.width = "100%"; /* I know this is rubbish - but IE7 will make the width of the table when 100% include * the scrollbar - which is shouldn't. This needs feature detection in future - to do */ if ( $.browser.msie && $.browser.version <= 7 ) { o.nTable.style.width = _fnStringToCss( $(o.nTable).outerWidth()-o.oScroll.iBarWidth ); } } else { if ( o.oScroll.sXInner !== "" ) { /* x scroll inner has been given - use it */ o.nTable.style.width = _fnStringToCss(o.oScroll.sXInner); } else if ( iSanityWidth == $(nScrollBody).width() && $(nScrollBody).height() < $(o.nTable).height() ) { /* There is y-scrolling - try to take account of the y scroll bar */ o.nTable.style.width = _fnStringToCss( iSanityWidth-o.oScroll.iBarWidth ); if ( $(o.nTable).outerWidth() > iSanityWidth-o.oScroll.iBarWidth ) { /* Not possible to take account of it */ o.nTable.style.width = _fnStringToCss( iSanityWidth ); } } else { /* All else fails */ o.nTable.style.width = _fnStringToCss( iSanityWidth ); } } /* Recalculate the sanity width - now that we've applied the required width, before it was * a temporary variable. This is required because the column width calculation is done * before this table DOM is created. */ iSanityWidth = $(o.nTable).outerWidth(); /* If x-scrolling is disabled, then the viewport cannot be less than the sanity width */ if ( o.oScroll.sX === "" ) { nScrollBody.style.width = _fnStringToCss( iSanityWidth+o.oScroll.iBarWidth ); nScrollHeadInner.parentNode.style.width = _fnStringToCss( iSanityWidth+o.oScroll.iBarWidth ); } /* We want the hidden header to have zero height, so remove padding and borders. Then * set the width based on the real headers */ anHeadToSize = o.nTHead.getElementsByTagName('tr'); anHeadSizers = nTheadSize.getElementsByTagName('tr'); _fnApplyToChildren( function(nSizer, nToSize) { oStyle = nSizer.style; oStyle.paddingTop = "0"; oStyle.paddingBottom = "0"; oStyle.borderTopWidth = "0"; oStyle.borderBottomWidth = "0"; oStyle.height = 0; iWidth = $(nSizer).width(); nToSize.style.width = _fnStringToCss( iWidth ); aApplied.push( iWidth ); }, anHeadSizers, anHeadToSize ); $(anHeadSizers).height(0); if ( o.nTFoot !== null ) { /* Clone the current footer and then place it into the body table as a "hidden header" */ anFootSizers = nTfootSize.getElementsByTagName('tr'); anFootToSize = o.nTFoot.getElementsByTagName('tr'); _fnApplyToChildren( function(nSizer, nToSize) { oStyle = nSizer.style; oStyle.paddingTop = "0"; oStyle.paddingBottom = "0"; oStyle.borderTopWidth = "0"; oStyle.borderBottomWidth = "0"; oStyle.height = 0; iWidth = $(nSizer).width(); nToSize.style.width = _fnStringToCss( iWidth ); aApplied.push( iWidth ); }, anFootSizers, anFootToSize ); $(anFootSizers).height(0); } /* * 3. Apply the measurements */ /* "Hide" the header and footer that we used for the sizing. We want to also fix their width * to what they currently are */ _fnApplyToChildren( function(nSizer) { nSizer.innerHTML = ""; nSizer.style.width = _fnStringToCss( aApplied.shift() ); }, anHeadSizers ); if ( o.nTFoot !== null ) { _fnApplyToChildren( function(nSizer) { nSizer.innerHTML = ""; nSizer.style.width = _fnStringToCss( aApplied.shift() ); }, anFootSizers ); } /* Sanity check that the table is of a sensible width. If not then we are going to get * misalignment */ if ( $(o.nTable).outerWidth() < iSanityWidth ) { if ( o.oScroll.sX === "" ) { _fnLog( o, 1, "The table cannot fit into the current element which will cause column"+ " misalignment. It is suggested that you enable x-scrolling or increase the width"+ " the table has in which to be drawn" ); } else if ( o.oScroll.sXInner !== "" ) { _fnLog( o, 1, "The table cannot fit into the current element which will cause column"+ " misalignment. It is suggested that you increase the sScrollXInner property to"+ " allow it to draw in a larger area, or simply remove that parameter to allow"+ " automatic calculation" ); } } /* * 4. Clean up */ if ( o.oScroll.sY === "" ) { /* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting * the scrollbar height from the visible display, rather than adding it on. We need to * set the height in order to sort this. Don't want to do it in any other browsers. */ if ( $.browser.msie && $.browser.version <= 7 ) { nScrollBody.style.height = _fnStringToCss( o.nTable.offsetHeight+o.oScroll.iBarWidth ); } } if ( o.oScroll.sY !== "" && o.oScroll.bCollapse ) { nScrollBody.style.height = _fnStringToCss( o.oScroll.sY ); var iExtra = (o.oScroll.sX !== "" && o.nTable.offsetWidth > nScrollBody.offsetWidth) ? o.oScroll.iBarWidth : 0; if ( o.nTable.offsetHeight < nScrollBody.offsetHeight ) { nScrollBody.style.height = _fnStringToCss( $(o.nTable).height()+iExtra ); } } /* Finally set the width's of the header and footer tables */ var iOuterWidth = $(o.nTable).outerWidth(); nScrollHeadTable.style.width = _fnStringToCss( iOuterWidth ); nScrollHeadInner.style.width = _fnStringToCss( iOuterWidth+o.oScroll.iBarWidth ); if ( o.nTFoot !== null ) { var nScrollFootInner = o.nScrollFoot.getElementsByTagName('div')[0], nScrollFootTable = nScrollFootInner.getElementsByTagName('table')[0]; nScrollFootInner.style.width = _fnStringToCss( o.nTable.offsetWidth+o.oScroll.iBarWidth ); nScrollFootTable.style.width = _fnStringToCss( o.nTable.offsetWidth ); } /* If sorting or filtering has occured, jump the scrolling back to the top */ if ( o.bSorted || o.bFiltered ) { nScrollBody.scrollTop = 0; } } /* * Function: _fnAjustColumnSizing * Purpose: Ajust the table column widths for new data * Returns: - * Inputs: object:oSettings - dataTables settings object * Notes: You would probably want to do a redraw after calling this function! */ function _fnAjustColumnSizing ( oSettings ) { /* Not interested in doing column width calculation if autowidth is disabled */ if ( oSettings.oFeatures.bAutoWidth === false ) { return false; } _fnCalculateColumnWidths( oSettings ); for ( var i=0 , iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { oSettings.aoColumns[i].nTh.style.width = oSettings.aoColumns[i].sWidth; } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: Filtering */ /* * Function: _fnFeatureHtmlFilter * Purpose: Generate the node required for filtering text * Returns: node * Inputs: object:oSettings - dataTables settings object */ function _fnFeatureHtmlFilter ( oSettings ) { var sSearchStr = oSettings.oLanguage.sSearch; sSearchStr = (sSearchStr.indexOf('_INPUT_') !== -1) ? sSearchStr.replace('_INPUT_', '<input type="text" />') : sSearchStr==="" ? '<input type="text" />' : sSearchStr+' <input type="text" />'; var nFilter = document.createElement( 'div' ); nFilter.className = oSettings.oClasses.sFilter; nFilter.innerHTML = '<label>'+sSearchStr+'</label>'; if ( oSettings.sTableId !== '' && typeof oSettings.aanFeatures.f == "undefined" ) { nFilter.setAttribute( 'id', oSettings.sTableId+'_filter' ); } var jqFilter = $("input", nFilter); jqFilter.val( oSettings.oPreviousSearch.sSearch.replace('"','&quot;') ); jqFilter.bind( 'keyup.DT', function(e) { /* Update all other filter input elements for the new display */ var n = oSettings.aanFeatures.f; for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { if ( n[i] != this.parentNode ) { $('input', n[i]).val( this.value ); } } /* Now do the filter */ if ( this.value != oSettings.oPreviousSearch.sSearch ) { _fnFilterComplete( oSettings, { "sSearch": this.value, "bRegex": oSettings.oPreviousSearch.bRegex, "bSmart": oSettings.oPreviousSearch.bSmart } ); } } ); jqFilter.bind( 'keypress.DT', function(e) { /* Prevent default */ if ( e.keyCode == 13 ) { return false; } } ); return nFilter; } /* * Function: _fnFilterComplete * Purpose: Filter the table using both the global filter and column based filtering * Returns: - * Inputs: object:oSettings - dataTables settings object * object:oSearch: search information * int:iForce - optional - force a research of the master array (1) or not (undefined or 0) */ function _fnFilterComplete ( oSettings, oInput, iForce ) { /* Filter on everything */ _fnFilter( oSettings, oInput.sSearch, iForce, oInput.bRegex, oInput.bSmart ); /* Now do the individual column filter */ for ( var i=0 ; i<oSettings.aoPreSearchCols.length ; i++ ) { _fnFilterColumn( oSettings, oSettings.aoPreSearchCols[i].sSearch, i, oSettings.aoPreSearchCols[i].bRegex, oSettings.aoPreSearchCols[i].bSmart ); } /* Custom filtering */ if ( _oExt.afnFiltering.length !== 0 ) { _fnFilterCustom( oSettings ); } /* Tell the draw function we have been filtering */ oSettings.bFiltered = true; /* Redraw the table */ oSettings._iDisplayStart = 0; _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); /* Rebuild search array 'offline' */ _fnBuildSearchArray( oSettings, 0 ); } /* * Function: _fnFilterCustom * Purpose: Apply custom filtering functions * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnFilterCustom( oSettings ) { var afnFilters = _oExt.afnFiltering; for ( var i=0, iLen=afnFilters.length ; i<iLen ; i++ ) { var iCorrector = 0; for ( var j=0, jLen=oSettings.aiDisplay.length ; j<jLen ; j++ ) { var iDisIndex = oSettings.aiDisplay[j-iCorrector]; /* Check if we should use this row based on the filtering function */ if ( !afnFilters[i]( oSettings, _fnGetRowData( oSettings, iDisIndex, 'filter' ), iDisIndex ) ) { oSettings.aiDisplay.splice( j-iCorrector, 1 ); iCorrector++; } } } } /* * Function: _fnFilterColumn * Purpose: Filter the table on a per-column basis * Returns: - * Inputs: object:oSettings - dataTables settings object * string:sInput - string to filter on * int:iColumn - column to filter * bool:bRegex - treat search string as a regular expression or not * bool:bSmart - use smart filtering or not */ function _fnFilterColumn ( oSettings, sInput, iColumn, bRegex, bSmart ) { if ( sInput === "" ) { return; } var iIndexCorrector = 0; var rpSearch = _fnFilterCreateSearch( sInput, bRegex, bSmart ); for ( var i=oSettings.aiDisplay.length-1 ; i>=0 ; i-- ) { var sData = _fnDataToSearch( _fnGetCellData( oSettings, oSettings.aiDisplay[i], iColumn, 'filter' ), oSettings.aoColumns[iColumn].sType ); if ( ! rpSearch.test( sData ) ) { oSettings.aiDisplay.splice( i, 1 ); iIndexCorrector++; } } } /* * Function: _fnFilter * Purpose: Filter the data table based on user input and draw the table * Returns: - * Inputs: object:oSettings - dataTables settings object * string:sInput - string to filter on * int:iForce - optional - force a research of the master array (1) or not (undefined or 0) * bool:bRegex - treat as a regular expression or not * bool:bSmart - perform smart filtering or not */ function _fnFilter( oSettings, sInput, iForce, bRegex, bSmart ) { var i; var rpSearch = _fnFilterCreateSearch( sInput, bRegex, bSmart ); /* Check if we are forcing or not - optional parameter */ if ( typeof iForce == 'undefined' || iForce === null ) { iForce = 0; } /* Need to take account of custom filtering functions - always filter */ if ( _oExt.afnFiltering.length !== 0 ) { iForce = 1; } /* * If the input is blank - we want the full data set */ if ( sInput.length <= 0 ) { oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length); oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); } else { /* * We are starting a new search or the new search string is smaller * then the old one (i.e. delete). Search from the master array */ if ( oSettings.aiDisplay.length == oSettings.aiDisplayMaster.length || oSettings.oPreviousSearch.sSearch.length > sInput.length || iForce == 1 || sInput.indexOf(oSettings.oPreviousSearch.sSearch) !== 0 ) { /* Nuke the old display array - we are going to rebuild it */ oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length); /* Force a rebuild of the search array */ _fnBuildSearchArray( oSettings, 1 ); /* Search through all records to populate the search array * The the oSettings.aiDisplayMaster and asDataSearch arrays have 1 to 1 * mapping */ for ( i=0 ; i<oSettings.aiDisplayMaster.length ; i++ ) { if ( rpSearch.test(oSettings.asDataSearch[i]) ) { oSettings.aiDisplay.push( oSettings.aiDisplayMaster[i] ); } } } else { /* Using old search array - refine it - do it this way for speed * Don't have to search the whole master array again */ var iIndexCorrector = 0; /* Search the current results */ for ( i=0 ; i<oSettings.asDataSearch.length ; i++ ) { if ( ! rpSearch.test(oSettings.asDataSearch[i]) ) { oSettings.aiDisplay.splice( i-iIndexCorrector, 1 ); iIndexCorrector++; } } } } oSettings.oPreviousSearch.sSearch = sInput; oSettings.oPreviousSearch.bRegex = bRegex; oSettings.oPreviousSearch.bSmart = bSmart; } /* * Function: _fnBuildSearchArray * Purpose: Create an array which can be quickly search through * Returns: - * Inputs: object:oSettings - dataTables settings object * int:iMaster - use the master data array - optional */ function _fnBuildSearchArray ( oSettings, iMaster ) { /* Clear out the old data */ oSettings.asDataSearch.splice( 0, oSettings.asDataSearch.length ); var aArray = (typeof iMaster != 'undefined' && iMaster == 1) ? oSettings.aiDisplayMaster : oSettings.aiDisplay; for ( var i=0, iLen=aArray.length ; i<iLen ; i++ ) { oSettings.asDataSearch[i] = _fnBuildSearchRow( oSettings, _fnGetRowData( oSettings, aArray[i], 'filter' ) ); } } /* * Function: _fnBuildSearchRow * Purpose: Create a searchable string from a single data row * Returns: - * Inputs: object:oSettings - dataTables settings object * array:aData - Row data array to use for the data to search */ function _fnBuildSearchRow( oSettings, aData ) { var sSearch = ''; if ( typeof oSettings.__nTmpFilter == 'undefined' ) { oSettings.__nTmpFilter = document.createElement('div'); } var nTmp = oSettings.__nTmpFilter; for ( var j=0, jLen=oSettings.aoColumns.length ; j<jLen ; j++ ) { if ( oSettings.aoColumns[j].bSearchable ) { var sData = aData[j]; sSearch += _fnDataToSearch( sData, oSettings.aoColumns[j].sType )+' '; } } /* If it looks like there is an HTML entity in the string, attempt to decode it */ if ( sSearch.indexOf('&') !== -1 ) { nTmp.innerHTML = sSearch; sSearch = nTmp.textContent ? nTmp.textContent : nTmp.innerText; /* IE and Opera appear to put an newline where there is a <br> tag - remove it */ sSearch = sSearch.replace(/\n/g," ").replace(/\r/g,""); } return sSearch; } /* * Function: _fnFilterCreateSearch * Purpose: Build a regular expression object suitable for searching a table * Returns: RegExp: - constructed object * Inputs: string:sSearch - string to search for * bool:bRegex - treat as a regular expression or not * bool:bSmart - perform smart filtering or not */ function _fnFilterCreateSearch( sSearch, bRegex, bSmart ) { var asSearch, sRegExpString; if ( bSmart ) { /* Generate the regular expression to use. Something along the lines of: * ^(?=.*?\bone\b)(?=.*?\btwo\b)(?=.*?\bthree\b).*$ */ asSearch = bRegex ? sSearch.split( ' ' ) : _fnEscapeRegex( sSearch ).split( ' ' ); sRegExpString = '^(?=.*?'+asSearch.join( ')(?=.*?' )+').*$'; return new RegExp( sRegExpString, "i" ); } else { sSearch = bRegex ? sSearch : _fnEscapeRegex( sSearch ); return new RegExp( sSearch, "i" ); } } /* * Function: _fnDataToSearch * Purpose: Convert raw data into something that the user can search on * Returns: string: - search string * Inputs: string:sData - data to be modified * string:sType - data type */ function _fnDataToSearch ( sData, sType ) { if ( typeof _oExt.ofnSearch[sType] == "function" ) { return _oExt.ofnSearch[sType]( sData ); } else if ( sType == "html" ) { return sData.replace(/\n/g," ").replace( /<.*?>/g, "" ); } else if ( typeof sData == "string" ) { return sData.replace(/\n/g," "); } else if ( sData === null ) { return ''; } return sData; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: Sorting */ /* * Function: _fnSort * Purpose: Change the order of the table * Returns: - * Inputs: object:oSettings - dataTables settings object * bool:bApplyClasses - optional - should we apply classes or not * Notes: We always sort the master array and then apply a filter again * if it is needed. This probably isn't optimal - but atm I can't think * of any other way which is (each has disadvantages). we want to sort aiDisplayMaster - * but according to aoData[]._aData */ function _fnSort ( oSettings, bApplyClasses ) { var iDataSort, iDataType, i, iLen, j, jLen, aaSort = [], aiOrig = [], oSort = _oExt.oSort, aoData = oSettings.aoData, aoColumns = oSettings.aoColumns; /* No sorting required if server-side or no sorting array */ if ( !oSettings.oFeatures.bServerSide && (oSettings.aaSorting.length !== 0 || oSettings.aaSortingFixed !== null) ) { if ( oSettings.aaSortingFixed !== null ) { aaSort = oSettings.aaSortingFixed.concat( oSettings.aaSorting ); } else { aaSort = oSettings.aaSorting.slice(); } /* If there is a sorting data type, and a fuction belonging to it, then we need to * get the data from the developer's function and apply it for this column */ for ( i=0 ; i<aaSort.length ; i++ ) { var iColumn = aaSort[i][0]; var iVisColumn = _fnColumnIndexToVisible( oSettings, iColumn ); var sDataType = oSettings.aoColumns[ iColumn ].sSortDataType; if ( typeof _oExt.afnSortData[sDataType] != 'undefined' ) { var aData = _oExt.afnSortData[sDataType]( oSettings, iColumn, iVisColumn ); for ( j=0, jLen=aoData.length ; j<jLen ; j++ ) { _fnSetCellData( oSettings, j, iColumn, aData[j] ); } } } /* Create a value - key array of the current row positions such that we can use their * current position during the sort, if values match, in order to perform stable sorting */ for ( i=0, iLen=oSettings.aiDisplayMaster.length ; i<iLen ; i++ ) { aiOrig[ oSettings.aiDisplayMaster[i] ] = i; } /* Do the sort - here we want multi-column sorting based on a given data source (column) * and sorting function (from oSort) in a certain direction. It's reasonably complex to * follow on it's own, but this is what we want (example two column sorting): * fnLocalSorting = function(a,b){ * var iTest; * iTest = oSort['string-asc']('data11', 'data12'); * if (iTest !== 0) * return iTest; * iTest = oSort['numeric-desc']('data21', 'data22'); * if (iTest !== 0) * return iTest; * return oSort['numeric-asc']( aiOrig[a], aiOrig[b] ); * } * Basically we have a test for each sorting column, if the data in that column is equal, * test the next column. If all columns match, then we use a numeric sort on the row * positions in the original data array to provide a stable sort. */ var iSortLen = aaSort.length; oSettings.aiDisplayMaster.sort( function ( a, b ) { var iTest, iDataSort, sDataType; for ( i=0 ; i<iSortLen ; i++ ) { iDataSort = aoColumns[ aaSort[i][0] ].iDataSort; sDataType = aoColumns[ iDataSort ].sType; iTest = oSort[ (sDataType?sDataType:'string')+"-"+aaSort[i][1] ]( _fnGetCellData( oSettings, a, iDataSort, 'sort' ), _fnGetCellData( oSettings, b, iDataSort, 'sort' ) ); if ( iTest !== 0 ) { return iTest; } } return oSort['numeric-asc']( aiOrig[a], aiOrig[b] ); } ); } /* Alter the sorting classes to take account of the changes */ if ( (typeof bApplyClasses == 'undefined' || bApplyClasses) && !oSettings.oFeatures.bDeferRender ) { _fnSortingClasses( oSettings ); } /* Tell the draw function that we have sorted the data */ oSettings.bSorted = true; /* Copy the master data into the draw array and re-draw */ if ( oSettings.oFeatures.bFilter ) { /* _fnFilter() will redraw the table for us */ _fnFilterComplete( oSettings, oSettings.oPreviousSearch, 1 ); } else { oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); oSettings._iDisplayStart = 0; /* reset display back to page 0 */ _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } } /* * Function: _fnSortAttachListener * Purpose: Attach a sort handler (click) to a node * Returns: - * Inputs: object:oSettings - dataTables settings object * node:nNode - node to attach the handler to * int:iDataIndex - column sorting index * function:fnCallback - callback function - optional */ function _fnSortAttachListener ( oSettings, nNode, iDataIndex, fnCallback ) { $(nNode).bind( 'click.DT', function (e) { /* If the column is not sortable - don't to anything */ if ( oSettings.aoColumns[iDataIndex].bSortable === false ) { return; } /* * This is a little bit odd I admit... I declare a temporary function inside the scope of * _fnBuildHead and the click handler in order that the code presented here can be used * twice - once for when bProcessing is enabled, and another time for when it is * disabled, as we need to perform slightly different actions. * Basically the issue here is that the Javascript engine in modern browsers don't * appear to allow the rendering engine to update the display while it is still excuting * it's thread (well - it does but only after long intervals). This means that the * 'processing' display doesn't appear for a table sort. To break the js thread up a bit * I force an execution break by using setTimeout - but this breaks the expected * thread continuation for the end-developer's point of view (their code would execute * too early), so we on;y do it when we absolutely have to. */ var fnInnerSorting = function () { var iColumn, iNextSort; /* If the shift key is pressed then we are multipe column sorting */ if ( e.shiftKey ) { /* Are we already doing some kind of sort on this column? */ var bFound = false; for ( var i=0 ; i<oSettings.aaSorting.length ; i++ ) { if ( oSettings.aaSorting[i][0] == iDataIndex ) { bFound = true; iColumn = oSettings.aaSorting[i][0]; iNextSort = oSettings.aaSorting[i][2]+1; if ( typeof oSettings.aoColumns[iColumn].asSorting[iNextSort] == 'undefined' ) { /* Reached the end of the sorting options, remove from multi-col sort */ oSettings.aaSorting.splice( i, 1 ); } else { /* Move onto next sorting direction */ oSettings.aaSorting[i][1] = oSettings.aoColumns[iColumn].asSorting[iNextSort]; oSettings.aaSorting[i][2] = iNextSort; } break; } } /* No sort yet - add it in */ if ( bFound === false ) { oSettings.aaSorting.push( [ iDataIndex, oSettings.aoColumns[iDataIndex].asSorting[0], 0 ] ); } } else { /* If no shift key then single column sort */ if ( oSettings.aaSorting.length == 1 && oSettings.aaSorting[0][0] == iDataIndex ) { iColumn = oSettings.aaSorting[0][0]; iNextSort = oSettings.aaSorting[0][2]+1; if ( typeof oSettings.aoColumns[iColumn].asSorting[iNextSort] == 'undefined' ) { iNextSort = 0; } oSettings.aaSorting[0][1] = oSettings.aoColumns[iColumn].asSorting[iNextSort]; oSettings.aaSorting[0][2] = iNextSort; } else { oSettings.aaSorting.splice( 0, oSettings.aaSorting.length ); oSettings.aaSorting.push( [ iDataIndex, oSettings.aoColumns[iDataIndex].asSorting[0], 0 ] ); } } /* Run the sort */ _fnSort( oSettings ); }; /* /fnInnerSorting */ if ( !oSettings.oFeatures.bProcessing ) { fnInnerSorting(); } else { _fnProcessingDisplay( oSettings, true ); setTimeout( function() { fnInnerSorting(); if ( !oSettings.oFeatures.bServerSide ) { _fnProcessingDisplay( oSettings, false ); } }, 0 ); } /* Call the user specified callback function - used for async user interaction */ if ( typeof fnCallback == 'function' ) { fnCallback( oSettings ); } } ); } /* * Function: _fnSortingClasses * Purpose: Set the sortting classes on the header * Returns: - * Inputs: object:oSettings - dataTables settings object * Notes: It is safe to call this function when bSort and bSortClasses are false */ function _fnSortingClasses( oSettings ) { var i, iLen, j, jLen, iFound; var aaSort, sClass; var iColumns = oSettings.aoColumns.length; var oClasses = oSettings.oClasses; for ( i=0 ; i<iColumns ; i++ ) { if ( oSettings.aoColumns[i].bSortable ) { $(oSettings.aoColumns[i].nTh).removeClass( oClasses.sSortAsc +" "+ oClasses.sSortDesc + " "+ oSettings.aoColumns[i].sSortingClass ); } } if ( oSettings.aaSortingFixed !== null ) { aaSort = oSettings.aaSortingFixed.concat( oSettings.aaSorting ); } else { aaSort = oSettings.aaSorting.slice(); } /* Apply the required classes to the header */ for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bSortable ) { sClass = oSettings.aoColumns[i].sSortingClass; iFound = -1; for ( j=0 ; j<aaSort.length ; j++ ) { if ( aaSort[j][0] == i ) { sClass = ( aaSort[j][1] == "asc" ) ? oClasses.sSortAsc : oClasses.sSortDesc; iFound = j; break; } } $(oSettings.aoColumns[i].nTh).addClass( sClass ); if ( oSettings.bJUI ) { /* jQuery UI uses extra markup */ var jqSpan = $("span", oSettings.aoColumns[i].nTh); jqSpan.removeClass(oClasses.sSortJUIAsc +" "+ oClasses.sSortJUIDesc +" "+ oClasses.sSortJUI +" "+ oClasses.sSortJUIAscAllowed +" "+ oClasses.sSortJUIDescAllowed ); var sSpanClass; if ( iFound == -1 ) { sSpanClass = oSettings.aoColumns[i].sSortingClassJUI; } else if ( aaSort[iFound][1] == "asc" ) { sSpanClass = oClasses.sSortJUIAsc; } else { sSpanClass = oClasses.sSortJUIDesc; } jqSpan.addClass( sSpanClass ); } } else { /* No sorting on this column, so add the base class. This will have been assigned by * _fnAddColumn */ $(oSettings.aoColumns[i].nTh).addClass( oSettings.aoColumns[i].sSortingClass ); } } /* * Apply the required classes to the table body * Note that this is given as a feature switch since it can significantly slow down a sort * on large data sets (adding and removing of classes is always slow at the best of times..) * Further to this, note that this code is admitadly fairly ugly. It could be made a lot * simpiler using jQuery selectors and add/removeClass, but that is significantly slower * (on the order of 5 times slower) - hence the direct DOM manipulation here. * Note that for defered drawing we do use jQuery - the reason being that taking the first * row found to see if the whole column needs processed can miss classes since the first * column might be new. */ sClass = oClasses.sSortColumn; if ( oSettings.oFeatures.bSort && oSettings.oFeatures.bSortClasses ) { var nTds = _fnGetTdNodes( oSettings ); /* Remove the old classes */ if ( oSettings.oFeatures.bDeferRender ) { $(nTds).removeClass(sClass+'1 '+sClass+'2 '+sClass+'3'); } else if ( nTds.length >= iColumns ) { for ( i=0 ; i<iColumns ; i++ ) { if ( nTds[i].className.indexOf(sClass+"1") != -1 ) { for ( j=0, jLen=(nTds.length/iColumns) ; j<jLen ; j++ ) { nTds[(iColumns*j)+i].className = $.trim( nTds[(iColumns*j)+i].className.replace( sClass+"1", "" ) ); } } else if ( nTds[i].className.indexOf(sClass+"2") != -1 ) { for ( j=0, jLen=(nTds.length/iColumns) ; j<jLen ; j++ ) { nTds[(iColumns*j)+i].className = $.trim( nTds[(iColumns*j)+i].className.replace( sClass+"2", "" ) ); } } else if ( nTds[i].className.indexOf(sClass+"3") != -1 ) { for ( j=0, jLen=(nTds.length/iColumns) ; j<jLen ; j++ ) { nTds[(iColumns*j)+i].className = $.trim( nTds[(iColumns*j)+i].className.replace( " "+sClass+"3", "" ) ); } } } } /* Add the new classes to the table */ var iClass = 1, iTargetCol; for ( i=0 ; i<aaSort.length ; i++ ) { iTargetCol = parseInt( aaSort[i][0], 10 ); for ( j=0, jLen=(nTds.length/iColumns) ; j<jLen ; j++ ) { nTds[(iColumns*j)+iTargetCol].className += " "+sClass+iClass; } if ( iClass < 3 ) { iClass++; } } } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: Pagination. Note that most of the paging logic is done in * _oExt.oPagination */ /* * Function: _fnFeatureHtmlPaginate * Purpose: Generate the node required for default pagination * Returns: node * Inputs: object:oSettings - dataTables settings object */ function _fnFeatureHtmlPaginate ( oSettings ) { if ( oSettings.oScroll.bInfinite ) { return null; } var nPaginate = document.createElement( 'div' ); nPaginate.className = oSettings.oClasses.sPaging+oSettings.sPaginationType; _oExt.oPagination[ oSettings.sPaginationType ].fnInit( oSettings, nPaginate, function( oSettings ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } ); /* Add a draw callback for the pagination on first instance, to update the paging display */ if ( typeof oSettings.aanFeatures.p == "undefined" ) { oSettings.aoDrawCallback.push( { "fn": function( oSettings ) { _oExt.oPagination[ oSettings.sPaginationType ].fnUpdate( oSettings, function( oSettings ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } ); }, "sName": "pagination" } ); } return nPaginate; } /* * Function: _fnPageChange * Purpose: Alter the display settings to change the page * Returns: bool:true - page has changed, false - no change (no effect) eg 'first' on page 1 * Inputs: object:oSettings - dataTables settings object * string:sAction - paging action to take: "first", "previous", "next" or "last" */ function _fnPageChange ( oSettings, sAction ) { var iOldStart = oSettings._iDisplayStart; if ( sAction == "first" ) { oSettings._iDisplayStart = 0; } else if ( sAction == "previous" ) { oSettings._iDisplayStart = oSettings._iDisplayLength>=0 ? oSettings._iDisplayStart - oSettings._iDisplayLength : 0; /* Correct for underrun */ if ( oSettings._iDisplayStart < 0 ) { oSettings._iDisplayStart = 0; } } else if ( sAction == "next" ) { if ( oSettings._iDisplayLength >= 0 ) { /* Make sure we are not over running the display array */ if ( oSettings._iDisplayStart + oSettings._iDisplayLength < oSettings.fnRecordsDisplay() ) { oSettings._iDisplayStart += oSettings._iDisplayLength; } } else { oSettings._iDisplayStart = 0; } } else if ( sAction == "last" ) { if ( oSettings._iDisplayLength >= 0 ) { var iPages = parseInt( (oSettings.fnRecordsDisplay()-1) / oSettings._iDisplayLength, 10 ) + 1; oSettings._iDisplayStart = (iPages-1) * oSettings._iDisplayLength; } else { oSettings._iDisplayStart = 0; } } else { _fnLog( oSettings, 0, "Unknown paging action: "+sAction ); } return iOldStart != oSettings._iDisplayStart; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: HTML info */ /* * Function: _fnFeatureHtmlInfo * Purpose: Generate the node required for the info display * Returns: node * Inputs: object:oSettings - dataTables settings object */ function _fnFeatureHtmlInfo ( oSettings ) { var nInfo = document.createElement( 'div' ); nInfo.className = oSettings.oClasses.sInfo; /* Actions that are to be taken once only for this feature */ if ( typeof oSettings.aanFeatures.i == "undefined" ) { /* Add draw callback */ oSettings.aoDrawCallback.push( { "fn": _fnUpdateInfo, "sName": "information" } ); /* Add id */ if ( oSettings.sTableId !== '' ) { nInfo.setAttribute( 'id', oSettings.sTableId+'_info' ); } } return nInfo; } /* * Function: _fnUpdateInfo * Purpose: Update the information elements in the display * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnUpdateInfo ( oSettings ) { /* Show information about the table */ if ( !oSettings.oFeatures.bInfo || oSettings.aanFeatures.i.length === 0 ) { return; } var iStart = oSettings._iDisplayStart+1, iEnd = oSettings.fnDisplayEnd(), iMax = oSettings.fnRecordsTotal(), iTotal = oSettings.fnRecordsDisplay(), sStart = oSettings.fnFormatNumber( iStart ), sEnd = oSettings.fnFormatNumber( iEnd ), sMax = oSettings.fnFormatNumber( iMax ), sTotal = oSettings.fnFormatNumber( iTotal ), sOut; /* When infinite scrolling, we are always starting at 1. _iDisplayStart is used only * internally */ if ( oSettings.oScroll.bInfinite ) { sStart = oSettings.fnFormatNumber( 1 ); } if ( oSettings.fnRecordsDisplay() === 0 && oSettings.fnRecordsDisplay() == oSettings.fnRecordsTotal() ) { /* Empty record set */ sOut = oSettings.oLanguage.sInfoEmpty+ oSettings.oLanguage.sInfoPostFix; } else if ( oSettings.fnRecordsDisplay() === 0 ) { /* Rmpty record set after filtering */ sOut = oSettings.oLanguage.sInfoEmpty +' '+ oSettings.oLanguage.sInfoFiltered.replace('_MAX_', sMax)+ oSettings.oLanguage.sInfoPostFix; } else if ( oSettings.fnRecordsDisplay() == oSettings.fnRecordsTotal() ) { /* Normal record set */ sOut = oSettings.oLanguage.sInfo. replace('_START_', sStart). replace('_END_', sEnd). replace('_TOTAL_', sTotal)+ oSettings.oLanguage.sInfoPostFix; } else { /* Record set after filtering */ sOut = oSettings.oLanguage.sInfo. replace('_START_', sStart). replace('_END_', sEnd). replace('_TOTAL_', sTotal) +' '+ oSettings.oLanguage.sInfoFiltered.replace('_MAX_', oSettings.fnFormatNumber(oSettings.fnRecordsTotal()))+ oSettings.oLanguage.sInfoPostFix; } if ( oSettings.oLanguage.fnInfoCallback !== null ) { sOut = oSettings.oLanguage.fnInfoCallback( oSettings, iStart, iEnd, iMax, iTotal, sOut ); } var n = oSettings.aanFeatures.i; for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { $(n[i]).html( sOut ); } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: Length change */ /* * Function: _fnFeatureHtmlLength * Purpose: Generate the node required for user display length changing * Returns: node * Inputs: object:oSettings - dataTables settings object */ function _fnFeatureHtmlLength ( oSettings ) { if ( oSettings.oScroll.bInfinite ) { return null; } /* This can be overruled by not using the _MENU_ var/macro in the language variable */ var sName = (oSettings.sTableId === "") ? "" : 'name="'+oSettings.sTableId+'_length"'; var sStdMenu = '<select size="1" '+sName+'>'; var i, iLen; if ( oSettings.aLengthMenu.length == 2 && typeof oSettings.aLengthMenu[0] == 'object' && typeof oSettings.aLengthMenu[1] == 'object' ) { for ( i=0, iLen=oSettings.aLengthMenu[0].length ; i<iLen ; i++ ) { sStdMenu += '<option value="'+oSettings.aLengthMenu[0][i]+'">'+ oSettings.aLengthMenu[1][i]+'</option>'; } } else { for ( i=0, iLen=oSettings.aLengthMenu.length ; i<iLen ; i++ ) { sStdMenu += '<option value="'+oSettings.aLengthMenu[i]+'">'+ oSettings.aLengthMenu[i]+'</option>'; } } sStdMenu += '</select>'; var nLength = document.createElement( 'div' ); if ( oSettings.sTableId !== '' && typeof oSettings.aanFeatures.l == "undefined" ) { nLength.setAttribute( 'id', oSettings.sTableId+'_length' ); } nLength.className = oSettings.oClasses.sLength; nLength.innerHTML = '<label>'+oSettings.oLanguage.sLengthMenu.replace( '_MENU_', sStdMenu )+'</label>'; /* * Set the length to the current display length - thanks to Andrea Pavlovic for this fix, * and Stefan Skopnik for fixing the fix! */ $('select option[value="'+oSettings._iDisplayLength+'"]',nLength).attr("selected",true); $('select', nLength).bind( 'change.DT', function(e) { var iVal = $(this).val(); /* Update all other length options for the new display */ var n = oSettings.aanFeatures.l; for ( i=0, iLen=n.length ; i<iLen ; i++ ) { if ( n[i] != this.parentNode ) { $('select', n[i]).val( iVal ); } } /* Redraw the table */ oSettings._iDisplayLength = parseInt(iVal, 10); _fnCalculateEnd( oSettings ); /* If we have space to show extra rows (backing up from the end point - then do so */ if ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() ) { oSettings._iDisplayStart = oSettings.fnDisplayEnd() - oSettings._iDisplayLength; if ( oSettings._iDisplayStart < 0 ) { oSettings._iDisplayStart = 0; } } if ( oSettings._iDisplayLength == -1 ) { oSettings._iDisplayStart = 0; } _fnDraw( oSettings ); } ); return nLength; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: Processing incidator */ /* * Function: _fnFeatureHtmlProcessing * Purpose: Generate the node required for the processing node * Returns: node * Inputs: object:oSettings - dataTables settings object */ function _fnFeatureHtmlProcessing ( oSettings ) { var nProcessing = document.createElement( 'div' ); if ( oSettings.sTableId !== '' && typeof oSettings.aanFeatures.r == "undefined" ) { nProcessing.setAttribute( 'id', oSettings.sTableId+'_processing' ); } nProcessing.innerHTML = oSettings.oLanguage.sProcessing; nProcessing.className = oSettings.oClasses.sProcessing; oSettings.nTable.parentNode.insertBefore( nProcessing, oSettings.nTable ); return nProcessing; } /* * Function: _fnProcessingDisplay * Purpose: Display or hide the processing indicator * Returns: - * Inputs: object:oSettings - dataTables settings object * bool: * true - show the processing indicator * false - don't show */ function _fnProcessingDisplay ( oSettings, bShow ) { if ( oSettings.oFeatures.bProcessing ) { var an = oSettings.aanFeatures.r; for ( var i=0, iLen=an.length ; i<iLen ; i++ ) { an[i].style.visibility = bShow ? "visible" : "hidden"; } } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Support functions */ /* * Function: _fnVisibleToColumnIndex * Purpose: Covert the index of a visible column to the index in the data array (take account * of hidden columns) * Returns: int:i - the data index * Inputs: object:oSettings - dataTables settings object */ function _fnVisibleToColumnIndex( oSettings, iMatch ) { var iColumn = -1; for ( var i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bVisible === true ) { iColumn++; } if ( iColumn == iMatch ) { return i; } } return null; } /* * Function: _fnColumnIndexToVisible * Purpose: Covert the index of an index in the data array and convert it to the visible * column index (take account of hidden columns) * Returns: int:i - the data index * Inputs: object:oSettings - dataTables settings object */ function _fnColumnIndexToVisible( oSettings, iMatch ) { var iVisible = -1; for ( var i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bVisible === true ) { iVisible++; } if ( i == iMatch ) { return oSettings.aoColumns[i].bVisible === true ? iVisible : null; } } return null; } /* * Function: _fnNodeToDataIndex * Purpose: Take a TR element and convert it to an index in aoData * Returns: int:i - index if found, null if not * Inputs: object:s - dataTables settings object * node:n - the TR element to find */ function _fnNodeToDataIndex( s, n ) { var i, iLen; /* Optimisation - see if the nodes which are currently visible match, since that is * the most likely node to be asked for (a selector or event for example) */ for ( i=s._iDisplayStart, iLen=s._iDisplayEnd ; i<iLen ; i++ ) { if ( s.aoData[ s.aiDisplay[i] ].nTr == n ) { return s.aiDisplay[i]; } } /* Otherwise we are in for a slog through the whole data cache */ for ( i=0, iLen=s.aoData.length ; i<iLen ; i++ ) { if ( s.aoData[i].nTr == n ) { return i; } } return null; } /* * Function: _fnVisbleColumns * Purpose: Get the number of visible columns * Returns: int:i - the number of visible columns * Inputs: object:oS - dataTables settings object */ function _fnVisbleColumns( oS ) { var iVis = 0; for ( var i=0 ; i<oS.aoColumns.length ; i++ ) { if ( oS.aoColumns[i].bVisible === true ) { iVis++; } } return iVis; } /* * Function: _fnCalculateEnd * Purpose: Rcalculate the end point based on the start point * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnCalculateEnd( oSettings ) { if ( oSettings.oFeatures.bPaginate === false ) { oSettings._iDisplayEnd = oSettings.aiDisplay.length; } else { /* Set the end point of the display - based on how many elements there are * still to display */ if ( oSettings._iDisplayStart + oSettings._iDisplayLength > oSettings.aiDisplay.length || oSettings._iDisplayLength == -1 ) { oSettings._iDisplayEnd = oSettings.aiDisplay.length; } else { oSettings._iDisplayEnd = oSettings._iDisplayStart + oSettings._iDisplayLength; } } } /* * Function: _fnConvertToWidth * Purpose: Convert a CSS unit width to pixels (e.g. 2em) * Returns: int:iWidth - width in pixels * Inputs: string:sWidth - width to be converted * node:nParent - parent to get the with for (required for * relative widths) - optional */ function _fnConvertToWidth ( sWidth, nParent ) { if ( !sWidth || sWidth === null || sWidth === '' ) { return 0; } if ( typeof nParent == "undefined" ) { nParent = document.getElementsByTagName('body')[0]; } var iWidth; var nTmp = document.createElement( "div" ); nTmp.style.width = _fnStringToCss( sWidth ); nParent.appendChild( nTmp ); iWidth = nTmp.offsetWidth; nParent.removeChild( nTmp ); return ( iWidth ); } /* * Function: _fnCalculateColumnWidths * Purpose: Calculate the width of columns for the table * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnCalculateColumnWidths ( oSettings ) { var iTableWidth = oSettings.nTable.offsetWidth; var iUserInputs = 0; var iTmpWidth; var iVisibleColumns = 0; var iColums = oSettings.aoColumns.length; var i, iIndex, iCorrector, iWidth; var oHeaders = $('th', oSettings.nTHead); /* Convert any user input sizes into pixel sizes */ for ( i=0 ; i<iColums ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { iVisibleColumns++; if ( oSettings.aoColumns[i].sWidth !== null ) { iTmpWidth = _fnConvertToWidth( oSettings.aoColumns[i].sWidthOrig, oSettings.nTable.parentNode ); if ( iTmpWidth !== null ) { oSettings.aoColumns[i].sWidth = _fnStringToCss( iTmpWidth ); } iUserInputs++; } } } /* If the number of columns in the DOM equals the number that we have to process in * DataTables, then we can use the offsets that are created by the web-browser. No custom * sizes can be set in order for this to happen, nor scrolling used */ if ( iColums == oHeaders.length && iUserInputs === 0 && iVisibleColumns == iColums && oSettings.oScroll.sX === "" && oSettings.oScroll.sY === "" ) { for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { iTmpWidth = $(oHeaders[i]).width(); if ( iTmpWidth !== null ) { oSettings.aoColumns[i].sWidth = _fnStringToCss( iTmpWidth ); } } } else { /* Otherwise we are going to have to do some calculations to get the width of each column. * Construct a 1 row table with the widest node in the data, and any user defined widths, * then insert it into the DOM and allow the browser to do all the hard work of * calculating table widths. */ var nCalcTmp = oSettings.nTable.cloneNode( false ), nTheadClone = oSettings.nTHead.cloneNode(true), nBody = document.createElement( 'tbody' ), nTr = document.createElement( 'tr' ), nDivSizing; nCalcTmp.removeAttribute( "id" ); nCalcTmp.appendChild( nTheadClone ); if ( oSettings.nTFoot !== null ) { nCalcTmp.appendChild( oSettings.nTFoot.cloneNode(true) ); _fnApplyToChildren( function(n) { n.style.width = ""; }, nCalcTmp.getElementsByTagName('tr') ); } nCalcTmp.appendChild( nBody ); nBody.appendChild( nTr ); /* Remove any sizing that was previously applied by the styles */ var jqColSizing = $('thead th', nCalcTmp); if ( jqColSizing.length === 0 ) { jqColSizing = $('tbody tr:eq(0)>td', nCalcTmp); } /* Apply custom sizing to the cloned header */ var nThs = _fnGetUniqueThs( oSettings, nTheadClone ); iCorrector = 0; for ( i=0 ; i<iColums ; i++ ) { var oColumn = oSettings.aoColumns[i]; if ( oColumn.bVisible && oColumn.sWidthOrig !== null && oColumn.sWidthOrig !== "" ) { nThs[i-iCorrector].style.width = _fnStringToCss( oColumn.sWidthOrig ); } else if ( oColumn.bVisible ) { nThs[i-iCorrector].style.width = ""; } else { iCorrector++; } } /* Find the biggest td for each column and put it into the table */ for ( i=0 ; i<iColums ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { var nTd = _fnGetWidestNode( oSettings, i ); if ( nTd !== null ) { nTd = nTd.cloneNode(true); if ( oSettings.aoColumns[i].sContentPadding !== "" ) { nTd.innerHTML += oSettings.aoColumns[i].sContentPadding; } nTr.appendChild( nTd ); } } } /* Build the table and 'display' it */ var nWrapper = oSettings.nTable.parentNode; nWrapper.appendChild( nCalcTmp ); /* When scrolling (X or Y) we want to set the width of the table as appropriate. However, * when not scrolling leave the table width as it is. This results in slightly different, * but I think correct behaviour */ if ( oSettings.oScroll.sX !== "" && oSettings.oScroll.sXInner !== "" ) { nCalcTmp.style.width = _fnStringToCss(oSettings.oScroll.sXInner); } else if ( oSettings.oScroll.sX !== "" ) { nCalcTmp.style.width = ""; if ( $(nCalcTmp).width() < nWrapper.offsetWidth ) { nCalcTmp.style.width = _fnStringToCss( nWrapper.offsetWidth ); } } else if ( oSettings.oScroll.sY !== "" ) { nCalcTmp.style.width = _fnStringToCss( nWrapper.offsetWidth ); } nCalcTmp.style.visibility = "hidden"; /* Scrolling considerations */ _fnScrollingWidthAdjust( oSettings, nCalcTmp ); /* Read the width's calculated by the browser and store them for use by the caller. We * first of all try to use the elements in the body, but it is possible that there are * no elements there, under which circumstances we use the header elements */ var oNodes = $("tbody tr:eq(0)", nCalcTmp).children(); if ( oNodes.length === 0 ) { oNodes = _fnGetUniqueThs( oSettings, $('thead', nCalcTmp)[0] ); } /* Browsers need a bit of a hand when a width is assigned to any columns when * x-scrolling as they tend to collapse the table to the min-width, even if * we sent the column widths. So we need to keep track of what the table width * should be by summing the user given values, and the automatic values */ if ( oSettings.oScroll.sX !== "" ) { var iTotal = 0; iCorrector = 0; for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { if ( oSettings.aoColumns[i].sWidthOrig === null ) { iTotal += $(oNodes[iCorrector]).outerWidth(); } else { iTotal += parseInt(oSettings.aoColumns[i].sWidth.replace('px',''), 10) + ($(oNodes[iCorrector]).outerWidth() - $(oNodes[iCorrector]).width()); } iCorrector++; } } nCalcTmp.style.width = _fnStringToCss( iTotal ); oSettings.nTable.style.width = _fnStringToCss( iTotal ); } iCorrector = 0; for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { iWidth = $(oNodes[iCorrector]).width(); if ( iWidth !== null && iWidth > 0 ) { oSettings.aoColumns[i].sWidth = _fnStringToCss( iWidth ); } iCorrector++; } } oSettings.nTable.style.width = _fnStringToCss( $(nCalcTmp).outerWidth() ); nCalcTmp.parentNode.removeChild( nCalcTmp ); } } /* * Function: _fnScrollingWidthAdjust * Purpose: Adjust a table's width to take account of scrolling * Returns: - * Inputs: object:oSettings - dataTables settings object * node:n - table node */ function _fnScrollingWidthAdjust ( oSettings, n ) { if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY !== "" ) { /* When y-scrolling only, we want to remove the width of the scroll bar so the table * + scroll bar will fit into the area avaialble. */ var iOrigWidth = $(n).width(); n.style.width = _fnStringToCss( $(n).outerWidth()-oSettings.oScroll.iBarWidth ); } else if ( oSettings.oScroll.sX !== "" ) { /* When x-scrolling both ways, fix the table at it's current size, without adjusting */ n.style.width = _fnStringToCss( $(n).outerWidth() ); } } /* * Function: _fnGetWidestNode * Purpose: Get the widest node * Returns: string: - max strlens for each column * Inputs: object:oSettings - dataTables settings object * int:iCol - column of interest */ function _fnGetWidestNode( oSettings, iCol ) { var iMaxIndex = _fnGetMaxLenString( oSettings, iCol ); if ( iMaxIndex < 0 ) { return null; } if ( oSettings.aoData[iMaxIndex].nTr === null ) { var n = document.createElement('td'); n.innerHTML = _fnGetCellData( oSettings, iMaxIndex, iCol, '' ); return n; } return _fnGetTdNodes(oSettings, iMaxIndex)[iCol]; } /* * Function: _fnGetMaxLenString * Purpose: Get the maximum strlen for each data column * Returns: string: - max strlens for each column * Inputs: object:oSettings - dataTables settings object * int:iCol - column of interest */ function _fnGetMaxLenString( oSettings, iCol ) { var iMax = -1; var iMaxIndex = -1; for ( var i=0 ; i<oSettings.aoData.length ; i++ ) { var s = _fnGetCellData( oSettings, i, iCol, 'display' )+""; s = s.replace( /<.*?>/g, "" ); if ( s.length > iMax ) { iMax = s.length; iMaxIndex = i; } } return iMaxIndex; } /* * Function: _fnStringToCss * Purpose: Append a CSS unit (only if required) to a string * Returns: 0 if match, 1 if length is different, 2 if no match * Inputs: array:aArray1 - first array * array:aArray2 - second array */ function _fnStringToCss( s ) { if ( s === null ) { return "0px"; } if ( typeof s == 'number' ) { if ( s < 0 ) { return "0px"; } return s+"px"; } /* Check if the last character is not 0-9 */ var c = s.charCodeAt( s.length-1 ); if (c < 0x30 || c > 0x39) { return s; } return s+"px"; } /* * Function: _fnArrayCmp * Purpose: Compare two arrays * Returns: 0 if match, 1 if length is different, 2 if no match * Inputs: array:aArray1 - first array * array:aArray2 - second array */ function _fnArrayCmp( aArray1, aArray2 ) { if ( aArray1.length != aArray2.length ) { return 1; } for ( var i=0 ; i<aArray1.length ; i++ ) { if ( aArray1[i] != aArray2[i] ) { return 2; } } return 0; } /* * Function: _fnDetectType * Purpose: Get the sort type based on an input string * Returns: string: - type (defaults to 'string' if no type can be detected) * Inputs: string:sData - data we wish to know the type of * Notes: This function makes use of the DataTables plugin objct _oExt * (.aTypes) such that new types can easily be added. */ function _fnDetectType( sData ) { var aTypes = _oExt.aTypes; var iLen = aTypes.length; for ( var i=0 ; i<iLen ; i++ ) { var sType = aTypes[i]( sData ); if ( sType !== null ) { return sType; } } return 'string'; } /* * Function: _fnSettingsFromNode * Purpose: Return the settings object for a particular table * Returns: object: Settings object - or null if not found * Inputs: node:nTable - table we are using as a dataTable */ function _fnSettingsFromNode ( nTable ) { for ( var i=0 ; i<_aoSettings.length ; i++ ) { if ( _aoSettings[i].nTable == nTable ) { return _aoSettings[i]; } } return null; } /* * Function: _fnGetDataMaster * Purpose: Return an array with the full table data * Returns: array array:aData - Master data array * Inputs: object:oSettings - dataTables settings object */ function _fnGetDataMaster ( oSettings ) { var aData = []; var iLen = oSettings.aoData.length; for ( var i=0 ; i<iLen; i++ ) { aData.push( oSettings.aoData[i]._aData ); } return aData; } /* * Function: _fnGetTrNodes * Purpose: Return an array with the TR nodes for the table * Returns: array: - TR array * Inputs: object:oSettings - dataTables settings object */ function _fnGetTrNodes ( oSettings ) { var aNodes = []; for ( var i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( oSettings.aoData[i].nTr !== null ) { aNodes.push( oSettings.aoData[i].nTr ); } } return aNodes; } /* * Function: _fnGetTdNodes * Purpose: Return an flat array with all TD nodes for the table, or row * Returns: array: - TD array * Inputs: object:oSettings - dataTables settings object * int:iIndividualRow - aoData index to get the nodes for - optional if not * given then the return array will contain all nodes for the table */ function _fnGetTdNodes ( oSettings, iIndividualRow ) { var anReturn = []; var iCorrector; var anTds; var iRow, iRows=oSettings.aoData.length, iColumn, iColumns, oData, sNodeName, iStart=0, iEnd=iRows; /* Allow the collection to be limited to just one row */ if ( typeof iIndividualRow != 'undefined' ) { iStart = iIndividualRow; iEnd = iIndividualRow+1; } for ( iRow=iStart ; iRow<iEnd ; iRow++ ) { oData = oSettings.aoData[iRow]; if ( oData.nTr !== null ) { /* get the TD child nodes - taking into account text etc nodes */ anTds = []; for ( iColumn=0, iColumns=oData.nTr.childNodes.length ; iColumn<iColumns ; iColumn++ ) { sNodeName = oData.nTr.childNodes[iColumn].nodeName.toLowerCase(); if ( sNodeName == 'td' || sNodeName == 'th' ) { anTds.push( oData.nTr.childNodes[iColumn] ); } } iCorrector = 0; for ( iColumn=0, iColumns=oSettings.aoColumns.length ; iColumn<iColumns ; iColumn++ ) { if ( oSettings.aoColumns[iColumn].bVisible ) { anReturn.push( anTds[iColumn-iCorrector] ); } else { anReturn.push( oData._anHidden[iColumn] ); iCorrector++; } } } } return anReturn; } /* * Function: _fnEscapeRegex * Purpose: scape a string stuch that it can be used in a regular expression * Returns: string: - escaped string * Inputs: string:sVal - string to escape */ function _fnEscapeRegex ( sVal ) { var acEscape = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^' ]; var reReplace = new RegExp( '(\\' + acEscape.join('|\\') + ')', 'g' ); return sVal.replace(reReplace, '\\$1'); } /* * Function: _fnDeleteIndex * Purpose: Take an array of integers (index array) and remove a target integer (value - not * the key!) * Returns: - * Inputs: a:array int - Index array to target * int:iTarget - value to find */ function _fnDeleteIndex( a, iTarget ) { var iTargetIndex = -1; for ( var i=0, iLen=a.length ; i<iLen ; i++ ) { if ( a[i] == iTarget ) { iTargetIndex = i; } else if ( a[i] > iTarget ) { a[i]--; } } if ( iTargetIndex != -1 ) { a.splice( iTargetIndex, 1 ); } } /* * Function: _fnReOrderIndex * Purpose: Figure out how to reorder a display list * Returns: array int:aiReturn - index list for reordering * Inputs: object:oSettings - dataTables settings object */ function _fnReOrderIndex ( oSettings, sColumns ) { var aColumns = sColumns.split(','); var aiReturn = []; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { for ( var j=0 ; j<iLen ; j++ ) { if ( oSettings.aoColumns[i].sName == aColumns[j] ) { aiReturn.push( j ); break; } } } return aiReturn; } /* * Function: _fnColumnOrdering * Purpose: Get the column ordering that DataTables expects * Returns: string: - comma separated list of names * Inputs: object:oSettings - dataTables settings object */ function _fnColumnOrdering ( oSettings ) { var sNames = ''; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { sNames += oSettings.aoColumns[i].sName+','; } if ( sNames.length == iLen ) { return ""; } return sNames.slice(0, -1); } /* * Function: _fnLog * Purpose: Log an error message * Returns: - * Inputs: int:iLevel - log error messages, or display them to the user * string:sMesg - error message */ function _fnLog( oSettings, iLevel, sMesg ) { var sAlert = oSettings.sTableId === "" ? "DataTables warning: " +sMesg : "DataTables warning (table id = '"+oSettings.sTableId+"'): " +sMesg; if ( iLevel === 0 ) { if ( _oExt.sErrMode == 'alert' ) { alert( sAlert ); } else { throw sAlert; } return; } else if ( typeof console != 'undefined' && typeof console.log != 'undefined' ) { console.log( sAlert ); } } /* * Function: _fnClearTable * Purpose: Nuke the table * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnClearTable( oSettings ) { oSettings.aoData.splice( 0, oSettings.aoData.length ); oSettings.aiDisplayMaster.splice( 0, oSettings.aiDisplayMaster.length ); oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length ); _fnCalculateEnd( oSettings ); } /* * Function: _fnSaveState * Purpose: Save the state of a table in a cookie such that the page can be reloaded * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnSaveState ( oSettings ) { if ( !oSettings.oFeatures.bStateSave || typeof oSettings.bDestroying != 'undefined' ) { return; } /* Store the interesting variables */ var i, iLen, sTmp; var sValue = "{"; sValue += '"iCreate":'+ new Date().getTime()+','; sValue += '"iStart":'+ (oSettings.oScroll.bInfinite ? 0 : oSettings._iDisplayStart)+','; sValue += '"iEnd":'+ (oSettings.oScroll.bInfinite ? oSettings._iDisplayLength : oSettings._iDisplayEnd)+','; sValue += '"iLength":'+ oSettings._iDisplayLength+','; sValue += '"sFilter":"'+ encodeURIComponent(oSettings.oPreviousSearch.sSearch)+'",'; sValue += '"sFilterEsc":'+ !oSettings.oPreviousSearch.bRegex+','; sValue += '"aaSorting":[ '; for ( i=0 ; i<oSettings.aaSorting.length ; i++ ) { sValue += '['+oSettings.aaSorting[i][0]+',"'+oSettings.aaSorting[i][1]+'"],'; } sValue = sValue.substring(0, sValue.length-1); sValue += "],"; sValue += '"aaSearchCols":[ '; for ( i=0 ; i<oSettings.aoPreSearchCols.length ; i++ ) { sValue += '["'+encodeURIComponent(oSettings.aoPreSearchCols[i].sSearch)+ '",'+!oSettings.aoPreSearchCols[i].bRegex+'],'; } sValue = sValue.substring(0, sValue.length-1); sValue += "],"; sValue += '"abVisCols":[ '; for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { sValue += oSettings.aoColumns[i].bVisible+","; } sValue = sValue.substring(0, sValue.length-1); sValue += "]"; /* Save state from any plug-ins */ for ( i=0, iLen=oSettings.aoStateSave.length ; i<iLen ; i++ ) { sTmp = oSettings.aoStateSave[i].fn( oSettings, sValue ); if ( sTmp !== "" ) { sValue = sTmp; } } sValue += "}"; _fnCreateCookie( oSettings.sCookiePrefix+oSettings.sInstance, sValue, oSettings.iCookieDuration, oSettings.sCookiePrefix, oSettings.fnCookieCallback ); } /* * Function: _fnLoadState * Purpose: Attempt to load a saved table state from a cookie * Returns: - * Inputs: object:oSettings - dataTables settings object * object:oInit - DataTables init object so we can override settings */ function _fnLoadState ( oSettings, oInit ) { if ( !oSettings.oFeatures.bStateSave ) { return; } var oData, i, iLen; var sData = _fnReadCookie( oSettings.sCookiePrefix+oSettings.sInstance ); if ( sData !== null && sData !== '' ) { /* Try/catch the JSON eval - if it is bad then we ignore it - note that 1.7.0 and before * incorrectly used single quotes for some strings - hence the replace below */ try { oData = (typeof $.parseJSON == 'function') ? $.parseJSON( sData.replace(/'/g, '"') ) : eval( '('+sData+')' ); } catch( e ) { return; } /* Allow custom and plug-in manipulation functions to alter the data set which was * saved, and also reject any saved state by returning false */ for ( i=0, iLen=oSettings.aoStateLoad.length ; i<iLen ; i++ ) { if ( !oSettings.aoStateLoad[i].fn( oSettings, oData ) ) { return; } } /* Store the saved state so it might be accessed at any time (particualrly a plug-in */ oSettings.oLoadedState = $.extend( true, {}, oData ); /* Restore key features */ oSettings._iDisplayStart = oData.iStart; oSettings.iInitDisplayStart = oData.iStart; oSettings._iDisplayEnd = oData.iEnd; oSettings._iDisplayLength = oData.iLength; oSettings.oPreviousSearch.sSearch = decodeURIComponent(oData.sFilter); oSettings.aaSorting = oData.aaSorting.slice(); oSettings.saved_aaSorting = oData.aaSorting.slice(); /* * Search filtering - global reference added in 1.4.1 * Note that we use a 'not' for the value of the regular expression indicator to maintain * compatibility with pre 1.7 versions, where this was basically inverted. Added in 1.7.0 */ if ( typeof oData.sFilterEsc != 'undefined' ) { oSettings.oPreviousSearch.bRegex = !oData.sFilterEsc; } /* Column filtering - added in 1.5.0 beta 6 */ if ( typeof oData.aaSearchCols != 'undefined' ) { for ( i=0 ; i<oData.aaSearchCols.length ; i++ ) { oSettings.aoPreSearchCols[i] = { "sSearch": decodeURIComponent(oData.aaSearchCols[i][0]), "bRegex": !oData.aaSearchCols[i][1] }; } } /* Column visibility state - added in 1.5.0 beta 10 */ if ( typeof oData.abVisCols != 'undefined' ) { /* Pass back visibiliy settings to the init handler, but to do not here override * the init object that the user might have passed in */ oInit.saved_aoColumns = []; for ( i=0 ; i<oData.abVisCols.length ; i++ ) { oInit.saved_aoColumns[i] = {}; oInit.saved_aoColumns[i].bVisible = oData.abVisCols[i]; } } } } /* * Function: _fnCreateCookie * Purpose: Create a new cookie with a value to store the state of a table * Returns: - * Inputs: string:sName - name of the cookie to create * string:sValue - the value the cookie should take * int:iSecs - duration of the cookie * string:sBaseName - sName is made up of the base + file name - this is the base * function:fnCallback - User definable function to modify the cookie */ function _fnCreateCookie ( sName, sValue, iSecs, sBaseName, fnCallback ) { var date = new Date(); date.setTime( date.getTime()+(iSecs*1000) ); /* * Shocking but true - it would appear IE has major issues with having the path not having * a trailing slash on it. We need the cookie to be available based on the path, so we * have to append the file name to the cookie name. Appalling. Thanks to vex for adding the * patch to use at least some of the path */ var aParts = window.location.pathname.split('/'); var sNameFile = sName + '_' + aParts.pop().replace(/[\/:]/g,"").toLowerCase(); var sFullCookie, oData; if ( fnCallback !== null ) { oData = (typeof $.parseJSON == 'function') ? $.parseJSON( sValue ) : eval( '('+sValue+')' ); sFullCookie = fnCallback( sNameFile, oData, date.toGMTString(), aParts.join('/')+"/" ); } else { sFullCookie = sNameFile + "=" + encodeURIComponent(sValue) + "; expires=" + date.toGMTString() +"; path=" + aParts.join('/')+"/"; } /* Are we going to go over the cookie limit of 4KiB? If so, try to delete a cookies * belonging to DataTables. This is FAR from bullet proof */ var sOldName="", iOldTime=9999999999999; var iLength = _fnReadCookie( sNameFile )!==null ? document.cookie.length : sFullCookie.length + document.cookie.length; if ( iLength+10 > 4096 ) /* Magic 10 for padding */ { var aCookies =document.cookie.split(';'); for ( var i=0, iLen=aCookies.length ; i<iLen ; i++ ) { if ( aCookies[i].indexOf( sBaseName ) != -1 ) { /* It's a DataTables cookie, so eval it and check the time stamp */ var aSplitCookie = aCookies[i].split('='); try { oData = eval( '('+decodeURIComponent(aSplitCookie[1])+')' ); } catch( e ) { continue; } if ( typeof oData.iCreate != 'undefined' && oData.iCreate < iOldTime ) { sOldName = aSplitCookie[0]; iOldTime = oData.iCreate; } } } if ( sOldName !== "" ) { document.cookie = sOldName+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path="+ aParts.join('/') + "/"; } } document.cookie = sFullCookie; } /* * Function: _fnReadCookie * Purpose: Read an old cookie to get a cookie with an old table state * Returns: string: - contents of the cookie - or null if no cookie with that name found * Inputs: string:sName - name of the cookie to read */ function _fnReadCookie ( sName ) { var aParts = window.location.pathname.split('/'), sNameEQ = sName + '_' + aParts[aParts.length-1].replace(/[\/:]/g,"").toLowerCase() + '=', sCookieContents = document.cookie.split(';'); for( var i=0 ; i<sCookieContents.length ; i++ ) { var c = sCookieContents[i]; while (c.charAt(0)==' ') { c = c.substring(1,c.length); } if (c.indexOf(sNameEQ) === 0) { return decodeURIComponent( c.substring(sNameEQ.length,c.length) ); } } return null; } /* * Function: _fnDetectHeader * Purpose: Use the DOM source to create up an array of header cells. The idea here is to * create a layout grid (array) of rows x columns, which contains a reference * to the cell that that point in the grid (regardless of col/rowspan), such that * any column / row could be removed and the new grid constructed * Returns: void * Outputs: array object:aLayout - Array to store the calculated layout in * Inputs: node:nThead - The header/footer element for the table */ function _fnDetectHeader ( aLayout, nThead ) { var nTrs = nThead.getElementsByTagName('tr'); var nCell; var i, j, k, l, iLen, jLen, iColShifted; var fnShiftCol = function ( a, i, j ) { while ( typeof a[i][j] != 'undefined' ) { j++; } return j; }; aLayout.splice( 0, aLayout.length ); /* We know how many rows there are in the layout - so prep it */ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { aLayout.push( [] ); } /* Calculate a layout array */ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { var iColumn = 0; /* For every cell in the row... */ for ( j=0, jLen=nTrs[i].childNodes.length ; j<jLen ; j++ ) { nCell = nTrs[i].childNodes[j]; if ( nCell.nodeName.toUpperCase() == "TD" || nCell.nodeName.toUpperCase() == "TH" ) { /* Get the col and rowspan attributes from the DOM and sanitise them */ var iColspan = nCell.getAttribute('colspan') * 1; var iRowspan = nCell.getAttribute('rowspan') * 1; iColspan = (!iColspan || iColspan===0 || iColspan===1) ? 1 : iColspan; iRowspan = (!iRowspan || iRowspan===0 || iRowspan===1) ? 1 : iRowspan; /* There might be colspan cells already in this row, so shift our target * accordingly */ iColShifted = fnShiftCol( aLayout, i, iColumn ); /* If there is col / rowspan, copy the information into the layout grid */ for ( l=0 ; l<iColspan ; l++ ) { for ( k=0 ; k<iRowspan ; k++ ) { aLayout[i+k][iColShifted+l] = { "cell": nCell, "unique": iColspan == 1 ? true : false }; aLayout[i+k].nTr = nTrs[i]; } } } } } } /* * Function: _fnGetUniqueThs * Purpose: Get an array of unique th elements, one for each column * Returns: array node:aReturn - list of unique ths * Inputs: object:oSettings - dataTables settings object * node:nHeader - automatically detect the layout from this node - optional * array object:aLayout - thead/tfoot layout from _fnDetectHeader - optional */ function _fnGetUniqueThs ( oSettings, nHeader, aLayout ) { var aReturn = []; if ( typeof aLayout == 'undefined' ) { aLayout = oSettings.aoHeader; if ( typeof nHeader != 'undefined' ) { aLayout = []; _fnDetectHeader( aLayout, nHeader ); } } for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ ) { for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ ) { if ( aLayout[i][j].unique && (typeof aReturn[j] == 'undefined' || !oSettings.bSortCellsTop) ) { aReturn[j] = aLayout[i][j].cell; } } } return aReturn; } /* * Function: _fnScrollBarWidth * Purpose: Get the width of a scroll bar in this browser being used * Returns: int: - width in pixels * Inputs: - * Notes: All credit for this function belongs to Alexandre Gomes. Thanks for sharing! * http://www.alexandre-gomes.com/?p=115 */ function _fnScrollBarWidth () { var inner = document.createElement('p'); var style = inner.style; style.width = "100%"; style.height = "200px"; var outer = document.createElement('div'); style = outer.style; style.position = "absolute"; style.top = "0px"; style.left = "0px"; style.visibility = "hidden"; style.width = "200px"; style.height = "150px"; style.overflow = "hidden"; outer.appendChild(inner); document.body.appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if ( w1 == w2 ) { w2 = outer.clientWidth; } document.body.removeChild(outer); return (w1 - w2); } /* * Function: _fnApplyToChildren * Purpose: Apply a given function to the display child nodes of an element array (typically * TD children of TR rows * Returns: - (done by reference) * Inputs: function:fn - Method to apply to the objects * array nodes:an1 - List of elements to look through for display children * array nodes:an2 - Another list (identical structure to the first) - optional */ function _fnApplyToChildren( fn, an1, an2 ) { for ( var i=0, iLen=an1.length ; i<iLen ; i++ ) { for ( var j=0, jLen=an1[i].childNodes.length ; j<jLen ; j++ ) { if ( an1[i].childNodes[j].nodeType == 1 ) { if ( typeof an2 != 'undefined' ) { fn( an1[i].childNodes[j], an2[i].childNodes[j] ); } else { fn( an1[i].childNodes[j] ); } } } } } /* * Function: _fnMap * Purpose: See if a property is defined on one object, if so assign it to the other object * Returns: - (done by reference) * Inputs: object:oRet - target object * object:oSrc - source object * string:sName - property * string:sMappedName - name to map too - optional, sName used if not given */ function _fnMap( oRet, oSrc, sName, sMappedName ) { if ( typeof sMappedName == 'undefined' ) { sMappedName = sName; } if ( typeof oSrc[sName] != 'undefined' ) { oRet[sMappedName] = oSrc[sName]; } } /* * Function: _fnGetRowData * Purpose: Get an array of data for a given row from the internal data cache * Returns: array: - Data array * Inputs: object:oSettings - dataTables settings object * int:iRow - aoData row id * string:sSpecific - data get type ('type' 'filter' 'sort') */ function _fnGetRowData( oSettings, iRow, sSpecific ) { var out = []; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { out.push( _fnGetCellData( oSettings, iRow, i, sSpecific ) ); } return out; } /* * Function: _fnGetCellData * Purpose: Get the data for a given cell from the internal cache, taking into account data mapping * Returns: *: - Cell data * Inputs: object:oSettings - dataTables settings object * int:iRow - aoData row id * int:iCol - Column index * string:sSpecific - data get type ('display', 'type' 'filter' 'sort') */ function _fnGetCellData( oSettings, iRow, iCol, sSpecific ) { var sData; var oCol = oSettings.aoColumns[iCol]; var oData = oSettings.aoData[iRow]._aData; if ( (sData=oCol.fnGetData( oData )) === undefined ) { if ( oSettings.iDrawError != oSettings.iDraw && oCol.sDefaultContent === null ) { _fnLog( oSettings, 0, "Requested unknown parameter '"+oCol.mDataProp+ "' from the data source for row "+iRow ); oSettings.iDrawError = oSettings.iDraw; } return oCol.sDefaultContent; } /* When the data source is null, we can use default column data */ if ( sData === null && oCol.sDefaultContent !== null ) { sData = oCol.sDefaultContent; } if ( sSpecific == 'display' && sData === null ) { return ''; } return sData; } /* * Function: _fnSetCellData * Purpose: Set the value for a specific cell, into the internal data cache * Returns: *: - Cell data * Inputs: object:oSettings - dataTables settings object * int:iRow - aoData row id * int:iCol - Column index * *:val - Value to set */ function _fnSetCellData( oSettings, iRow, iCol, val ) { var oCol = oSettings.aoColumns[iCol]; var oData = oSettings.aoData[iRow]._aData; oCol.fnSetData( oData, val ); } /* * Function: _fnGetObjectDataFn * Purpose: Return a function that can be used to get data from a source object, taking * into account the ability to use nested objects as a source * Returns: function: - Data get function * Inputs: string|int|function:mSource - The data source for the object */ function _fnGetObjectDataFn( mSource ) { if ( mSource === null ) { /* Give an empty string for rendering / sorting etc */ return function (data) { return null; }; } else if ( typeof mSource == 'function' ) { return function (data) { return mSource( data ); }; } else if ( typeof mSource == 'string' && mSource.indexOf('.') != -1 ) { /* If there is a . in the source string then the data source is in a nested object * we provide two 'quick' functions for the look up to speed up the most common * operation, and a generalised one for when it is needed */ var a = mSource.split('.'); if ( a.length == 2 ) { return function (data) { return data[ a[0] ][ a[1] ]; }; } else if ( a.length == 3 ) { return function (data) { return data[ a[0] ][ a[1] ][ a[2] ]; }; } else { return function (data) { for ( var i=0, iLen=a.length ; i<iLen ; i++ ) { data = data[ a[i] ]; } return data; }; } } else { /* Array or flat object mapping */ return function (data) { return data[mSource]; }; } } /* * Function: _fnSetObjectDataFn * Purpose: Return a function that can be used to set data from a source object, taking * into account the ability to use nested objects as a source * Returns: function: - Data set function * Inputs: string|int|function:mSource - The data source for the object */ function _fnSetObjectDataFn( mSource ) { if ( mSource === null ) { /* Nothing to do when the data source is null */ return function (data, val) {}; } else if ( typeof mSource == 'function' ) { return function (data, val) { return mSource( data, val ); }; } else if ( typeof mSource == 'string' && mSource.indexOf('.') != -1 ) { /* Like the get, we need to get data from a nested object. Again two fast lookup * functions are provided, and a generalised one. */ var a = mSource.split('.'); if ( a.length == 2 ) { return function (data, val) { data[ a[0] ][ a[1] ] = val; }; } else if ( a.length == 3 ) { return function (data, val) { data[ a[0] ][ a[1] ][ a[2] ] = val; }; } else { return function (data, val) { for ( var i=0, iLen=a.length-1 ; i<iLen ; i++ ) { data = data[ a[i] ]; } data[ a[a.length-1] ] = val; }; } } else { /* Array or flat object mapping */ return function (data, val) { data[mSource] = val; }; } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - API * I'm not happy with this solution... - To be fixed in 2.0 */ this.oApi._fnExternApiFunc = _fnExternApiFunc; this.oApi._fnInitalise = _fnInitalise; this.oApi._fnInitComplete = _fnInitComplete; this.oApi._fnLanguageProcess = _fnLanguageProcess; this.oApi._fnAddColumn = _fnAddColumn; this.oApi._fnColumnOptions = _fnColumnOptions; this.oApi._fnAddData = _fnAddData; this.oApi._fnCreateTr = _fnCreateTr; this.oApi._fnGatherData = _fnGatherData; this.oApi._fnBuildHead = _fnBuildHead; this.oApi._fnDrawHead = _fnDrawHead; this.oApi._fnDraw = _fnDraw; this.oApi._fnReDraw = _fnReDraw; this.oApi._fnAjaxUpdate = _fnAjaxUpdate; this.oApi._fnAjaxUpdateDraw = _fnAjaxUpdateDraw; this.oApi._fnAddOptionsHtml = _fnAddOptionsHtml; this.oApi._fnFeatureHtmlTable = _fnFeatureHtmlTable; this.oApi._fnScrollDraw = _fnScrollDraw; this.oApi._fnAjustColumnSizing = _fnAjustColumnSizing; this.oApi._fnFeatureHtmlFilter = _fnFeatureHtmlFilter; this.oApi._fnFilterComplete = _fnFilterComplete; this.oApi._fnFilterCustom = _fnFilterCustom; this.oApi._fnFilterColumn = _fnFilterColumn; this.oApi._fnFilter = _fnFilter; this.oApi._fnBuildSearchArray = _fnBuildSearchArray; this.oApi._fnBuildSearchRow = _fnBuildSearchRow; this.oApi._fnFilterCreateSearch = _fnFilterCreateSearch; this.oApi._fnDataToSearch = _fnDataToSearch; this.oApi._fnSort = _fnSort; this.oApi._fnSortAttachListener = _fnSortAttachListener; this.oApi._fnSortingClasses = _fnSortingClasses; this.oApi._fnFeatureHtmlPaginate = _fnFeatureHtmlPaginate; this.oApi._fnPageChange = _fnPageChange; this.oApi._fnFeatureHtmlInfo = _fnFeatureHtmlInfo; this.oApi._fnUpdateInfo = _fnUpdateInfo; this.oApi._fnFeatureHtmlLength = _fnFeatureHtmlLength; this.oApi._fnFeatureHtmlProcessing = _fnFeatureHtmlProcessing; this.oApi._fnProcessingDisplay = _fnProcessingDisplay; this.oApi._fnVisibleToColumnIndex = _fnVisibleToColumnIndex; this.oApi._fnColumnIndexToVisible = _fnColumnIndexToVisible; this.oApi._fnNodeToDataIndex = _fnNodeToDataIndex; this.oApi._fnVisbleColumns = _fnVisbleColumns; this.oApi._fnCalculateEnd = _fnCalculateEnd; this.oApi._fnConvertToWidth = _fnConvertToWidth; this.oApi._fnCalculateColumnWidths = _fnCalculateColumnWidths; this.oApi._fnScrollingWidthAdjust = _fnScrollingWidthAdjust; this.oApi._fnGetWidestNode = _fnGetWidestNode; this.oApi._fnGetMaxLenString = _fnGetMaxLenString; this.oApi._fnStringToCss = _fnStringToCss; this.oApi._fnArrayCmp = _fnArrayCmp; this.oApi._fnDetectType = _fnDetectType; this.oApi._fnSettingsFromNode = _fnSettingsFromNode; this.oApi._fnGetDataMaster = _fnGetDataMaster; this.oApi._fnGetTrNodes = _fnGetTrNodes; this.oApi._fnGetTdNodes = _fnGetTdNodes; this.oApi._fnEscapeRegex = _fnEscapeRegex; this.oApi._fnDeleteIndex = _fnDeleteIndex; this.oApi._fnReOrderIndex = _fnReOrderIndex; this.oApi._fnColumnOrdering = _fnColumnOrdering; this.oApi._fnLog = _fnLog; this.oApi._fnClearTable = _fnClearTable; this.oApi._fnSaveState = _fnSaveState; this.oApi._fnLoadState = _fnLoadState; this.oApi._fnCreateCookie = _fnCreateCookie; this.oApi._fnReadCookie = _fnReadCookie; this.oApi._fnDetectHeader = _fnDetectHeader; this.oApi._fnGetUniqueThs = _fnGetUniqueThs; this.oApi._fnScrollBarWidth = _fnScrollBarWidth; this.oApi._fnApplyToChildren = _fnApplyToChildren; this.oApi._fnMap = _fnMap; this.oApi._fnGetRowData = _fnGetRowData; this.oApi._fnGetCellData = _fnGetCellData; this.oApi._fnSetCellData = _fnSetCellData; this.oApi._fnGetObjectDataFn = _fnGetObjectDataFn; this.oApi._fnSetObjectDataFn = _fnSetObjectDataFn; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Constructor */ /* Want to be able to reference "this" inside the this.each function */ var _that = this; return this.each(function() { var i=0, iLen, j, jLen, k, kLen; /* Check to see if we are re-initalising a table */ for ( i=0, iLen=_aoSettings.length ; i<iLen ; i++ ) { /* Base check on table node */ if ( _aoSettings[i].nTable == this ) { if ( typeof oInit == 'undefined' || ( typeof oInit.bRetrieve != 'undefined' && oInit.bRetrieve === true ) ) { return _aoSettings[i].oInstance; } else if ( typeof oInit.bDestroy != 'undefined' && oInit.bDestroy === true ) { _aoSettings[i].oInstance.fnDestroy(); break; } else { _fnLog( _aoSettings[i], 0, "Cannot reinitialise DataTable.\n\n"+ "To retrieve the DataTables object for this table, please pass either no arguments "+ "to the dataTable() function, or set bRetrieve to true. Alternatively, to destory "+ "the old table and create a new one, set bDestroy to true (note that a lot of "+ "changes to the configuration can be made through the API which is usually much "+ "faster)." ); return; } } /* If the element we are initialising has the same ID as a table which was previously * initialised, but the table nodes don't match (from before) then we destory the old * instance by simply deleting it. This is under the assumption that the table has been * destroyed by other methods. Anyone using non-id selectors will need to do this manually */ if ( _aoSettings[i].sTableId !== "" && _aoSettings[i].sTableId == this.getAttribute('id') ) { _aoSettings.splice( i, 1 ); break; } } /* Make a complete and independent copy of the settings object */ var oSettings = new classSettings(); _aoSettings.push( oSettings ); var bInitHandedOff = false; var bUsePassedData = false; /* Set the id */ var sId = this.getAttribute( 'id' ); if ( sId !== null ) { oSettings.sTableId = sId; oSettings.sInstance = sId; } else { oSettings.sInstance = _oExt._oExternConfig.iNextUnique ++; } /* Sanity check */ if ( this.nodeName.toLowerCase() != 'table' ) { _fnLog( oSettings, 0, "Attempted to initialise DataTables on a node which is not a "+ "table: "+this.nodeName ); return; } /* Set the table node */ oSettings.nTable = this; /* Keep a reference to the 'this' instance for the table. Note that if this table is being * created with others, we retrieve a unique instance to ease API access. */ oSettings.oInstance = _that.length == 1 ? _that : $(this).dataTable(); /* Bind the API functions to the settings, so we can perform actions whenever oSettings is * available */ oSettings.oApi = _that.oApi; /* State the table's width for if a destroy is called at a later time */ oSettings.sDestroyWidth = $(this).width(); /* Store the features that we have available */ if ( typeof oInit != 'undefined' && oInit !== null ) { oSettings.oInit = oInit; _fnMap( oSettings.oFeatures, oInit, "bPaginate" ); _fnMap( oSettings.oFeatures, oInit, "bLengthChange" ); _fnMap( oSettings.oFeatures, oInit, "bFilter" ); _fnMap( oSettings.oFeatures, oInit, "bSort" ); _fnMap( oSettings.oFeatures, oInit, "bInfo" ); _fnMap( oSettings.oFeatures, oInit, "bProcessing" ); _fnMap( oSettings.oFeatures, oInit, "bAutoWidth" ); _fnMap( oSettings.oFeatures, oInit, "bSortClasses" ); _fnMap( oSettings.oFeatures, oInit, "bServerSide" ); _fnMap( oSettings.oFeatures, oInit, "bDeferRender" ); _fnMap( oSettings.oScroll, oInit, "sScrollX", "sX" ); _fnMap( oSettings.oScroll, oInit, "sScrollXInner", "sXInner" ); _fnMap( oSettings.oScroll, oInit, "sScrollY", "sY" ); _fnMap( oSettings.oScroll, oInit, "bScrollCollapse", "bCollapse" ); _fnMap( oSettings.oScroll, oInit, "bScrollInfinite", "bInfinite" ); _fnMap( oSettings.oScroll, oInit, "iScrollLoadGap", "iLoadGap" ); _fnMap( oSettings.oScroll, oInit, "bScrollAutoCss", "bAutoCss" ); _fnMap( oSettings, oInit, "asStripClasses" ); _fnMap( oSettings, oInit, "fnPreDrawCallback" ); _fnMap( oSettings, oInit, "fnRowCallback" ); _fnMap( oSettings, oInit, "fnHeaderCallback" ); _fnMap( oSettings, oInit, "fnFooterCallback" ); _fnMap( oSettings, oInit, "fnCookieCallback" ); _fnMap( oSettings, oInit, "fnInitComplete" ); _fnMap( oSettings, oInit, "fnServerData" ); _fnMap( oSettings, oInit, "fnFormatNumber" ); _fnMap( oSettings, oInit, "aaSorting" ); _fnMap( oSettings, oInit, "aaSortingFixed" ); _fnMap( oSettings, oInit, "aLengthMenu" ); _fnMap( oSettings, oInit, "sPaginationType" ); _fnMap( oSettings, oInit, "sAjaxSource" ); _fnMap( oSettings, oInit, "sAjaxDataProp" ); _fnMap( oSettings, oInit, "iCookieDuration" ); _fnMap( oSettings, oInit, "sCookiePrefix" ); _fnMap( oSettings, oInit, "sDom" ); _fnMap( oSettings, oInit, "bSortCellsTop" ); _fnMap( oSettings, oInit, "oSearch", "oPreviousSearch" ); _fnMap( oSettings, oInit, "aoSearchCols", "aoPreSearchCols" ); _fnMap( oSettings, oInit, "iDisplayLength", "_iDisplayLength" ); _fnMap( oSettings, oInit, "bJQueryUI", "bJUI" ); _fnMap( oSettings.oLanguage, oInit, "fnInfoCallback" ); /* Callback functions which are array driven */ if ( typeof oInit.fnDrawCallback == 'function' ) { oSettings.aoDrawCallback.push( { "fn": oInit.fnDrawCallback, "sName": "user" } ); } if ( typeof oInit.fnStateSaveCallback == 'function' ) { oSettings.aoStateSave.push( { "fn": oInit.fnStateSaveCallback, "sName": "user" } ); } if ( typeof oInit.fnStateLoadCallback == 'function' ) { oSettings.aoStateLoad.push( { "fn": oInit.fnStateLoadCallback, "sName": "user" } ); } if ( oSettings.oFeatures.bServerSide && oSettings.oFeatures.bSort && oSettings.oFeatures.bSortClasses ) { /* Enable sort classes for server-side processing. Safe to do it here, since server-side * processing must be enabled by the developer */ oSettings.aoDrawCallback.push( { "fn": _fnSortingClasses, "sName": "server_side_sort_classes" } ); } else if ( oSettings.oFeatures.bDeferRender ) { oSettings.aoDrawCallback.push( { "fn": _fnSortingClasses, "sName": "defer_sort_classes" } ); } if ( typeof oInit.bJQueryUI != 'undefined' && oInit.bJQueryUI ) { /* Use the JUI classes object for display. You could clone the oStdClasses object if * you want to have multiple tables with multiple independent classes */ oSettings.oClasses = _oExt.oJUIClasses; if ( typeof oInit.sDom == 'undefined' ) { /* Set the DOM to use a layout suitable for jQuery UI's theming */ oSettings.sDom = '<"H"lfr>t<"F"ip>'; } } /* Calculate the scroll bar width and cache it for use later on */ if ( oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "" ) { oSettings.oScroll.iBarWidth = _fnScrollBarWidth(); } if ( typeof oInit.iDisplayStart != 'undefined' && typeof oSettings.iInitDisplayStart == 'undefined' ) { /* Display start point, taking into account the save saving */ oSettings.iInitDisplayStart = oInit.iDisplayStart; oSettings._iDisplayStart = oInit.iDisplayStart; } /* Must be done after everything which can be overridden by a cookie! */ if ( typeof oInit.bStateSave != 'undefined' ) { oSettings.oFeatures.bStateSave = oInit.bStateSave; _fnLoadState( oSettings, oInit ); oSettings.aoDrawCallback.push( { "fn": _fnSaveState, "sName": "state_save" } ); } if ( typeof oInit.iDeferLoading != 'undefined' ) { oSettings.bDeferLoading = true; oSettings._iRecordsTotal = oInit.iDeferLoading; oSettings._iRecordsDisplay = oInit.iDeferLoading; } if ( typeof oInit.aaData != 'undefined' ) { bUsePassedData = true; } /* Backwards compatability */ /* aoColumns / aoData - remove at some point... */ if ( typeof oInit != 'undefined' && typeof oInit.aoData != 'undefined' ) { oInit.aoColumns = oInit.aoData; } /* Language definitions */ if ( typeof oInit.oLanguage != 'undefined' ) { if ( typeof oInit.oLanguage.sUrl != 'undefined' && oInit.oLanguage.sUrl !== "" ) { /* Get the language definitions from a file */ oSettings.oLanguage.sUrl = oInit.oLanguage.sUrl; $.getJSON( oSettings.oLanguage.sUrl, null, function( json ) { _fnLanguageProcess( oSettings, json, true ); } ); bInitHandedOff = true; } else { _fnLanguageProcess( oSettings, oInit.oLanguage, false ); } } /* Warning: The _fnLanguageProcess function is async to the remainder of this function due * to the XHR. We use _bInitialised in _fnLanguageProcess() to check this the processing * below is complete. The reason for spliting it like this is optimisation - we can fire * off the XHR (if needed) and then continue processing the data. */ } else { /* Create a dummy object for quick manipulation later on. */ oInit = {}; } /* * Stripes * Add the strip classes now that we know which classes to apply - unless overruled */ if ( typeof oInit.asStripClasses == 'undefined' ) { oSettings.asStripClasses.push( oSettings.oClasses.sStripOdd ); oSettings.asStripClasses.push( oSettings.oClasses.sStripEven ); } /* Remove row stripe classes if they are already on the table row */ var bStripeRemove = false; var anRows = $('>tbody>tr', this); for ( i=0, iLen=oSettings.asStripClasses.length ; i<iLen ; i++ ) { if ( anRows.filter(":lt(2)").hasClass( oSettings.asStripClasses[i]) ) { bStripeRemove = true; break; } } if ( bStripeRemove ) { /* Store the classes which we are about to remove so they can be readded on destory */ oSettings.asDestoryStrips = [ '', '' ]; if ( $(anRows[0]).hasClass(oSettings.oClasses.sStripOdd) ) { oSettings.asDestoryStrips[0] += oSettings.oClasses.sStripOdd+" "; } if ( $(anRows[0]).hasClass(oSettings.oClasses.sStripEven) ) { oSettings.asDestoryStrips[0] += oSettings.oClasses.sStripEven; } if ( $(anRows[1]).hasClass(oSettings.oClasses.sStripOdd) ) { oSettings.asDestoryStrips[1] += oSettings.oClasses.sStripOdd+" "; } if ( $(anRows[1]).hasClass(oSettings.oClasses.sStripEven) ) { oSettings.asDestoryStrips[1] += oSettings.oClasses.sStripEven; } anRows.removeClass( oSettings.asStripClasses.join(' ') ); } /* * Columns * See if we should load columns automatically or use defined ones */ var anThs = []; var aoColumnsInit; var nThead = this.getElementsByTagName('thead'); if ( nThead.length !== 0 ) { _fnDetectHeader( oSettings.aoHeader, nThead[0] ); anThs = _fnGetUniqueThs( oSettings ); } /* If not given a column array, generate one with nulls */ if ( typeof oInit.aoColumns == 'undefined' ) { aoColumnsInit = []; for ( i=0, iLen=anThs.length ; i<iLen ; i++ ) { aoColumnsInit.push( null ); } } else { aoColumnsInit = oInit.aoColumns; } /* Add the columns */ for ( i=0, iLen=aoColumnsInit.length ; i<iLen ; i++ ) { /* Check if we have column visibilty state to restore */ if ( typeof oInit.saved_aoColumns != 'undefined' && oInit.saved_aoColumns.length == iLen ) { if ( aoColumnsInit[i] === null ) { aoColumnsInit[i] = {}; } aoColumnsInit[i].bVisible = oInit.saved_aoColumns[i].bVisible; } _fnAddColumn( oSettings, anThs ? anThs[i] : null ); } /* Add options from column definations */ if ( typeof oInit.aoColumnDefs != 'undefined' ) { /* Loop over the column defs array - loop in reverse so first instace has priority */ for ( i=oInit.aoColumnDefs.length-1 ; i>=0 ; i-- ) { /* Each column def can target multiple columns, as it is an array */ var aTargets = oInit.aoColumnDefs[i].aTargets; if ( !$.isArray( aTargets ) ) { _fnLog( oSettings, 1, 'aTargets must be an array of targets, not a '+(typeof aTargets) ); } for ( j=0, jLen=aTargets.length ; j<jLen ; j++ ) { if ( typeof aTargets[j] == 'number' && aTargets[j] >= 0 ) { /* 0+ integer, left to right column counting. We add columns which are unknown * automatically. Is this the right behaviour for this? We should at least * log it in future. We cannot do this for the negative or class targets, only here. */ while( oSettings.aoColumns.length <= aTargets[j] ) { _fnAddColumn( oSettings ); } _fnColumnOptions( oSettings, aTargets[j], oInit.aoColumnDefs[i] ); } else if ( typeof aTargets[j] == 'number' && aTargets[j] < 0 ) { /* Negative integer, right to left column counting */ _fnColumnOptions( oSettings, oSettings.aoColumns.length+aTargets[j], oInit.aoColumnDefs[i] ); } else if ( typeof aTargets[j] == 'string' ) { /* Class name matching on TH element */ for ( k=0, kLen=oSettings.aoColumns.length ; k<kLen ; k++ ) { if ( aTargets[j] == "_all" || $(oSettings.aoColumns[k].nTh).hasClass( aTargets[j] ) ) { _fnColumnOptions( oSettings, k, oInit.aoColumnDefs[i] ); } } } } } } /* Add options from column array - after the defs array so this has priority */ if ( typeof aoColumnsInit != 'undefined' ) { for ( i=0, iLen=aoColumnsInit.length ; i<iLen ; i++ ) { _fnColumnOptions( oSettings, i, aoColumnsInit[i] ); } } /* * Sorting * Check the aaSorting array */ for ( i=0, iLen=oSettings.aaSorting.length ; i<iLen ; i++ ) { if ( oSettings.aaSorting[i][0] >= oSettings.aoColumns.length ) { oSettings.aaSorting[i][0] = 0; } var oColumn = oSettings.aoColumns[ oSettings.aaSorting[i][0] ]; /* Add a default sorting index */ if ( typeof oSettings.aaSorting[i][2] == 'undefined' ) { oSettings.aaSorting[i][2] = 0; } /* If aaSorting is not defined, then we use the first indicator in asSorting */ if ( typeof oInit.aaSorting == "undefined" && typeof oSettings.saved_aaSorting == "undefined" ) { oSettings.aaSorting[i][1] = oColumn.asSorting[0]; } /* Set the current sorting index based on aoColumns.asSorting */ for ( j=0, jLen=oColumn.asSorting.length ; j<jLen ; j++ ) { if ( oSettings.aaSorting[i][1] == oColumn.asSorting[j] ) { oSettings.aaSorting[i][2] = j; break; } } } /* Do a first pass on the sorting classes (allows any size changes to be taken into * account, and also will apply sorting disabled classes if disabled */ _fnSortingClasses( oSettings ); /* * Final init * Cache the header, body and footer as required, creating them if needed */ var thead = $('>thead', this); if ( thead.length === 0 ) { thead = [ document.createElement( 'thead' ) ]; this.appendChild( thead[0] ); } oSettings.nTHead = thead[0]; var tbody = $('>tbody', this); if ( tbody.length === 0 ) { tbody = [ document.createElement( 'tbody' ) ]; this.appendChild( tbody[0] ); } oSettings.nTBody = tbody[0]; var tfoot = $('>tfoot', this); if ( tfoot.length > 0 ) { oSettings.nTFoot = tfoot[0]; _fnDetectHeader( oSettings.aoFooter, oSettings.nTFoot ); } /* Check if there is data passing into the constructor */ if ( bUsePassedData ) { for ( i=0 ; i<oInit.aaData.length ; i++ ) { _fnAddData( oSettings, oInit.aaData[ i ] ); } } else { /* Grab the data from the page */ _fnGatherData( oSettings ); } /* Copy the data index array */ oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); /* Initialisation complete - table can be drawn */ oSettings.bInitialised = true; /* Check if we need to initialise the table (it might not have been handed off to the * language processor) */ if ( bInitHandedOff === false ) { _fnInitalise( oSettings ); } }); }; })(jQuery, window, document);
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Editor v 1.1 by revaxarts.com /* description: makes a WYSIWYG Editor /* dependency: jWYSIWYG Editor /*----------------------------------------------------------------------*/ $.fn.wl_Editor = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Editor.methods[method]) { return $.fn.wl_Editor.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Editor')) { var opts = $.extend({}, $this.data('wl_Editor'), method); } else { var opts = $.extend({}, $.fn.wl_Editor.defaults, method, $this.data()); } } else { try { return $this.wysiwyg(method, args[1], args[2], args[3]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_Editor')) { $this.data('wl_Editor', {}); //detroying and re-made the editor crashes safari on iOS Devices so I disabled it. //normally the browser don't get resized as much. //wysiwyg isn't working on iPhone anyway /* $(window).bind('resize.' + 'wl_Editor', function () { $this.wysiwyg('destroy').wysiwyg(opts.eOpts); }); */ //make an array out of the buttons or use it if it is allready an array opts.buttons = opts.buttons.split('|') || opts.buttons; //set initial options opts.eOpts = { initialContent: opts.initialContent, css: opts.css }; //set buttons visible if they are in the array var controls = {}; $.each(opts.buttons, function (i, id) { controls[id] = { visible: true }; }); //add them to the options $.extend(true, opts.eOpts, { controls: controls }, opts.eOpts); //call the jWYSIWYG plugin $this.wysiwyg(opts.eOpts); } else { } if (opts) $.extend($this.data('wl_Editor'), opts); }); }; $.fn.wl_Editor.defaults = { css: 'css/light/editor.css', buttons: 'bold|italic|underline|strikeThrough|justifyLeft|justifyCenter|justifyRight|justifyFull|highlight|colorpicker|indent|outdent|subscript|superscript|undo|redo|insertOrderedList|insertUnorderedList|insertHorizontalRule|createLink|insertImage|h1|h2|h3|h4|h5|h6|paragraph|rtl|ltr|cut|copy|paste|increaseFontSize|decreaseFontSize|html|code|removeFormat|insertTable', initialContent: "" }; $.fn.wl_Editor.version = '1.1'; $.fn.wl_Editor.methods = { destroy: function () { var $this = $(this); //destroy it! $this.wysiwyg('destroy'); $this.removeData('wl_Editor'); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Editor.defaults[key] !== undefined || $.fn.wl_Editor.defaults[key] == null) { $this.data('wl_Editor')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Alert v 1.1 by revaxarts.com /* description: Handles alert boxes /* dependency: jquery UI Slider, fadeOutSlide plugin /*----------------------------------------------------------------------*/ $.fn.wl_Alert = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Alert.methods[method]) { return $.fn.wl_Alert.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Alert')) { var opts = $.extend({}, $this.data('wl_Alert'), method); } else { var opts = $.extend({}, $.fn.wl_Alert.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Alert')) { $this.data('wl_Alert', {}); //bind click events to hide alert box $this.bind('click.wl_Alert', function (event) { event.preventDefault(); //Don't hide if it is sticky if (!$this.data('wl_Alert').sticky) { $.fn.wl_Alert.methods.close.call($this[0]); } //prevent hiding the box if an inline link is clicked }).find('a').bind('click.wl_Alert', function (event) { event.stopPropagation(); }); } else { } //show it if it is hidden if ($this.is(':hidden')) { $this.slideDown(opts.speed / 2); } if (opts) $.extend($this.data('wl_Alert'), opts); }); }; $.fn.wl_Alert.defaults = { speed: 500, sticky: false, onBeforeClose: function (element) {}, onClose: function (element) {} }; $.fn.wl_Alert.version = '1.1'; $.fn.wl_Alert.methods = { close: function () { var $this = $(this), opts = $this.data('wl_Alert'); //call callback and stop if it returns false if (opts.onBeforeClose.call(this, $this) === false) { return false; }; //fadeout and call an callback $this.fadeOutSlide(opts.speed, function () { opts.onClose.call($this[0], $this); }); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Alert.defaults[key] !== undefined || $.fn.wl_Alert.defaults[key] == null) { $this.data('wl_Alert')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } }; //to create an alert box on the fly $.wl_Alert = function (text, cssclass, insert, after, options) { //go thru all $('div.alert').each(function () { var _this = $(this); //...and hide if one with the same text is allready set if (_this.text() == text) { _this.slideUp($.fn.wl_Alert.defaults.speed); } }); //create a new DOM element and inject it var al = $('<div class="alert ' + cssclass + '">' + text + '</div>').hide(); (after) ? al.appendTo(insert).wl_Alert(options) : al.prependTo(insert).wl_Alert(options); //return the element return al; };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Breadcrumb v 1.0 by revaxarts.com /* description: Makes and handles a Breadcrumb navigation /* dependency: /*----------------------------------------------------------------------*/ $.fn.wl_Breadcrumb = function (method) { var args = arguments; return this.each(function () { var $this = $(this), $li = $this.find('li'); $a = $this.find('a'); if ($.fn.wl_Breadcrumb.methods[method]) { return $.fn.wl_Breadcrumb.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Breadcrumb')) { var opts = $.extend({}, $this.data('wl_Breadcrumb'), method); } else { var opts = $.extend({}, $.fn.wl_Breadcrumb.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } //get the current field or use the first if not set var $current = $this.find('a.active').eq(0); if (!$current.length) $current = $a.eq(opts.start); if (!$this.data('wl_Breadcrumb')) { $this.data('wl_Breadcrumb', {}); //each anchor $a.each(function (i) { var _this = $(this); //save the id _this.data('id', i); //prepend numbers if set if (opts.numbers) _this.text((i + 1) + '. ' + _this.text()); }); //each listelement $li.each(function (i) { var _this = $(this); //if has a class (must be an icon) if (_this.attr('class')) { //innerwrap the anchor to attach the icon $a.eq(i).wrapInner('<span class="' + _this.attr('class') + '"/>'); //remove the class from the list element _this.removeAttr('class'); } }); //add a 'last' class to the last element for IE :( if($.browser.msie)$li.filter(':last').addClass('last'); //Bind the click handler $this.delegate('a', 'click.wl_Breadcrumb', function () { var opts = $this.data('wl_Breadcrumb') || opts; //if disabled stop if (opts.disabled) return false; var _this = $(this); //if not allownextonly or data is current+1 or current-x if (!opts.allownextonly || _this.data('id') - $this.find('a.active').data('id') <= 1) { //activate and trigger callback $.fn.wl_Breadcrumb.methods.activate.call($this[0], _this); opts.onChange.call($this[0], _this, _this.data('id')); } return false; }); //connected breadcrumb if (opts.connect) { var $connect = $('#' + opts.connect), $pages = $connect.children(); //bind event to all 'next' class elements $connect.find('.next').bind('click.wl_Breadcrumb', function () { $this.wl_Breadcrumb('next'); return false; }); //bind event to all 'prev' class elements $connect.find('.prev').bind('click.wl_Breadcrumb', function () { $this.wl_Breadcrumb('prev'); return false; }); //hide all and show the starting one $pages.hide().eq(opts.start).show(); } //disable if set if (opts.disabled) { $this.wl_Breadcrumb('disable'); } } else { } if (opts) $.extend($this.data('wl_Breadcrumb'), opts); //activate the current part $.fn.wl_Breadcrumb.methods.activate.call(this, $current); }); }; $.fn.wl_Breadcrumb.defaults = { start: 0, numbers: false, allownextonly: false, disabled: false, connect: null, onChange: function () {} }; $.fn.wl_Breadcrumb.version = '1.0'; $.fn.wl_Breadcrumb.methods = { activate: function (element) { var $this = $(this); //element is a number so we mean the id if (typeof element === 'number') { element = $this.find('li').eq(element).find('a'); element.trigger('click.wl_Breadcrumb'); return false; } var _opts = $this.data('wl_Breadcrumb'); //remove classes $this.find('a').removeClass('active previous'); //find all previous tabs and add a class element.parent().prevAll().find('a').addClass('previous'); //add and active class to the current tab element.addClass('active'); //connected breadcrumb if (_opts.connect) { var $connect = $('#' + _opts.connect), $pages = $connect.children(); //hide all and show selected $pages.hide().eq(element.data('id')).show(); } }, disable: function () { var $this = $(this); //disable and add class disable $this.wl_Breadcrumb('set', 'disabled', true); $this.addClass('disabled'); }, enable: function () { var $this = $(this); //enable and remove class disable $this.wl_Breadcrumb('set', 'disabled', false); $this.removeClass('disabled'); }, next: function () { var $this = $(this); //click next tab $this.find('a.active').parent().next().find('a').trigger('click.wl_Breadcrumb'); }, prev: function () { var $this = $(this); //click prev tab $this.find('a.active').parent().prev().find('a').trigger('click.wl_Breadcrumb'); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Breadcrumb.defaults[key] !== undefined || $.fn.wl_Breadcrumb.defaults[key] == null) { $this.data('wl_Breadcrumb')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Slider v 1.1.1 by revaxarts.com /* description: /* dependency: jquery UI Slider, mousewheel plugin /*----------------------------------------------------------------------*/ $.fn.wl_Slider = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Slider.methods[method]) { return $.fn.wl_Slider.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Slider')) { var opts = $.extend({}, $this.data('wl_Slider'), method); } else { var opts = $.extend({}, $.fn.wl_Slider.defaults, method, $this.data()); } } else { try { return $this.slider(method, args[1], args[2]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_Slider')) { $this.data('wl_Slider', {}); //bind mousewheel events $this.bind('mousewheel.wl_Slider', function (event, delta) { if (opts.mousewheel) { //delta must be 1 or -1 (different on macs and with shiftkey pressed) delta = (delta < 0) ? -1 : 1; event.preventDefault(); //slider with one handler if ($this.data('range') !== true) { var _value = $this.slider('value'); $.fn.wl_Slider.methods.values.call($this[0], _value + (delta * opts.step)); //update the tooltip if (opts.tooltip){ var _handle = $this.find('a'); _handle.tipsy('setTitel',opts.tooltipPattern.replace('%n', _value + (delta * opts.step))); _handle.tipsy('update'); } //slider with two handlers } else { var _values = $this.slider('values'); var _handler = $this.find('a'), _h1 = _handler.eq(0).offset(), _h2 = _handler.eq(1).offset(); //callculate the affected handler depending on the mouseposition if (opts.orientation == 'horizontal') { if (_h1.left + (_h2.left - _h1.left) / 2 > event.clientX) { $.fn.wl_Slider.methods.values.call($this[0], Math.min(_values[0] + (delta * opts.step), _values[1]), _values[1]); } else { $.fn.wl_Slider.methods.values.call($this[0], _values[0], Math.max(_values[1] + (delta * opts.step), _values[0])); } } else if (opts.orientation == 'vertical') { if (_h2.top + (_h1.top - _h2.top) / 2 < event.pageY) { $.fn.wl_Slider.methods.values.call($this[0], Math.min(_values[0] + (delta * opts.step), _values[1]), _values[1]); } else { $.fn.wl_Slider.methods.values.call($this[0], _values[0], Math.max(_values[1] + (delta * opts.step), _values[0])); } } //update the tooltip if (opts.tooltip){ _handler.eq(0).tipsy('setTitel',opts.tooltipPattern.replace('%n', _values[0] + (delta * opts.step))); _handler.eq(0).tipsy('update'); _handler.eq(1).tipsy('setTitel',opts.tooltipPattern.replace('%n', _values[0] + (delta * opts.step))); _handler.eq(1).tipsy('update'); } } $.fn.wl_Slider.methods.slide.call($this[0]); } }); } else { //destroy it $this.unbind('slide slidechange').slider('destroy'); } //call the jQuery UI slider plugin and add callbacks $this.slider(opts).bind('slide', function (event, ui) { $.fn.wl_Slider.methods.slide.call($this[0], ui.value); }).bind('slidechange', function (event, ui) { $.fn.wl_Slider.methods.change.call($this[0], ui.value); }); //slider is connected to an input field if (opts.connect) { //single slider if ($this.data('range') !== true) { var _input = $('#' + opts.connect), _value = _input.val() || $this.data('value') || opts.min; if(!_input.data('wl_Number')) _input.wl_Number(); $this.unbind('slide slidechange').slider('value', _value); //set callbacks on slide to change input fields $this.bind('slide', function (event, ui) { _input.val(ui.value); $.fn.wl_Slider.methods.slide.call($this[0], ui.value); }).bind('slidechange', function (event, ui) { _input.val(ui.value); $.fn.wl_Slider.methods.change.call($this[0], ui.value); }); _input.val(_value).wl_Number('set', $.extend({}, opts, { onChange: function (value) { $this.slider('value', value); $this.wl_Slider('slide'); $this.wl_Slider('change'); } })); //range slider with two handlers } else { var _input = $.parseData(opts.connect, true), _input1 = $('#' + _input[0]), _input2 = $('#' + _input[1]), _value1 = _input1.val() || $this.data('values')[0] || opts.min, _value2 = _input2.val() || $this.data('values')[1] || opts.max; if(!_input1.data('wl_Number')) _input1.wl_Number(); if(!_input2.data('wl_Number')) _input2.wl_Number(); //set callbacks on slide to change input fields $this.unbind('slide slidechange').slider('option', 'values', [_value1, _value2]).bind('slide', function (event, ui) { _input1.val(ui.values[0]); _input2.val(ui.values[1]); $.fn.wl_Slider.methods.slide.call($this[0], ui.values); }).bind('slidechange', function (event, ui) { _input1.val(ui.values[0]); _input2.val(ui.values[1]); $.fn.wl_Slider.methods.change.call($this[0], ui.values); }); //set callbacks to the connected input fields _input1.wl_Number('set', $.extend({}, opts, { onChange: function (value) { $this.slider('option', 'values', [value, _input2.val()]); _input2.wl_Number('set', 'min', parseFloat(value)); $this.wl_Slider('slide'); $this.wl_Slider('change'); }, min: opts.min, max: _input2.val() || _value2 })).val(_value1); _input2.wl_Number('set', $.extend({}, opts, { onChange: function (value) { $this.slider('option', 'values', [_input1.val(), value]); _input1.wl_Number('set', 'max', parseFloat(value)); $this.wl_Slider('slide'); $this.wl_Slider('change'); }, min: _input1.val() || _value1, max: opts.max })).val(_value2); } } //activate tooltip if(opts.tooltip){ var e = $this.find('.ui-slider-handle'); var gravity, handles = []; //set the gravity if($.isArray(opts.tooltipGravity)){ if(opts.orientation == 'horizontal'){ gravity = opts.tooltipGravity[0]; }else if(opts.orientation == 'vertical'){ gravity = opts.tooltipGravity[1]; } }else{ gravity = opts.tooltipGravity; } //for each handle (e) $.each(e, function(i,handle){ var value; handles.push($(handle)); //get the value as array. set it to zero if undefined (required for init) if(opts.values){ value = opts.values; }else if(opts.value){ value = [opts.value]; }else{ value = [0,0]; } //use tipsy for a tooltip handles[i].tipsy($.extend({}, config.tooltip, { trigger: 'manual', gravity: gravity, html: true, fallback: opts.tooltipPattern.replace('%n',value[i]), appendTo: handles[i] })); //prevent the tooltip to wrap var tip = handles[i].tipsy('tip'); tip.find('.tipsy-inner').css('white-space','nowrap'); //bind events to the handler(s) handles[i].bind({ 'mouseenter.wl_Slider touchstart.wl_Slider':function(){handles[i].tipsy('show');}, 'mouseleave.wl_Slider touchend.wl_Slider':function(){handles[i].tipsy('hide');}, 'mouseenter touchstart':function(){handles[i].data('mouseIsOver',true);}, 'mouseleave touchend':function(){handles[i].data('mouseIsOver',false);} }); }); $this //unbind events if the slider starts (prevents flickering if the cursor leaves the handle) .bind('slidestart', function (event, ui) { $(ui.handle).unbind('mouseleave.wl_Slider touchstart.wl_Slider mouseenter.wl_Slider touchend.wl_Slider'); }) //rebind them again on slidestop .bind('slidestop', function (event, ui) { var handle = $(ui.handle); handle.bind({ 'mouseenter.wl_Slider touchstart.wl_Slider':function(){handle.tipsy('show');}, 'mouseleave.wl_Slider touchend.wl_Slider':function(){handle.tipsy('hide');} }); //hide the tooltip if the mouse isn't over the handle if(!handle.data('mouseIsOver'))handle.tipsy('hide'); }) //update the tooltip on the slide event .bind('slide', function (event, ui) { var handle = $(ui.handle); handle.tipsy('setTitel',opts.tooltipPattern.replace('%n',ui.value)); handle.tipsy('update'); }); } //disable if set if (opts.disabled) { $this.fn.wl_Slider.methods.disable.call($this[0]); } if (opts) $.extend($this.data('wl_Slider'), opts); }); }; $.fn.wl_Slider.defaults = { min: 0, max: 100, step: 1, animate: false, disabled: false, orientation: 'horizontal', range: false, mousewheel: true, connect: null, tooltip: false, tooltipGravity: ['s','w'], tooltipPattern: '%n', onSlide: function (value) {}, onChange: function (value) {} }; $.fn.wl_Slider.version = '1.1.1'; $.fn.wl_Slider.methods = { disable: function () { var $this = $(this), opts = $this.data('wl_Slider'); //disable slider $this.slider('disable'); //disable connected input fields if (opts.connect) { if ($this.data('range') !== true) { $('#' + opts.connect).prop('disabled', true); } else { var _input = $.parseData(opts.connect, true), _input1 = $('#' + _input[0]), _input2 = $('#' + _input[1]); _input1.attr('disabled', true); _input2.attr('disabled', true); } } $this.data('wl_Slider').disabled = true; }, enable: function () { var $this = $(this), opts = $this.data('wl_Slider'); //enable slider $this.slider('enable'); //enable connected input fields if ($this.data('wl_Slider').connect) { if ($this.data('range') !== true) { $('#' + opts.connect).prop('disabled', false); } else { var _input = $.parseData(opts.connect, true), _input1 = $('#' + _input[0]), _input2 = $('#' + _input[1]); _input1.removeAttr('disabled'); _input2.removeAttr('disabled'); } } $this.data('wl_Slider').disabled = false; }, change: function (value) { var $this = $(this), opts = $this.data('wl_Slider'); if ($this.data('range') !== true) { opts.onChange.call(this, value || $this.slider('value')); } else { opts.onChange.call(this, value || $this.slider('values')); } }, slide: function (value) { var $this = $(this), opts = $this.data('wl_Slider'); if ($this.data('range') !== true) { opts.onSlide.call(this, value || $this.slider('value')); } else { opts.onSlide.call(this, value || $this.slider('values')); } }, value: function () { var $this = $(this), opts = $this.data('wl_Slider'); if (opts.range !== true) { $this.slider('value', arguments[0]); } }, values: function () { var $this = $(this), opts = $this.data('wl_Slider'); if (opts.range === true) { if (typeof arguments[0] === 'object') { $this.slider('values', 0, arguments[0][0]); $this.slider('values', 1, arguments[0][1]); } else { $this.slider('values', 0, arguments[0]); $this.slider('values', 1, arguments[1]); } } else { $.fn.wl_Slider.methods.value.call(this, arguments[0]); } }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } if ($this.data('wl_Slider').connect) { if ($this.data('range') !== true) { var _input1 = $('#' + $this.data('wl_Slider').connect); } else { var _input = $.parseData($this.data('wl_Slider').connect, true), _input1 = $('#' + _input[0]), _input2 = $('#' + _input[1]); } } $.each(options, function (key, value) { if ($.fn.wl_Slider.defaults[key] !== undefined || $.fn.wl_Slider.defaults[key] == null) { $this.slider('option', key, value).data('wl_Slider')[key] = value; if (_input1) _input1.data(key, value).trigger('change'); if (_input2) _input2.data(key, value).trigger('change'); } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
$(document).ready(function () { /*----------------------------------------------------------------------*/ /* Parse the data from an data-attribute of DOM Elements /*----------------------------------------------------------------------*/ $.parseData = function (data, returnArray) { if (/^\[(.*)\]$/.test(data)) { //array data = data.substr(1, data.length - 2).split(','); } if (returnArray && !$.isArray(data) && data != null) { data = Array(data); } return data; }; /*----------------------------------------------------------------------*/ /* Image Preloader /* http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript /*----------------------------------------------------------------------*/ // Arguments are image paths relative to the current page. $.preload = function() { var cache = [], args_len = arguments.length; for (var i = args_len; i--;) { var cacheImage = document.createElement('img'); cacheImage.src = arguments[i]; cache.push(cacheImage); } }; /*----------------------------------------------------------------------*/ /* fadeInSlide by revaxarts.com /* Fades out a box and slide it up before it will get removed /*----------------------------------------------------------------------*/ $.fn.fadeInSlide = function (speed, callback) { if ($.isFunction(speed)) callback = speed; if (!speed) speed = 200; if (!callback) callback = function () {}; this.each(function () { var $this = $(this); $this.fadeTo(speed / 2, 1).slideDown(speed / 2, function () { callback(); }); }); return this; }; /*----------------------------------------------------------------------*/ /* fadeOutSlide by revaxarts.com /* Fades out a box and slide it up before it will get removed /*----------------------------------------------------------------------*/ $.fn.fadeOutSlide = function (speed, callback) { if ($.isFunction(speed)) callback = speed; if (!speed) speed = 200; if (!callback) callback = function () {}; this.each(function () { var $this = $(this); $this.fadeTo(speed / 2, 0).slideUp(speed / 2, function () { $this.remove(); callback(); }); }); return this; }; /*----------------------------------------------------------------------*/ /* textFadeOut by revaxarts.com /* Fades out a box and slide it up before it will get removed /*----------------------------------------------------------------------*/ $.fn.textFadeOut = function (text, delay, callback) { if (!text) return false; if ($.isFunction(delay)) callback = delay; if (!delay) delay = 2000; if (!callback) callback = function () {}; this.each(function () { var $this = $(this); $this.stop().text(text).show().delay(delay).fadeOut(1000,function(){ $this.text('').show(); callback(); }) }); return this; }; /*----------------------------------------------------------------------*/ /* leadingZero by revaxarts.com /* adds a leding zero if necessary /*----------------------------------------------------------------------*/ $.leadingZero = function (value) { value = parseInt(value, 10); if(!isNaN(value)) { (value < 10) ? value = '0' + value : value; } return value; }; });
JavaScript
$(document).ready(function() { var $body = $('body'), $content = $('#content'); //IE doen't like that fadein if(!$.browser.msie) $body.fadeTo(0,0.0).delay(500).fadeTo(1000, 1); $("input").not('input[type=submit]').uniform(); $content.find('.breadcrumb').wl_Breadcrumb({ allownextonly:true, onChange: function(el,id){ switch(id){ case 0: //Start break; case 1: //Information break; case 2: //Summery break; case 3: //Installation break; case 4: //Finish break; } } }); $('#loginbtn').click(function(){ location.href="login.html"; }); });
JavaScript
$(document).ready(function () { /** * FullCalendar v1.5.1 * http://arshaw.com/fullcalendar/ * * Use fullcalendar.css for basic styling. * For event drag & drop, requires jQuery UI draggable. * For event resizing, requires jQuery UI resizable. * * Copyright (c) 2011 Adam Shaw * Dual licensed under the MIT and GPL licenses, located in * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. * * Date: Sat Apr 9 14:09:51 2011 -0700 * */ (function($, undefined) { var defaults = { // display defaultView: 'month', aspectRatio: 1.35, header: { left: 'title', center: '', right: 'today prev,next' }, weekends: true, // editing //editable: false, //disableDragging: false, //disableResizing: false, allDayDefault: true, ignoreTimezone: true, // event ajax lazyFetching: true, startParam: 'start', endParam: 'end', // time formats titleFormat: { month: 'MMMM yyyy', week: "MMM d[ yyyy]{ '&#8212;'[ MMM] d yyyy}", day: 'dddd, MMM d, yyyy' }, columnFormat: { month: 'ddd', week: 'ddd M/d', day: 'dddd M/d' }, timeFormat: { // for event elements '': 'h(:mm)t' // default }, // locale isRTL: false, firstDay: 0, monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'], monthNamesShort: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'], dayNamesShort: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'], buttonText: { prev: '&nbsp;&#9668;&nbsp;', next: '&nbsp;&#9658;&nbsp;', prevYear: '&nbsp;&lt;&lt;&nbsp;', nextYear: '&nbsp;&gt;&gt;&nbsp;', today: 'today', month: 'month', week: 'week', day: 'day' }, // jquery-ui theming theme: false, buttonIcons: { prev: 'circle-triangle-w', next: 'circle-triangle-e' }, //selectable: false, unselectAuto: true, dropAccept: '*' }; // right-to-left defaults var rtlDefaults = { header: { left: 'next,prev today', center: '', right: 'title' }, buttonText: { prev: '&nbsp;&#9658;&nbsp;', next: '&nbsp;&#9668;&nbsp;', prevYear: '&nbsp;&gt;&gt;&nbsp;', nextYear: '&nbsp;&lt;&lt;&nbsp;' }, buttonIcons: { prev: 'circle-triangle-e', next: 'circle-triangle-w' } }; var fc = $.fullCalendar = { version: "1.5.1" }; var fcViews = fc.views = {}; $.fn.fullCalendar = function(options) { // method calling if (typeof options == 'string') { var args = Array.prototype.slice.call(arguments, 1); var res; this.each(function() { var calendar = $.data(this, 'fullCalendar'); if (calendar && $.isFunction(calendar[options])) { var r = calendar[options].apply(calendar, args); if (res === undefined) { res = r; } if (options == 'destroy') { $.removeData(this, 'fullCalendar'); } } }); if (res !== undefined) { return res; } return this; } // would like to have this logic in EventManager, but needs to happen before options are recursively extended var eventSources = options.eventSources || []; delete options.eventSources; if (options.events) { eventSources.push(options.events); delete options.events; } options = $.extend(true, {}, defaults, (options.isRTL || options.isRTL===undefined && defaults.isRTL) ? rtlDefaults : {}, options ); this.each(function(i, _element) { var element = $(_element); var calendar = new Calendar(element, options, eventSources); element.data('fullCalendar', calendar); // TODO: look into memory leak implications calendar.render(); }); return this; }; // function for adding/overriding defaults function setDefaults(d) { $.extend(true, defaults, d); } function Calendar(element, options, eventSources) { var t = this; // exports t.options = options; t.render = render; t.destroy = destroy; t.refetchEvents = refetchEvents; t.reportEvents = reportEvents; t.reportEventChange = reportEventChange; t.rerenderEvents = rerenderEvents; t.changeView = changeView; t.select = select; t.unselect = unselect; t.prev = prev; t.next = next; t.prevYear = prevYear; t.nextYear = nextYear; t.today = today; t.gotoDate = gotoDate; t.incrementDate = incrementDate; t.formatDate = function(format, date) { return formatDate(format, date, options) }; t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) }; t.getDate = getDate; t.getView = getView; t.option = option; t.trigger = trigger; // imports EventManager.call(t, options, eventSources); var isFetchNeeded = t.isFetchNeeded; var fetchEvents = t.fetchEvents; // locals var _element = element[0]; var header; var headerElement; var content; var tm; // for making theme classes var currentView; var viewInstances = {}; var elementOuterWidth; var suggestedViewHeight; var absoluteViewElement; var resizeUID = 0; var ignoreWindowResize = 0; var date = new Date(); var events = []; var _dragElement; /* Main Rendering -----------------------------------------------------------------------------*/ setYMD(date, options.year, options.month, options.date); function render(inc) { if (!content) { initialRender(); }else{ calcSize(); markSizesDirty(); markEventsDirty(); renderView(inc); } } function initialRender() { tm = options.theme ? 'ui' : 'fc'; element.addClass('fc'); if (options.isRTL) { element.addClass('fc-rtl'); } if (options.theme) { element.addClass('ui-widget'); } content = $("<div class='fc-content' style='position:relative'/>") .prependTo(element); header = new Header(t, options); headerElement = header.render(); if (headerElement) { element.prepend(headerElement); } changeView(options.defaultView); $(window).resize(windowResize); // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize if (!bodyVisible()) { lateRender(); } } // called when we know the calendar couldn't be rendered when it was initialized, // but we think it's ready now function lateRender() { setTimeout(function() { // IE7 needs this so dimensions are calculated correctly if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once renderView(); } },0); } function destroy() { $(window).unbind('resize', windowResize); header.destroy(); content.remove(); element.removeClass('fc fc-rtl ui-widget'); } function elementVisible() { return _element.offsetWidth !== 0; } function bodyVisible() { return $('body')[0].offsetWidth !== 0; } /* View Rendering -----------------------------------------------------------------------------*/ // TODO: improve view switching (still weird transition in IE, and FF has whiteout problem) function changeView(newViewName) { if (!currentView || newViewName != currentView.name) { ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached unselect(); var oldView = currentView; var newViewElement; if (oldView) { (oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera) setMinHeight(content, content.height()); oldView.element.hide(); }else{ setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated } content.css('overflow', 'hidden'); currentView = viewInstances[newViewName]; if (currentView) { currentView.element.show(); }else{ currentView = viewInstances[newViewName] = new fcViews[newViewName]( newViewElement = absoluteViewElement = $("<div class='fc-view fc-view-" + newViewName + "' style='position:absolute'/>") .appendTo(content), t // the calendar object ); } if (oldView) { header.deactivateButton(oldView.name); } header.activateButton(newViewName); renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null content.css('overflow', ''); if (oldView) { setMinHeight(content, 1); } if (!newViewElement) { (currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera) } ignoreWindowResize--; } } function renderView(inc) { if (elementVisible()) { ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached unselect(); if (suggestedViewHeight === undefined) { calcSize(); } var forceEventRender = false; if (!currentView.start || inc || date < currentView.start || date >= currentView.end) { // view must render an entire new date range (and refetch/render events) currentView.render(date, inc || 0); // responsible for clearing events setSize(true); forceEventRender = true; } else if (currentView.sizeDirty) { // view must resize (and rerender events) currentView.clearEvents(); setSize(); forceEventRender = true; } else if (currentView.eventsDirty) { currentView.clearEvents(); forceEventRender = true; } currentView.sizeDirty = false; currentView.eventsDirty = false; updateEvents(forceEventRender); elementOuterWidth = element.outerWidth(); header.updateTitle(currentView.title); var today = new Date(); if (today >= currentView.start && today < currentView.end) { header.disableButton('today'); }else{ header.enableButton('today'); } ignoreWindowResize--; currentView.trigger('viewDisplay', _element); } } /* Resizing -----------------------------------------------------------------------------*/ function updateSize() { markSizesDirty(); if (elementVisible()) { calcSize(); setSize(); unselect(); currentView.clearEvents(); currentView.renderEvents(events); currentView.sizeDirty = false; } } function markSizesDirty() { $.each(viewInstances, function(i, inst) { inst.sizeDirty = true; }); } function calcSize() { if (options.contentHeight) { suggestedViewHeight = options.contentHeight; } else if (options.height) { suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content); } else { suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5)); } } function setSize(dateChanged) { // todo: dateChanged? ignoreWindowResize++; currentView.setHeight(suggestedViewHeight, dateChanged); if (absoluteViewElement) { absoluteViewElement.css('position', 'relative'); absoluteViewElement = null; } currentView.setWidth(content.width(), dateChanged); ignoreWindowResize--; } function windowResize() { if (!ignoreWindowResize) { if (currentView.start) { // view has already been rendered var uid = ++resizeUID; setTimeout(function() { // add a delay if (uid == resizeUID && !ignoreWindowResize && elementVisible()) { if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) { ignoreWindowResize++; // in case the windowResize callback changes the height updateSize(); currentView.trigger('windowResize', _element); ignoreWindowResize--; } } }, 200); }else{ // calendar must have been initialized in a 0x0 iframe that has just been resized lateRender(); } } } /* Event Fetching/Rendering -----------------------------------------------------------------------------*/ // fetches events if necessary, rerenders events if necessary (or if forced) function updateEvents(forceRender) { if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) { refetchEvents(); } else if (forceRender) { rerenderEvents(); } } function refetchEvents() { fetchEvents(currentView.visStart, currentView.visEnd); // will call reportEvents } // called when event data arrives function reportEvents(_events) { events = _events; rerenderEvents(); } // called when a single event's data has been changed function reportEventChange(eventID) { rerenderEvents(eventID); } // attempts to rerenderEvents function rerenderEvents(modifiedEventID) { markEventsDirty(); if (elementVisible()) { currentView.clearEvents(); currentView.renderEvents(events, modifiedEventID); currentView.eventsDirty = false; } } function markEventsDirty() { $.each(viewInstances, function(i, inst) { inst.eventsDirty = true; }); } /* Selection -----------------------------------------------------------------------------*/ function select(start, end, allDay) { currentView.select(start, end, allDay===undefined ? true : allDay); } function unselect() { // safe to be called before renderView if (currentView) { currentView.unselect(); } } /* Date -----------------------------------------------------------------------------*/ function prev() { renderView(-1); } function next() { renderView(1); } function prevYear() { addYears(date, -1); renderView(); } function nextYear() { addYears(date, 1); renderView(); } function today() { date = new Date(); renderView(); } function gotoDate(year, month, dateOfMonth) { if (year instanceof Date) { date = cloneDate(year); // provided 1 argument, a Date }else{ setYMD(date, year, month, dateOfMonth); } renderView(); } function incrementDate(years, months, days) { if (years !== undefined) { addYears(date, years); } if (months !== undefined) { addMonths(date, months); } if (days !== undefined) { addDays(date, days); } renderView(); } function getDate() { return cloneDate(date); } /* Misc -----------------------------------------------------------------------------*/ function getView() { return currentView; } function option(name, value) { if (value === undefined) { return options[name]; } if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') { options[name] = value; updateSize(); } } function trigger(name, thisObj) { if (options[name]) { return options[name].apply( thisObj || _element, Array.prototype.slice.call(arguments, 2) ); } } /* External Dragging ------------------------------------------------------------------------*/ if (options.droppable) { $(document) .bind('dragstart', function(ev, ui) { var _e = ev.target; var e = $(_e); if (!e.parents('.fc').length) { // not already inside a calendar var accept = options.dropAccept; if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) { _dragElement = _e; currentView.dragStart(_dragElement, ev, ui); } } }) .bind('dragstop', function(ev, ui) { if (_dragElement) { currentView.dragStop(_dragElement, ev, ui); _dragElement = null; } }); } } function Header(calendar, options) { var t = this; // exports t.render = render; t.destroy = destroy; t.updateTitle = updateTitle; t.activateButton = activateButton; t.deactivateButton = deactivateButton; t.disableButton = disableButton; t.enableButton = enableButton; // locals var element = $([]); var tm; function render() { tm = options.theme ? 'ui' : 'fc'; var sections = options.header; if (sections) { element = $("<table class='fc-header' style='width:100%'/>") .append( $("<tr/>") .append(renderSection('left')) .append(renderSection('center')) .append(renderSection('right')) ); return element; } } function destroy() { element.remove(); } function renderSection(position) { var e = $("<td class='fc-header-" + position + "'/>"); var buttonStr = options.header[position]; if (buttonStr) { $.each(buttonStr.split(' '), function(i) { if (i > 0) { e.append("<span class='fc-header-space'/>"); } var prevButton; $.each(this.split(','), function(j, buttonName) { if (buttonName == 'title') { e.append("<span class='fc-header-title'><h2>&nbsp;</h2></span>"); if (prevButton) { prevButton.addClass(tm + '-corner-right'); } prevButton = null; }else{ var buttonClick; if (calendar[buttonName]) { buttonClick = calendar[buttonName]; // calendar method } else if (fcViews[buttonName]) { buttonClick = function() { button.removeClass(tm + '-state-hover'); // forget why calendar.changeView(buttonName); }; } if (buttonClick) { var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null; // why are we using smartProperty here? var text = smartProperty(options.buttonText, buttonName); // why are we using smartProperty here? var button = $( "<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" + "<span class='fc-button-inner'>" + "<span class='fc-button-content'>" + (icon ? "<span class='fc-icon-wrap'>" + "<span class='ui-icon ui-icon-" + icon + "'/>" + "</span>" : text ) + "</span>" + "<span class='fc-button-effect'><span></span></span>" + "</span>" + "</span>" ); if (button) { button .click(function() { if (!button.hasClass(tm + '-state-disabled')) { buttonClick(); } }) .mousedown(function() { button .not('.' + tm + '-state-active') .not('.' + tm + '-state-disabled') .addClass(tm + '-state-down'); }) .mouseup(function() { button.removeClass(tm + '-state-down'); }) .hover( function() { button .not('.' + tm + '-state-active') .not('.' + tm + '-state-disabled') .addClass(tm + '-state-hover'); }, function() { button .removeClass(tm + '-state-hover') .removeClass(tm + '-state-down'); } ) .appendTo(e); if (!prevButton) { button.addClass(tm + '-corner-left'); } prevButton = button; } } } }); if (prevButton) { prevButton.addClass(tm + '-corner-right'); } }); } return e; } function updateTitle(html) { element.find('h2') .html(html); } function activateButton(buttonName) { element.find('span.fc-button-' + buttonName) .addClass(tm + '-state-active'); } function deactivateButton(buttonName) { element.find('span.fc-button-' + buttonName) .removeClass(tm + '-state-active'); } function disableButton(buttonName) { element.find('span.fc-button-' + buttonName) .addClass(tm + '-state-disabled'); } function enableButton(buttonName) { element.find('span.fc-button-' + buttonName) .removeClass(tm + '-state-disabled'); } } fc.sourceNormalizers = []; fc.sourceFetchers = []; var ajaxDefaults = { dataType: 'json', cache: false }; var eventGUID = 1; function EventManager(options, _sources) { var t = this; // exports t.isFetchNeeded = isFetchNeeded; t.fetchEvents = fetchEvents; t.addEventSource = addEventSource; t.removeEventSource = removeEventSource; t.updateEvent = updateEvent; t.renderEvent = renderEvent; t.removeEvents = removeEvents; t.clientEvents = clientEvents; t.normalizeEvent = normalizeEvent; // imports var trigger = t.trigger; var getView = t.getView; var reportEvents = t.reportEvents; // locals var stickySource = { events: [] }; var sources = [ stickySource ]; var rangeStart, rangeEnd; var currentFetchID = 0; var pendingSourceCnt = 0; var loadingLevel = 0; var cache = []; for (var i=0; i<_sources.length; i++) { _addEventSource(_sources[i]); } /* Fetching -----------------------------------------------------------------------------*/ function isFetchNeeded(start, end) { return !rangeStart || start < rangeStart || end > rangeEnd; } function fetchEvents(start, end) { rangeStart = start; rangeEnd = end; cache = []; var fetchID = ++currentFetchID; var len = sources.length; pendingSourceCnt = len; for (var i=0; i<len; i++) { fetchEventSource(sources[i], fetchID); } } function fetchEventSource(source, fetchID) { _fetchEventSource(source, function(events) { if (fetchID == currentFetchID) { if (events) { for (var i=0; i<events.length; i++) { events[i].source = source; normalizeEvent(events[i]); } cache = cache.concat(events); } pendingSourceCnt--; if (!pendingSourceCnt) { reportEvents(cache); } } }); } function _fetchEventSource(source, callback) { var i; var fetchers = fc.sourceFetchers; var res; for (i=0; i<fetchers.length; i++) { res = fetchers[i](source, rangeStart, rangeEnd, callback); if (res === true) { // the fetcher is in charge. made its own async request return; } else if (typeof res == 'object') { // the fetcher returned a new source. process it _fetchEventSource(res, callback); return; } } var events = source.events; if (events) { if ($.isFunction(events)) { pushLoading(); events(cloneDate(rangeStart), cloneDate(rangeEnd), function(events) { callback(events); popLoading(); }); } else if ($.isArray(events)) { callback(events); } else { callback(); } }else{ var url = source.url; if (url) { var success = source.success; var error = source.error; var complete = source.complete; var data = $.extend({}, source.data || {}); var startParam = firstDefined(source.startParam, options.startParam); var endParam = firstDefined(source.endParam, options.endParam); if (startParam) { data[startParam] = Math.round(+rangeStart / 1000); } if (endParam) { data[endParam] = Math.round(+rangeEnd / 1000); } pushLoading(); $.ajax($.extend({}, ajaxDefaults, source, { data: data, success: function(events) { events = events || []; var res = applyAll(success, this, arguments); if ($.isArray(res)) { events = res; } callback(events); }, error: function() { applyAll(error, this, arguments); callback(); }, complete: function() { applyAll(complete, this, arguments); popLoading(); } })); }else{ callback(); } } } /* Sources -----------------------------------------------------------------------------*/ function addEventSource(source) { source = _addEventSource(source); if (source) { pendingSourceCnt++; fetchEventSource(source, currentFetchID); // will eventually call reportEvents } } function _addEventSource(source) { if ($.isFunction(source) || $.isArray(source)) { source = { events: source }; } else if (typeof source == 'string') { source = { url: source }; } if (typeof source == 'object') { normalizeSource(source); sources.push(source); return source; } } function removeEventSource(source) { sources = $.grep(sources, function(src) { return !isSourcesEqual(src, source); }); // remove all client events from that source cache = $.grep(cache, function(e) { return !isSourcesEqual(e.source, source); }); reportEvents(cache); } /* Manipulation -----------------------------------------------------------------------------*/ function updateEvent(event) { // update an existing event var i, len = cache.length, e, defaultEventEnd = getView().defaultEventEnd, // getView??? startDelta = event.start - event._start, endDelta = event.end ? (event.end - (event._end || defaultEventEnd(event))) // event._end would be null if event.end : 0; // was null and event was just resized for (i=0; i<len; i++) { e = cache[i]; if (e._id == event._id && e != event) { e.start = new Date(+e.start + startDelta); if (event.end) { if (e.end) { e.end = new Date(+e.end + endDelta); }else{ e.end = new Date(+defaultEventEnd(e) + endDelta); } }else{ e.end = null; } e.title = event.title; e.url = event.url; e.allDay = event.allDay; e.className = event.className; e.editable = event.editable; e.color = event.color; e.backgroudColor = event.backgroudColor; e.borderColor = event.borderColor; e.textColor = event.textColor; normalizeEvent(e); } } normalizeEvent(event); reportEvents(cache); } function renderEvent(event, stick) { normalizeEvent(event); if (!event.source) { if (stick) { stickySource.events.push(event); event.source = stickySource; } cache.push(event); } reportEvents(cache); } function removeEvents(filter) { if (!filter) { // remove all cache = []; // clear all array sources for (var i=0; i<sources.length; i++) { if ($.isArray(sources[i].events)) { sources[i].events = []; } } }else{ if (!$.isFunction(filter)) { // an event ID var id = filter + ''; filter = function(e) { return e._id == id; }; } cache = $.grep(cache, filter, true); // remove events from array sources for (var i=0; i<sources.length; i++) { if ($.isArray(sources[i].events)) { sources[i].events = $.grep(sources[i].events, filter, true); } } } reportEvents(cache); } function clientEvents(filter) { if ($.isFunction(filter)) { return $.grep(cache, filter); } else if (filter) { // an event ID filter += ''; return $.grep(cache, function(e) { return e._id == filter; }); } return cache; // else, return all } /* Loading State -----------------------------------------------------------------------------*/ function pushLoading() { if (!loadingLevel++) { trigger('loading', null, true); } } function popLoading() { if (!--loadingLevel) { trigger('loading', null, false); } } /* Event Normalization -----------------------------------------------------------------------------*/ function normalizeEvent(event) { var source = event.source || {}; var ignoreTimezone = firstDefined(source.ignoreTimezone, options.ignoreTimezone); event._id = event._id || (event.id === undefined ? '_fc' + eventGUID++ : event.id + ''); if (event.date) { if (!event.start) { event.start = event.date; } delete event.date; } event._start = cloneDate(event.start = parseDate(event.start, ignoreTimezone)); event.end = parseDate(event.end, ignoreTimezone); if (event.end && event.end <= event.start) { event.end = null; } event._end = event.end ? cloneDate(event.end) : null; if (event.allDay === undefined) { event.allDay = firstDefined(source.allDayDefault, options.allDayDefault); } if (event.className) { if (typeof event.className == 'string') { event.className = event.className.split(/\s+/); } }else{ event.className = []; } // TODO: if there is no start date, return false to indicate an invalid event } /* Utils ------------------------------------------------------------------------------*/ function normalizeSource(source) { if (source.className) { // TODO: repeat code, same code for event classNames if (typeof source.className == 'string') { source.className = source.className.split(/\s+/); } }else{ source.className = []; } var normalizers = fc.sourceNormalizers; for (var i=0; i<normalizers.length; i++) { normalizers[i](source); } } function isSourcesEqual(source1, source2) { return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2); } function getSourcePrimitive(source) { return ((typeof source == 'object') ? (source.events || source.url) : '') || source; } } fc.addDays = addDays; fc.cloneDate = cloneDate; fc.parseDate = parseDate; fc.parseISO8601 = parseISO8601; fc.parseTime = parseTime; fc.formatDate = formatDate; fc.formatDates = formatDates; /* Date Math -----------------------------------------------------------------------------*/ var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'], DAY_MS = 86400000, HOUR_MS = 3600000, MINUTE_MS = 60000; function addYears(d, n, keepTime) { d.setFullYear(d.getFullYear() + n); if (!keepTime) { clearTime(d); } return d; } function addMonths(d, n, keepTime) { // prevents day overflow/underflow if (+d) { // prevent infinite looping on invalid dates var m = d.getMonth() + n, check = cloneDate(d); check.setDate(1); check.setMonth(m); d.setMonth(m); if (!keepTime) { clearTime(d); } while (d.getMonth() != check.getMonth()) { d.setDate(d.getDate() + (d < check ? 1 : -1)); } } return d; } function addDays(d, n, keepTime) { // deals with daylight savings if (+d) { var dd = d.getDate() + n, check = cloneDate(d); check.setHours(9); // set to middle of day check.setDate(dd); d.setDate(dd); if (!keepTime) { clearTime(d); } fixDate(d, check); } return d; } function fixDate(d, check) { // force d to be on check's YMD, for daylight savings purposes if (+d) { // prevent infinite looping on invalid dates while (d.getDate() != check.getDate()) { d.setTime(+d + (d < check ? 1 : -1) * HOUR_MS); } } } function addMinutes(d, n) { d.setMinutes(d.getMinutes() + n); return d; } function clearTime(d) { d.setHours(0); d.setMinutes(0); d.setSeconds(0); d.setMilliseconds(0); return d; } function cloneDate(d, dontKeepTime) { if (dontKeepTime) { return clearTime(new Date(+d)); } return new Date(+d); } function zeroDate() { // returns a Date with time 00:00:00 and dateOfMonth=1 var i=0, d; do { d = new Date(1970, i++, 1); } while (d.getHours()); // != 0 return d; } function skipWeekend(date, inc, excl) { inc = inc || 1; while (!date.getDay() || (excl && date.getDay()==1 || !excl && date.getDay()==6)) { addDays(date, inc); } return date; } function dayDiff(d1, d2) { // d1 - d2 return Math.round((cloneDate(d1, true) - cloneDate(d2, true)) / DAY_MS); } function setYMD(date, y, m, d) { if (y !== undefined && y != date.getFullYear()) { date.setDate(1); date.setMonth(0); date.setFullYear(y); } if (m !== undefined && m != date.getMonth()) { date.setDate(1); date.setMonth(m); } if (d !== undefined) { date.setDate(d); } } /* Date Parsing -----------------------------------------------------------------------------*/ function parseDate(s, ignoreTimezone) { // ignoreTimezone defaults to true if (typeof s == 'object') { // already a Date object return s; } if (typeof s == 'number') { // a UNIX timestamp return new Date(s * 1000); } if (typeof s == 'string') { if (s.match(/^\d+(\.\d+)?$/)) { // a UNIX timestamp return new Date(parseFloat(s) * 1000); } if (ignoreTimezone === undefined) { ignoreTimezone = true; } return parseISO8601(s, ignoreTimezone) || (s ? new Date(s) : null); } // TODO: never return invalid dates (like from new Date(<string>)), return null instead return null; } function parseISO8601(s, ignoreTimezone) { // ignoreTimezone defaults to false // derived from http://delete.me.uk/2005/03/iso8601.html // TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html var m = s.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/); if (!m) { return null; } var date = new Date(m[1], 0, 1); if (ignoreTimezone || !m[14]) { var check = new Date(m[1], 0, 1, 9, 0); if (m[3]) { date.setMonth(m[3] - 1); check.setMonth(m[3] - 1); } if (m[5]) { date.setDate(m[5]); check.setDate(m[5]); } fixDate(date, check); if (m[7]) { date.setHours(m[7]); } if (m[8]) { date.setMinutes(m[8]); } if (m[10]) { date.setSeconds(m[10]); } if (m[12]) { date.setMilliseconds(Number("0." + m[12]) * 1000); } fixDate(date, check); }else{ date.setUTCFullYear( m[1], m[3] ? m[3] - 1 : 0, m[5] || 1 ); date.setUTCHours( m[7] || 0, m[8] || 0, m[10] || 0, m[12] ? Number("0." + m[12]) * 1000 : 0 ); var offset = Number(m[16]) * 60 + (m[18] ? Number(m[18]) : 0); offset *= m[15] == '-' ? 1 : -1; date = new Date(+date + (offset * 60 * 1000)); } return date; } function parseTime(s) { // returns minutes since start of day if (typeof s == 'number') { // an hour return s * 60; } if (typeof s == 'object') { // a Date object return s.getHours() * 60 + s.getMinutes(); } var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/); if (m) { var h = parseInt(m[1], 10); if (m[3]) { h %= 12; if (m[3].toLowerCase().charAt(0) == 'p') { h += 12; } } return h * 60 + (m[2] ? parseInt(m[2], 10) : 0); } } /* Date Formatting -----------------------------------------------------------------------------*/ // TODO: use same function formatDate(date, [date2], format, [options]) function formatDate(date, format, options) { return formatDates(date, null, format, options); } function formatDates(date1, date2, format, options) { options = options || defaults; var date = date1, otherDate = date2, i, len = format.length, c, i2, formatter, res = ''; for (i=0; i<len; i++) { c = format.charAt(i); if (c == "'") { for (i2=i+1; i2<len; i2++) { if (format.charAt(i2) == "'") { if (date) { if (i2 == i+1) { res += "'"; }else{ res += format.substring(i+1, i2); } i = i2; } break; } } } else if (c == '(') { for (i2=i+1; i2<len; i2++) { if (format.charAt(i2) == ')') { var subres = formatDate(date, format.substring(i+1, i2), options); if (parseInt(subres.replace(/\D/, ''), 10)) { res += subres; } i = i2; break; } } } else if (c == '[') { for (i2=i+1; i2<len; i2++) { if (format.charAt(i2) == ']') { var subformat = format.substring(i+1, i2); var subres = formatDate(date, subformat, options); if (subres != formatDate(otherDate, subformat, options)) { res += subres; } i = i2; break; } } } else if (c == '{') { date = date2; otherDate = date1; } else if (c == '}') { date = date1; otherDate = date2; } else { for (i2=len; i2>i; i2--) { if (formatter = dateFormatters[format.substring(i, i2)]) { if (date) { res += formatter(date, options); } i = i2 - 1; break; } } if (i2 == i) { if (date) { res += c; } } } } return res; }; var dateFormatters = { s : function(d) { return d.getSeconds() }, ss : function(d) { return zeroPad(d.getSeconds()) }, m : function(d) { return d.getMinutes() }, mm : function(d) { return zeroPad(d.getMinutes()) }, h : function(d) { return d.getHours() % 12 || 12 }, hh : function(d) { return zeroPad(d.getHours() % 12 || 12) }, H : function(d) { return d.getHours() }, HH : function(d) { return zeroPad(d.getHours()) }, d : function(d) { return d.getDate() }, dd : function(d) { return zeroPad(d.getDate()) }, ddd : function(d,o) { return o.dayNamesShort[d.getDay()] }, dddd: function(d,o) { return o.dayNames[d.getDay()] }, M : function(d) { return d.getMonth() + 1 }, MM : function(d) { return zeroPad(d.getMonth() + 1) }, MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] }, MMMM: function(d,o) { return o.monthNames[d.getMonth()] }, yy : function(d) { return (d.getFullYear()+'').substring(2) }, yyyy: function(d) { return d.getFullYear() }, t : function(d) { return d.getHours() < 12 ? 'a' : 'p' }, tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' }, T : function(d) { return d.getHours() < 12 ? 'A' : 'P' }, TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' }, u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") }, S : function(d) { var date = d.getDate(); if (date > 10 && date < 20) { return 'th'; } return ['st', 'nd', 'rd'][date%10-1] || 'th'; } }; fc.applyAll = applyAll; /* Event Date Math -----------------------------------------------------------------------------*/ function exclEndDay(event) { if (event.end) { return _exclEndDay(event.end, event.allDay); }else{ return addDays(cloneDate(event.start), 1); } } function _exclEndDay(end, allDay) { end = cloneDate(end); return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end); } function segCmp(a, b) { return (b.msLength - a.msLength) * 100 + (a.event.start - b.event.start); } function segsCollide(seg1, seg2) { return seg1.end > seg2.start && seg1.start < seg2.end; } /* Event Sorting -----------------------------------------------------------------------------*/ // event rendering utilities function sliceSegs(events, visEventEnds, start, end) { var segs = [], i, len=events.length, event, eventStart, eventEnd, segStart, segEnd, isStart, isEnd; for (i=0; i<len; i++) { event = events[i]; eventStart = event.start; eventEnd = visEventEnds[i]; if (eventEnd > start && eventStart < end) { if (eventStart < start) { segStart = cloneDate(start); isStart = false; }else{ segStart = eventStart; isStart = true; } if (eventEnd > end) { segEnd = cloneDate(end); isEnd = false; }else{ segEnd = eventEnd; isEnd = true; } segs.push({ event: event, start: segStart, end: segEnd, isStart: isStart, isEnd: isEnd, msLength: segEnd - segStart }); } } return segs.sort(segCmp); } // event rendering calculation utilities function stackSegs(segs) { var levels = [], i, len = segs.length, seg, j, collide, k; for (i=0; i<len; i++) { seg = segs[i]; j = 0; // the level index where seg should belong while (true) { collide = false; if (levels[j]) { for (k=0; k<levels[j].length; k++) { if (segsCollide(levels[j][k], seg)) { collide = true; break; } } } if (collide) { j++; }else{ break; } } if (levels[j]) { levels[j].push(seg); }else{ levels[j] = [seg]; } } return levels; } /* Event Element Binding -----------------------------------------------------------------------------*/ function lazySegBind(container, segs, bindHandlers) { container.unbind('mouseover').mouseover(function(ev) { var parent=ev.target, e, i, seg; while (parent != this) { e = parent; parent = parent.parentNode; } if ((i = e._fci) !== undefined) { e._fci = undefined; seg = segs[i]; bindHandlers(seg.event, seg.element, seg); $(ev.target).trigger(ev); } ev.stopPropagation(); }); } /* Element Dimensions -----------------------------------------------------------------------------*/ function setOuterWidth(element, width, includeMargins) { for (var i=0, e; i<element.length; i++) { e = $(element[i]); e.width(Math.max(0, width - hsides(e, includeMargins))); } } function setOuterHeight(element, height, includeMargins) { for (var i=0, e; i<element.length; i++) { e = $(element[i]); e.height(Math.max(0, height - vsides(e, includeMargins))); } } function hsides(element, includeMargins) { return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0); } function hpadding(element) { return (parseFloat($.css(element[0], 'paddingLeft', true)) || 0) + (parseFloat($.css(element[0], 'paddingRight', true)) || 0); } function hmargins(element) { return (parseFloat($.css(element[0], 'marginLeft', true)) || 0) + (parseFloat($.css(element[0], 'marginRight', true)) || 0); } function hborders(element) { return (parseFloat($.css(element[0], 'borderLeftWidth', true)) || 0) + (parseFloat($.css(element[0], 'borderRightWidth', true)) || 0); } function vsides(element, includeMargins) { return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0); } function vpadding(element) { return (parseFloat($.css(element[0], 'paddingTop', true)) || 0) + (parseFloat($.css(element[0], 'paddingBottom', true)) || 0); } function vmargins(element) { return (parseFloat($.css(element[0], 'marginTop', true)) || 0) + (parseFloat($.css(element[0], 'marginBottom', true)) || 0); } function vborders(element) { return (parseFloat($.css(element[0], 'borderTopWidth', true)) || 0) + (parseFloat($.css(element[0], 'borderBottomWidth', true)) || 0); } function setMinHeight(element, height) { height = (typeof height == 'number' ? height + 'px' : height); element.each(function(i, _element) { _element.style.cssText += ';min-height:' + height + ';_height:' + height; // why can't we just use .css() ? i forget }); } /* Misc Utils -----------------------------------------------------------------------------*/ //TODO: arraySlice //TODO: isFunction, grep ? function noop() { } function cmp(a, b) { return a - b; } function arrayMax(a) { return Math.max.apply(Math, a); } function zeroPad(n) { return (n < 10 ? '0' : '') + n; } function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object if (obj[name] !== undefined) { return obj[name]; } var parts = name.split(/(?=[A-Z])/), i=parts.length-1, res; for (; i>=0; i--) { res = obj[parts[i].toLowerCase()]; if (res !== undefined) { return res; } } return obj['']; } function htmlEscape(s) { return s.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/'/g, '&#039;') .replace(/"/g, '&quot;') .replace(/\n/g, '<br />'); } function cssKey(_element) { return _element.id + '/' + _element.className + '/' + _element.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig, ''); } function disableTextSelection(element) { element .attr('unselectable', 'on') .css('MozUserSelect', 'none') .bind('selectstart.ui', function() { return false; }); } /* function enableTextSelection(element) { element .attr('unselectable', 'off') .css('MozUserSelect', '') .unbind('selectstart.ui'); } */ function markFirstLast(e) { e.children() .removeClass('fc-first fc-last') .filter(':first-child') .addClass('fc-first') .end() .filter(':last-child') .addClass('fc-last'); } function setDayID(cell, date) { cell.each(function(i, _cell) { _cell.className = _cell.className.replace(/^fc-\w*/, 'fc-' + dayIDs[date.getDay()]); // TODO: make a way that doesn't rely on order of classes }); } function getSkinCss(event, opt) { var source = event.source || {}; var eventColor = event.color; var sourceColor = source.color; var optionColor = opt('eventColor'); var backgroundColor = event.backgroundColor || eventColor || source.backgroundColor || sourceColor || opt('eventBackgroundColor') || optionColor; var borderColor = event.borderColor || eventColor || source.borderColor || sourceColor || opt('eventBorderColor') || optionColor; var textColor = event.textColor || source.textColor || opt('eventTextColor'); var statements = []; if (backgroundColor) { statements.push('background-color:' + backgroundColor); } if (borderColor) { statements.push('border-color:' + borderColor); } if (textColor) { statements.push('color:' + textColor); } return statements.join(';'); } function applyAll(functions, thisObj, args) { if ($.isFunction(functions)) { functions = [ functions ]; } if (functions) { var i; var ret; for (i=0; i<functions.length; i++) { ret = functions[i].apply(thisObj, args) || ret; } return ret; } } function firstDefined() { for (var i=0; i<arguments.length; i++) { if (arguments[i] !== undefined) { return arguments[i]; } } } fcViews.month = MonthView; function MonthView(element, calendar) { var t = this; // exports t.render = render; // imports BasicView.call(t, element, calendar, 'month'); var opt = t.opt; var renderBasic = t.renderBasic; var formatDate = calendar.formatDate; function render(date, delta) { if (delta) { addMonths(date, delta); date.setDate(1); } var start = cloneDate(date, true); start.setDate(1); var end = addMonths(cloneDate(start), 1); var visStart = cloneDate(start); var visEnd = cloneDate(end); var firstDay = opt('firstDay'); var nwe = opt('weekends') ? 0 : 1; if (nwe) { skipWeekend(visStart); skipWeekend(visEnd, -1, true); } addDays(visStart, -((visStart.getDay() - Math.max(firstDay, nwe) + 7) % 7)); addDays(visEnd, (7 - visEnd.getDay() + Math.max(firstDay, nwe)) % 7); var rowCnt = Math.round((visEnd - visStart) / (DAY_MS * 7)); if (opt('weekMode') == 'fixed') { addDays(visEnd, (6 - rowCnt) * 7); rowCnt = 6; } t.title = formatDate(start, opt('titleFormat')); t.start = start; t.end = end; t.visStart = visStart; t.visEnd = visEnd; renderBasic(6, rowCnt, nwe ? 5 : 7, true); } } fcViews.basicWeek = BasicWeekView; function BasicWeekView(element, calendar) { var t = this; // exports t.render = render; // imports BasicView.call(t, element, calendar, 'basicWeek'); var opt = t.opt; var renderBasic = t.renderBasic; var formatDates = calendar.formatDates; function render(date, delta) { if (delta) { addDays(date, delta * 7); } var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7)); var end = addDays(cloneDate(start), 7); var visStart = cloneDate(start); var visEnd = cloneDate(end); var weekends = opt('weekends'); if (!weekends) { skipWeekend(visStart); skipWeekend(visEnd, -1, true); } t.title = formatDates( visStart, addDays(cloneDate(visEnd), -1), opt('titleFormat') ); t.start = start; t.end = end; t.visStart = visStart; t.visEnd = visEnd; renderBasic(1, 1, weekends ? 7 : 5, false); } } fcViews.basicDay = BasicDayView; //TODO: when calendar's date starts out on a weekend, shouldn't happen function BasicDayView(element, calendar) { var t = this; // exports t.render = render; // imports BasicView.call(t, element, calendar, 'basicDay'); var opt = t.opt; var renderBasic = t.renderBasic; var formatDate = calendar.formatDate; function render(date, delta) { if (delta) { addDays(date, delta); if (!opt('weekends')) { skipWeekend(date, delta < 0 ? -1 : 1); } } t.title = formatDate(date, opt('titleFormat')); t.start = t.visStart = cloneDate(date, true); t.end = t.visEnd = addDays(cloneDate(t.start), 1); renderBasic(1, 1, 1, false); } } setDefaults({ weekMode: 'fixed' }); function BasicView(element, calendar, viewName) { var t = this; // exports t.renderBasic = renderBasic; t.setHeight = setHeight; t.setWidth = setWidth; t.renderDayOverlay = renderDayOverlay; t.defaultSelectionEnd = defaultSelectionEnd; t.renderSelection = renderSelection; t.clearSelection = clearSelection; t.reportDayClick = reportDayClick; // for selection (kinda hacky) t.dragStart = dragStart; t.dragStop = dragStop; t.defaultEventEnd = defaultEventEnd; t.getHoverListener = function() { return hoverListener }; t.colContentLeft = colContentLeft; t.colContentRight = colContentRight; t.dayOfWeekCol = dayOfWeekCol; t.dateCell = dateCell; t.cellDate = cellDate; t.cellIsAllDay = function() { return true }; t.allDayRow = allDayRow; t.allDayBounds = allDayBounds; t.getRowCnt = function() { return rowCnt }; t.getColCnt = function() { return colCnt }; t.getColWidth = function() { return colWidth }; t.getDaySegmentContainer = function() { return daySegmentContainer }; // imports View.call(t, element, calendar, viewName); OverlayManager.call(t); SelectionManager.call(t); BasicEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; var clearEvents = t.clearEvents; var renderOverlay = t.renderOverlay; var clearOverlays = t.clearOverlays; var daySelectionMousedown = t.daySelectionMousedown; var formatDate = calendar.formatDate; // locals var head; var headCells; var body; var bodyRows; var bodyCells; var bodyFirstCells; var bodyCellTopInners; var daySegmentContainer; var viewWidth; var viewHeight; var colWidth; var rowCnt, colCnt; var coordinateGrid; var hoverListener; var colContentPositions; var rtl, dis, dit; var firstDay; var nwe; var tm; var colFormat; /* Rendering ------------------------------------------------------------*/ disableTextSelection(element.addClass('fc-grid')); function renderBasic(maxr, r, c, showNumbers) { rowCnt = r; colCnt = c; updateOptions(); var firstTime = !body; if (firstTime) { buildSkeleton(maxr, showNumbers); }else{ clearEvents(); } updateCells(firstTime); } function updateOptions() { rtl = opt('isRTL'); if (rtl) { dis = -1; dit = colCnt - 1; }else{ dis = 1; dit = 0; } firstDay = opt('firstDay'); nwe = opt('weekends') ? 0 : 1; tm = opt('theme') ? 'ui' : 'fc'; colFormat = opt('columnFormat'); } function buildSkeleton(maxRowCnt, showNumbers) { var s; var headerClass = tm + "-widget-header"; var contentClass = tm + "-widget-content"; var i, j; var table; s = "<table class='fc-border-separate' style='width:100%' cellspacing='0'>" + "<thead>" + "<tr>"; for (i=0; i<colCnt; i++) { s += "<th class='fc- " + headerClass + "'/>"; // need fc- for setDayID } s += "</tr>" + "</thead>" + "<tbody>"; for (i=0; i<maxRowCnt; i++) { s += "<tr class='fc-week" + i + "'>"; for (j=0; j<colCnt; j++) { s += "<td class='fc- " + contentClass + " fc-day" + (i*colCnt+j) + "'>" + // need fc- for setDayID "<div>" + (showNumbers ? "<div class='fc-day-number'/>" : '' ) + "<div class='fc-day-content'>" + "<div style='position:relative'>&nbsp;</div>" + "</div>" + "</div>" + "</td>"; } s += "</tr>"; } s += "</tbody>" + "</table>"; table = $(s).appendTo(element); head = table.find('thead'); headCells = head.find('th'); body = table.find('tbody'); bodyRows = body.find('tr'); bodyCells = body.find('td'); bodyFirstCells = bodyCells.filter(':first-child'); bodyCellTopInners = bodyRows.eq(0).find('div.fc-day-content div'); markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's markFirstLast(bodyRows); // marks first+last td's bodyRows.eq(0).addClass('fc-first'); // fc-last is done in updateCells dayBind(bodyCells); daySegmentContainer = $("<div style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(element); } function updateCells(firstTime) { var dowDirty = firstTime || rowCnt == 1; // could the cells' day-of-weeks need updating? var month = t.start.getMonth(); var today = clearTime(new Date()); var cell; var date; var row; if (dowDirty) { headCells.each(function(i, _cell) { cell = $(_cell); date = indexDate(i); cell.html(formatDate(date, colFormat)); setDayID(cell, date); }); } bodyCells.each(function(i, _cell) { cell = $(_cell); date = indexDate(i); if (date.getMonth() == month) { cell.removeClass('fc-other-month'); }else{ cell.addClass('fc-other-month'); } if (+date == +today) { cell.addClass(tm + '-state-highlight fc-today'); }else{ cell.removeClass(tm + '-state-highlight fc-today'); } cell.find('div.fc-day-number').text(date.getDate()); if (dowDirty) { setDayID(cell, date); } }); bodyRows.each(function(i, _row) { row = $(_row); if (i < rowCnt) { row.show(); if (i == rowCnt-1) { row.addClass('fc-last'); }else{ row.removeClass('fc-last'); } }else{ row.hide(); } }); } function setHeight(height) { viewHeight = height; var bodyHeight = viewHeight - head.height(); var rowHeight; var rowHeightLast; var cell; if (opt('weekMode') == 'variable') { rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6)); }else{ rowHeight = Math.floor(bodyHeight / rowCnt); rowHeightLast = bodyHeight - rowHeight * (rowCnt-1); } bodyFirstCells.each(function(i, _cell) { if (i < rowCnt) { cell = $(_cell); setMinHeight( cell.find('> div'), (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell) ); } }); } function setWidth(width) { viewWidth = width; colContentPositions.clear(); colWidth = Math.floor(viewWidth / colCnt); setOuterWidth(headCells.slice(0, -1), colWidth); } /* Day clicking and binding -----------------------------------------------------------*/ function dayBind(days) { days.click(dayClick) .mousedown(daySelectionMousedown); } function dayClick(ev) { if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick var index = parseInt(this.className.match(/fc\-day(\d+)/)[1]); // TODO: maybe use .data var date = indexDate(index); trigger('dayClick', this, date, true, ev); } } /* Semi-transparent Overlay Helpers ------------------------------------------------------*/ function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive if (refreshCoordinateGrid) { coordinateGrid.build(); } var rowStart = cloneDate(t.visStart); var rowEnd = addDays(cloneDate(rowStart), colCnt); for (var i=0; i<rowCnt; i++) { var stretchStart = new Date(Math.max(rowStart, overlayStart)); var stretchEnd = new Date(Math.min(rowEnd, overlayEnd)); if (stretchStart < stretchEnd) { var colStart, colEnd; if (rtl) { colStart = dayDiff(stretchEnd, rowStart)*dis+dit+1; colEnd = dayDiff(stretchStart, rowStart)*dis+dit+1; }else{ colStart = dayDiff(stretchStart, rowStart); colEnd = dayDiff(stretchEnd, rowStart); } dayBind( renderCellOverlay(i, colStart, i, colEnd-1) ); } addDays(rowStart, 7); addDays(rowEnd, 7); } } function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive var rect = coordinateGrid.rect(row0, col0, row1, col1, element); return renderOverlay(rect, element); } /* Selection -----------------------------------------------------------------------*/ function defaultSelectionEnd(startDate, allDay) { return cloneDate(startDate); } function renderSelection(startDate, endDate, allDay) { renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); // rebuild every time??? } function clearSelection() { clearOverlays(); } function reportDayClick(date, allDay, ev) { var cell = dateCell(date); var _element = bodyCells[cell.row*colCnt + cell.col]; trigger('dayClick', _element, date, allDay, ev); } /* External Dragging -----------------------------------------------------------------------*/ function dragStart(_dragElement, ev, ui) { hoverListener.start(function(cell) { clearOverlays(); if (cell) { renderCellOverlay(cell.row, cell.col, cell.row, cell.col); } }, ev); } function dragStop(_dragElement, ev, ui) { var cell = hoverListener.stop(); clearOverlays(); if (cell) { var d = cellDate(cell); trigger('drop', _dragElement, d, true, ev, ui); } } /* Utilities --------------------------------------------------------*/ function defaultEventEnd(event) { return cloneDate(event.start); } coordinateGrid = new CoordinateGrid(function(rows, cols) { var e, n, p; headCells.each(function(i, _e) { e = $(_e); n = e.offset().left; if (i) { p[1] = n; } p = [n]; cols[i] = p; }); p[1] = n + e.outerWidth(); bodyRows.each(function(i, _e) { if (i < rowCnt) { e = $(_e); n = e.offset().top; if (i) { p[1] = n; } p = [n]; rows[i] = p; } }); p[1] = n + e.outerHeight(); }); hoverListener = new HoverListener(coordinateGrid); colContentPositions = new HorizontalPositionCache(function(col) { return bodyCellTopInners.eq(col); }); function colContentLeft(col) { return colContentPositions.left(col); } function colContentRight(col) { return colContentPositions.right(col); } function dateCell(date) { return { row: Math.floor(dayDiff(date, t.visStart) / 7), col: dayOfWeekCol(date.getDay()) }; } function cellDate(cell) { return _cellDate(cell.row, cell.col); } function _cellDate(row, col) { return addDays(cloneDate(t.visStart), row*7 + col*dis+dit); // what about weekends in middle of week? } function indexDate(index) { return _cellDate(Math.floor(index/colCnt), index%colCnt); } function dayOfWeekCol(dayOfWeek) { return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt) * dis + dit; } function allDayRow(i) { return bodyRows.eq(i); } function allDayBounds(i) { return { left: 0, right: viewWidth }; } } function BasicEventRenderer() { var t = this; // exports t.renderEvents = renderEvents; t.compileDaySegs = compileSegs; // for DayEventRenderer t.clearEvents = clearEvents; t.bindDaySeg = bindDaySeg; // imports DayEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; //var setOverflowHidden = t.setOverflowHidden; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var reportEvents = t.reportEvents; var reportEventClear = t.reportEventClear; var eventElementHandlers = t.eventElementHandlers; var showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventDrop = t.eventDrop; var getDaySegmentContainer = t.getDaySegmentContainer; var getHoverListener = t.getHoverListener; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var getRowCnt = t.getRowCnt; var getColCnt = t.getColCnt; var renderDaySegs = t.renderDaySegs; var resizableDayEvent = t.resizableDayEvent; /* Rendering --------------------------------------------------------------------*/ function renderEvents(events, modifiedEventId) { reportEvents(events); renderDaySegs(compileSegs(events), modifiedEventId); } function clearEvents() { reportEventClear(); getDaySegmentContainer().empty(); } function compileSegs(events) { var rowCnt = getRowCnt(), colCnt = getColCnt(), d1 = cloneDate(t.visStart), d2 = addDays(cloneDate(d1), colCnt), visEventsEnds = $.map(events, exclEndDay), i, row, j, level, k, seg, segs=[]; for (i=0; i<rowCnt; i++) { row = stackSegs(sliceSegs(events, visEventsEnds, d1, d2)); for (j=0; j<row.length; j++) { level = row[j]; for (k=0; k<level.length; k++) { seg = level[k]; seg.row = i; seg.level = j; // not needed anymore segs.push(seg); } } addDays(d1, 7); addDays(d2, 7); } return segs; } function bindDaySeg(event, eventElement, seg) { if (isEventDraggable(event)) { draggableDayEvent(event, eventElement); } if (seg.isEnd && isEventResizable(event)) { resizableDayEvent(event, eventElement, seg); } eventElementHandlers(event, eventElement); // needs to be after, because resizableDayEvent might stopImmediatePropagation on click } /* Dragging ----------------------------------------------------------------------------*/ function draggableDayEvent(event, eventElement) { var hoverListener = getHoverListener(); var dayDelta; eventElement.draggable({ zIndex: 9, delay: 50, opacity: opt('dragOpacity'), revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); hoverListener.start(function(cell, origCell, rowDelta, colDelta) { eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta); clearOverlays(); if (cell) { //setOverflowHidden(true); dayDelta = rowDelta*7 + colDelta * (opt('isRTL') ? -1 : 1); renderDayOverlay( addDays(cloneDate(event.start), dayDelta), addDays(exclEndDay(event), dayDelta) ); }else{ //setOverflowHidden(false); dayDelta = 0; } }, ev, 'drag'); }, stop: function(ev, ui) { hoverListener.stop(); clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (dayDelta) { eventDrop(this, event, dayDelta, 0, event.allDay, ev, ui); }else{ eventElement.css('filter', ''); // clear IE opacity side-effects showEvents(event, eventElement); } //setOverflowHidden(false); } }); } } fcViews.agendaWeek = AgendaWeekView; function AgendaWeekView(element, calendar) { var t = this; // exports t.render = render; // imports AgendaView.call(t, element, calendar, 'agendaWeek'); var opt = t.opt; var renderAgenda = t.renderAgenda; var formatDates = calendar.formatDates; function render(date, delta) { if (delta) { addDays(date, delta * 7); } var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7)); var end = addDays(cloneDate(start), 7); var visStart = cloneDate(start); var visEnd = cloneDate(end); var weekends = opt('weekends'); if (!weekends) { skipWeekend(visStart); skipWeekend(visEnd, -1, true); } t.title = formatDates( visStart, addDays(cloneDate(visEnd), -1), opt('titleFormat') ); t.start = start; t.end = end; t.visStart = visStart; t.visEnd = visEnd; renderAgenda(weekends ? 7 : 5); } } fcViews.agendaDay = AgendaDayView; function AgendaDayView(element, calendar) { var t = this; // exports t.render = render; // imports AgendaView.call(t, element, calendar, 'agendaDay'); var opt = t.opt; var renderAgenda = t.renderAgenda; var formatDate = calendar.formatDate; function render(date, delta) { if (delta) { addDays(date, delta); if (!opt('weekends')) { skipWeekend(date, delta < 0 ? -1 : 1); } } var start = cloneDate(date, true); var end = addDays(cloneDate(start), 1); t.title = formatDate(date, opt('titleFormat')); t.start = t.visStart = start; t.end = t.visEnd = end; renderAgenda(1); } } setDefaults({ allDaySlot: true, allDayText: 'all-day', firstHour: 6, slotMinutes: 30, defaultEventMinutes: 120, axisFormat: 'h(:mm)tt', timeFormat: { agenda: 'h:mm{ - h:mm}' }, dragOpacity: { agenda: .5 }, minTime: 0, maxTime: 24 }); // TODO: make it work in quirks mode (event corners, all-day height) // TODO: test liquid width, especially in IE6 function AgendaView(element, calendar, viewName) { var t = this; // exports t.renderAgenda = renderAgenda; t.setWidth = setWidth; t.setHeight = setHeight; t.beforeHide = beforeHide; t.afterShow = afterShow; t.defaultEventEnd = defaultEventEnd; t.timePosition = timePosition; t.dayOfWeekCol = dayOfWeekCol; t.dateCell = dateCell; t.cellDate = cellDate; t.cellIsAllDay = cellIsAllDay; t.allDayRow = getAllDayRow; t.allDayBounds = allDayBounds; t.getHoverListener = function() { return hoverListener }; t.colContentLeft = colContentLeft; t.colContentRight = colContentRight; t.getDaySegmentContainer = function() { return daySegmentContainer }; t.getSlotSegmentContainer = function() { return slotSegmentContainer }; t.getMinMinute = function() { return minMinute }; t.getMaxMinute = function() { return maxMinute }; t.getBodyContent = function() { return slotContent }; // !!?? t.getRowCnt = function() { return 1 }; t.getColCnt = function() { return colCnt }; t.getColWidth = function() { return colWidth }; t.getSlotHeight = function() { return slotHeight }; t.defaultSelectionEnd = defaultSelectionEnd; t.renderDayOverlay = renderDayOverlay; t.renderSelection = renderSelection; t.clearSelection = clearSelection; t.reportDayClick = reportDayClick; // selection mousedown hack t.dragStart = dragStart; t.dragStop = dragStop; // imports View.call(t, element, calendar, viewName); OverlayManager.call(t); SelectionManager.call(t); AgendaEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; var clearEvents = t.clearEvents; var renderOverlay = t.renderOverlay; var clearOverlays = t.clearOverlays; var reportSelection = t.reportSelection; var unselect = t.unselect; var daySelectionMousedown = t.daySelectionMousedown; var slotSegHtml = t.slotSegHtml; var formatDate = calendar.formatDate; // locals var dayTable; var dayHead; var dayHeadCells; var dayBody; var dayBodyCells; var dayBodyCellInners; var dayBodyFirstCell; var dayBodyFirstCellStretcher; var slotLayer; var daySegmentContainer; var allDayTable; var allDayRow; var slotScroller; var slotContent; var slotSegmentContainer; var slotTable; var slotTableFirstInner; var axisFirstCells; var gutterCells; var selectionHelper; var viewWidth; var viewHeight; var axisWidth; var colWidth; var gutterWidth; var slotHeight; // TODO: what if slotHeight changes? (see issue 650) var savedScrollTop; var colCnt; var slotCnt; var coordinateGrid; var hoverListener; var colContentPositions; var slotTopCache = {}; var tm; var firstDay; var nwe; // no weekends (int) var rtl, dis, dit; // day index sign / translate var minMinute, maxMinute; var colFormat; /* Rendering -----------------------------------------------------------------------------*/ disableTextSelection(element.addClass('fc-agenda')); function renderAgenda(c) { colCnt = c; updateOptions(); if (!dayTable) { buildSkeleton(); }else{ clearEvents(); } updateCells(); } function updateOptions() { tm = opt('theme') ? 'ui' : 'fc'; nwe = opt('weekends') ? 0 : 1; firstDay = opt('firstDay'); if (rtl = opt('isRTL')) { dis = -1; dit = colCnt - 1; }else{ dis = 1; dit = 0; } minMinute = parseTime(opt('minTime')); maxMinute = parseTime(opt('maxTime')); colFormat = opt('columnFormat'); } function buildSkeleton() { var headerClass = tm + "-widget-header"; var contentClass = tm + "-widget-content"; var s; var i; var d; var maxd; var minutes; var slotNormal = opt('slotMinutes') % 15 == 0; s = "<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" + "<thead>" + "<tr>" + "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>"; for (i=0; i<colCnt; i++) { s += "<th class='fc- fc-col" + i + ' ' + headerClass + "'/>"; // fc- needed for setDayID } s += "<th class='fc-agenda-gutter " + headerClass + "'>&nbsp;</th>" + "</tr>" + "</thead>" + "<tbody>" + "<tr>" + "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>"; for (i=0; i<colCnt; i++) { s += "<td class='fc- fc-col" + i + ' ' + contentClass + "'>" + // fc- needed for setDayID "<div>" + "<div class='fc-day-content'>" + "<div style='position:relative'>&nbsp;</div>" + "</div>" + "</div>" + "</td>"; } s += "<td class='fc-agenda-gutter " + contentClass + "'>&nbsp;</td>" + "</tr>" + "</tbody>" + "</table>"; dayTable = $(s).appendTo(element); dayHead = dayTable.find('thead'); dayHeadCells = dayHead.find('th').slice(1, -1); dayBody = dayTable.find('tbody'); dayBodyCells = dayBody.find('td').slice(0, -1); dayBodyCellInners = dayBodyCells.find('div.fc-day-content div'); dayBodyFirstCell = dayBodyCells.eq(0); dayBodyFirstCellStretcher = dayBodyFirstCell.find('> div'); markFirstLast(dayHead.add(dayHead.find('tr'))); markFirstLast(dayBody.add(dayBody.find('tr'))); axisFirstCells = dayHead.find('th:first'); gutterCells = dayTable.find('.fc-agenda-gutter'); slotLayer = $("<div style='position:absolute;z-index:2;left:0;width:100%'/>") .appendTo(element); if (opt('allDaySlot')) { daySegmentContainer = $("<div style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(slotLayer); s = "<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" + "<tr>" + "<th class='" + headerClass + " fc-agenda-axis'>" + opt('allDayText') + "</th>" + "<td>" + "<div class='fc-day-content'><div style='position:relative'/></div>" + "</td>" + "<th class='" + headerClass + " fc-agenda-gutter'>&nbsp;</th>" + "</tr>" + "</table>"; allDayTable = $(s).appendTo(slotLayer); allDayRow = allDayTable.find('tr'); dayBind(allDayRow.find('td')); axisFirstCells = axisFirstCells.add(allDayTable.find('th:first')); gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter')); slotLayer.append( "<div class='fc-agenda-divider " + headerClass + "'>" + "<div class='fc-agenda-divider-inner'/>" + "</div>" ); }else{ daySegmentContainer = $([]); // in jQuery 1.4, we can just do $() } slotScroller = $("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>") .appendTo(slotLayer); slotContent = $("<div style='position:relative;width:100%;overflow:hidden'/>") .appendTo(slotScroller); slotSegmentContainer = $("<div style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(slotContent); s = "<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" + "<tbody>"; d = zeroDate(); maxd = addMinutes(cloneDate(d), maxMinute); addMinutes(d, minMinute); slotCnt = 0; for (i=0; d < maxd; i++) { minutes = d.getMinutes(); s += "<tr class='fc-slot" + i + ' ' + (!minutes ? '' : 'fc-minor') + "'>" + "<th class='fc-agenda-axis " + headerClass + "'>" + ((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : '&nbsp;') + "</th>" + "<td class='" + contentClass + "'>" + "<div style='position:relative'>&nbsp;</div>" + "</td>" + "</tr>"; addMinutes(d, opt('slotMinutes')); slotCnt++; } s += "</tbody>" + "</table>"; slotTable = $(s).appendTo(slotContent); slotTableFirstInner = slotTable.find('div:first'); slotBind(slotTable.find('td')); axisFirstCells = axisFirstCells.add(slotTable.find('th:first')); } function updateCells() { var i; var headCell; var bodyCell; var date; var today = clearTime(new Date()); for (i=0; i<colCnt; i++) { date = colDate(i); headCell = dayHeadCells.eq(i); headCell.html(formatDate(date, colFormat)); bodyCell = dayBodyCells.eq(i); if (+date == +today) { bodyCell.addClass(tm + '-state-highlight fc-today'); }else{ bodyCell.removeClass(tm + '-state-highlight fc-today'); } setDayID(headCell.add(bodyCell), date); } } function setHeight(height, dateChanged) { if (height === undefined) { height = viewHeight; } viewHeight = height; slotTopCache = {}; var headHeight = dayBody.position().top; var allDayHeight = slotScroller.position().top; // including divider var bodyHeight = Math.min( // total body height, including borders height - headHeight, // when scrollbars slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border ); dayBodyFirstCellStretcher .height(bodyHeight - vsides(dayBodyFirstCell)); slotLayer.css('top', headHeight); slotScroller.height(bodyHeight - allDayHeight - 1); slotHeight = slotTableFirstInner.height() + 1; // +1 for border if (dateChanged) { resetScroll(); } } function setWidth(width) { viewWidth = width; colContentPositions.clear(); axisWidth = 0; setOuterWidth( axisFirstCells .width('') .each(function(i, _cell) { axisWidth = Math.max(axisWidth, $(_cell).outerWidth()); }), axisWidth ); var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7) //slotTable.width(slotTableWidth); gutterWidth = slotScroller.width() - slotTableWidth; if (gutterWidth) { setOuterWidth(gutterCells, gutterWidth); gutterCells .show() .prev() .removeClass('fc-last'); }else{ gutterCells .hide() .prev() .addClass('fc-last'); } colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt); setOuterWidth(dayHeadCells.slice(0, -1), colWidth); } function resetScroll() { var d0 = zeroDate(); var scrollDate = cloneDate(d0); scrollDate.setHours(opt('firstHour')); var top = timePosition(d0, scrollDate) + 1; // +1 for the border function scroll() { slotScroller.scrollTop(top); } scroll(); setTimeout(scroll, 0); // overrides any previous scroll state made by the browser } function beforeHide() { savedScrollTop = slotScroller.scrollTop(); } function afterShow() { slotScroller.scrollTop(savedScrollTop); } /* Slot/Day clicking and binding -----------------------------------------------------------------------*/ function dayBind(cells) { cells.click(slotClick) .mousedown(daySelectionMousedown); } function slotBind(cells) { cells.click(slotClick) .mousedown(slotSelectionMousedown); } function slotClick(ev) { if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth)); var date = colDate(col); var rowMatch = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data if (rowMatch) { var mins = parseInt(rowMatch[1]) * opt('slotMinutes'); var hours = Math.floor(mins/60); date.setHours(hours); date.setMinutes(mins%60 + minMinute); trigger('dayClick', dayBodyCells[col], date, false, ev); }else{ trigger('dayClick', dayBodyCells[col], date, true, ev); } } } /* Semi-transparent Overlay Helpers -----------------------------------------------------*/ function renderDayOverlay(startDate, endDate, refreshCoordinateGrid) { // endDate is exclusive if (refreshCoordinateGrid) { coordinateGrid.build(); } var visStart = cloneDate(t.visStart); var startCol, endCol; if (rtl) { startCol = dayDiff(endDate, visStart)*dis+dit+1; endCol = dayDiff(startDate, visStart)*dis+dit+1; }else{ startCol = dayDiff(startDate, visStart); endCol = dayDiff(endDate, visStart); } startCol = Math.max(0, startCol); endCol = Math.min(colCnt, endCol); if (startCol < endCol) { dayBind( renderCellOverlay(0, startCol, 0, endCol-1) ); } } function renderCellOverlay(row0, col0, row1, col1) { // only for all-day? var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer); return renderOverlay(rect, slotLayer); } function renderSlotOverlay(overlayStart, overlayEnd) { var dayStart = cloneDate(t.visStart); var dayEnd = addDays(cloneDate(dayStart), 1); for (var i=0; i<colCnt; i++) { var stretchStart = new Date(Math.max(dayStart, overlayStart)); var stretchEnd = new Date(Math.min(dayEnd, overlayEnd)); if (stretchStart < stretchEnd) { var col = i*dis+dit; var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only use it for horizontal coords var top = timePosition(dayStart, stretchStart); var bottom = timePosition(dayStart, stretchEnd); rect.top = top; rect.height = bottom - top; slotBind( renderOverlay(rect, slotContent) ); } addDays(dayStart, 1); addDays(dayEnd, 1); } } /* Coordinate Utilities -----------------------------------------------------------------------------*/ coordinateGrid = new CoordinateGrid(function(rows, cols) { var e, n, p; dayHeadCells.each(function(i, _e) { e = $(_e); n = e.offset().left; if (i) { p[1] = n; } p = [n]; cols[i] = p; }); p[1] = n + e.outerWidth(); if (opt('allDaySlot')) { e = allDayRow; n = e.offset().top; rows[0] = [n, n+e.outerHeight()]; } var slotTableTop = slotContent.offset().top; var slotScrollerTop = slotScroller.offset().top; var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight(); function constrain(n) { return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n)); } for (var i=0; i<slotCnt; i++) { rows.push([ constrain(slotTableTop + slotHeight*i), constrain(slotTableTop + slotHeight*(i+1)) ]); } }); hoverListener = new HoverListener(coordinateGrid); colContentPositions = new HorizontalPositionCache(function(col) { return dayBodyCellInners.eq(col); }); function colContentLeft(col) { return colContentPositions.left(col); } function colContentRight(col) { return colContentPositions.right(col); } function dateCell(date) { // "cell" terminology is now confusing return { row: Math.floor(dayDiff(date, t.visStart) / 7), col: dayOfWeekCol(date.getDay()) }; } function cellDate(cell) { var d = colDate(cell.col); var slotIndex = cell.row; if (opt('allDaySlot')) { slotIndex--; } if (slotIndex >= 0) { addMinutes(d, minMinute + slotIndex * opt('slotMinutes')); } return d; } function colDate(col) { // returns dates with 00:00:00 return addDays(cloneDate(t.visStart), col*dis+dit); } function cellIsAllDay(cell) { return opt('allDaySlot') && !cell.row; } function dayOfWeekCol(dayOfWeek) { return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt)*dis+dit; } // get the Y coordinate of the given time on the given day (both Date objects) function timePosition(day, time) { // both date objects. day holds 00:00 of current day day = cloneDate(day, true); if (time < addMinutes(cloneDate(day), minMinute)) { return 0; } if (time >= addMinutes(cloneDate(day), maxMinute)) { return slotTable.height(); } var slotMinutes = opt('slotMinutes'), minutes = time.getHours()*60 + time.getMinutes() - minMinute, slotI = Math.floor(minutes / slotMinutes), slotTop = slotTopCache[slotI]; if (slotTop === undefined) { slotTop = slotTopCache[slotI] = slotTable.find('tr:eq(' + slotI + ') td div')[0].offsetTop; //.position().top; // need this optimization??? } return Math.max(0, Math.round( slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes) )); } function allDayBounds() { return { left: axisWidth, right: viewWidth - gutterWidth } } function getAllDayRow(index) { return allDayRow; } function defaultEventEnd(event) { var start = cloneDate(event.start); if (event.allDay) { return start; } return addMinutes(start, opt('defaultEventMinutes')); } /* Selection ---------------------------------------------------------------------------------*/ function defaultSelectionEnd(startDate, allDay) { if (allDay) { return cloneDate(startDate); } return addMinutes(cloneDate(startDate), opt('slotMinutes')); } function renderSelection(startDate, endDate, allDay) { // only for all-day if (allDay) { if (opt('allDaySlot')) { renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); } }else{ renderSlotSelection(startDate, endDate); } } function renderSlotSelection(startDate, endDate) { var helperOption = opt('selectHelper'); coordinateGrid.build(); if (helperOption) { var col = dayDiff(startDate, t.visStart) * dis + dit; if (col >= 0 && col < colCnt) { // only works when times are on same day var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only for horizontal coords var top = timePosition(startDate, startDate); var bottom = timePosition(startDate, endDate); if (bottom > top) { // protect against selections that are entirely before or after visible range rect.top = top; rect.height = bottom - top; rect.left += 2; rect.width -= 5; if ($.isFunction(helperOption)) { var helperRes = helperOption(startDate, endDate); if (helperRes) { rect.position = 'absolute'; rect.zIndex = 8; selectionHelper = $(helperRes) .css(rect) .appendTo(slotContent); } }else{ rect.isStart = true; // conside rect a "seg" now rect.isEnd = true; // selectionHelper = $(slotSegHtml( { title: '', start: startDate, end: endDate, className: ['fc-select-helper'], editable: false }, rect )); selectionHelper.css('opacity', opt('dragOpacity')); } if (selectionHelper) { slotBind(selectionHelper); slotContent.append(selectionHelper); setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended setOuterHeight(selectionHelper, rect.height, true); } } } }else{ renderSlotOverlay(startDate, endDate); } } function clearSelection() { clearOverlays(); if (selectionHelper) { selectionHelper.remove(); selectionHelper = null; } } function slotSelectionMousedown(ev) { if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button unselect(ev); var dates; hoverListener.start(function(cell, origCell) { clearSelection(); if (cell && cell.col == origCell.col && !cellIsAllDay(cell)) { var d1 = cellDate(origCell); var d2 = cellDate(cell); dates = [ d1, addMinutes(cloneDate(d1), opt('slotMinutes')), d2, addMinutes(cloneDate(d2), opt('slotMinutes')) ].sort(cmp); renderSlotSelection(dates[0], dates[3]); }else{ dates = null; } }, ev); $(document).one('mouseup', function(ev) { hoverListener.stop(); if (dates) { if (+dates[0] == +dates[1]) { reportDayClick(dates[0], false, ev); } reportSelection(dates[0], dates[3], false, ev); } }); } } function reportDayClick(date, allDay, ev) { trigger('dayClick', dayBodyCells[dayOfWeekCol(date.getDay())], date, allDay, ev); } /* External Dragging --------------------------------------------------------------------------------*/ function dragStart(_dragElement, ev, ui) { hoverListener.start(function(cell) { clearOverlays(); if (cell) { if (cellIsAllDay(cell)) { renderCellOverlay(cell.row, cell.col, cell.row, cell.col); }else{ var d1 = cellDate(cell); var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes')); renderSlotOverlay(d1, d2); } } }, ev); } function dragStop(_dragElement, ev, ui) { var cell = hoverListener.stop(); clearOverlays(); if (cell) { trigger('drop', _dragElement, cellDate(cell), cellIsAllDay(cell), ev, ui); } } } function AgendaEventRenderer() { var t = this; // exports t.renderEvents = renderEvents; t.compileDaySegs = compileDaySegs; // for DayEventRenderer t.clearEvents = clearEvents; t.slotSegHtml = slotSegHtml; t.bindDaySeg = bindDaySeg; // imports DayEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; //var setOverflowHidden = t.setOverflowHidden; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var eventEnd = t.eventEnd; var reportEvents = t.reportEvents; var reportEventClear = t.reportEventClear; var eventElementHandlers = t.eventElementHandlers; var setHeight = t.setHeight; var getDaySegmentContainer = t.getDaySegmentContainer; var getSlotSegmentContainer = t.getSlotSegmentContainer; var getHoverListener = t.getHoverListener; var getMaxMinute = t.getMaxMinute; var getMinMinute = t.getMinMinute; var timePosition = t.timePosition; var colContentLeft = t.colContentLeft; var colContentRight = t.colContentRight; var renderDaySegs = t.renderDaySegs; var resizableDayEvent = t.resizableDayEvent; // TODO: streamline binding architecture var getColCnt = t.getColCnt; var getColWidth = t.getColWidth; var getSlotHeight = t.getSlotHeight; var getBodyContent = t.getBodyContent; var reportEventElement = t.reportEventElement; var showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventDrop = t.eventDrop; var eventResize = t.eventResize; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var calendar = t.calendar; var formatDate = calendar.formatDate; var formatDates = calendar.formatDates; /* Rendering ----------------------------------------------------------------------------*/ function renderEvents(events, modifiedEventId) { reportEvents(events); var i, len=events.length, dayEvents=[], slotEvents=[]; for (i=0; i<len; i++) { if (events[i].allDay) { dayEvents.push(events[i]); }else{ slotEvents.push(events[i]); } } if (opt('allDaySlot')) { renderDaySegs(compileDaySegs(dayEvents), modifiedEventId); setHeight(); // no params means set to viewHeight } renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId); } function clearEvents() { reportEventClear(); getDaySegmentContainer().empty(); getSlotSegmentContainer().empty(); } function compileDaySegs(events) { var levels = stackSegs(sliceSegs(events, $.map(events, exclEndDay), t.visStart, t.visEnd)), i, levelCnt=levels.length, level, j, seg, segs=[]; for (i=0; i<levelCnt; i++) { level = levels[i]; for (j=0; j<level.length; j++) { seg = level[j]; seg.row = 0; seg.level = i; // not needed anymore segs.push(seg); } } return segs; } function compileSlotSegs(events) { var colCnt = getColCnt(), minMinute = getMinMinute(), maxMinute = getMaxMinute(), d = addMinutes(cloneDate(t.visStart), minMinute), visEventEnds = $.map(events, slotEventEnd), i, col, j, level, k, seg, segs=[]; for (i=0; i<colCnt; i++) { col = stackSegs(sliceSegs(events, visEventEnds, d, addMinutes(cloneDate(d), maxMinute-minMinute))); countForwardSegs(col); for (j=0; j<col.length; j++) { level = col[j]; for (k=0; k<level.length; k++) { seg = level[k]; seg.col = i; seg.level = j; segs.push(seg); } } addDays(d, 1, true); } return segs; } function slotEventEnd(event) { if (event.end) { return cloneDate(event.end); }else{ return addMinutes(cloneDate(event.start), opt('defaultEventMinutes')); } } // renders events in the 'time slots' at the bottom function renderSlotSegs(segs, modifiedEventId) { var i, segCnt=segs.length, seg, event, classes, top, bottom, colI, levelI, forward, leftmost, availWidth, outerWidth, left, html='', eventElements, eventElement, triggerRes, vsideCache={}, hsideCache={}, key, val, contentElement, height, slotSegmentContainer = getSlotSegmentContainer(), rtl, dis, dit, colCnt = getColCnt(); if (rtl = opt('isRTL')) { dis = -1; dit = colCnt - 1; }else{ dis = 1; dit = 0; } // calculate position/dimensions, create html for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; top = timePosition(seg.start, seg.start); bottom = timePosition(seg.start, seg.end); colI = seg.col; levelI = seg.level; forward = seg.forward || 0; leftmost = colContentLeft(colI*dis + dit); availWidth = colContentRight(colI*dis + dit) - leftmost; availWidth = Math.min(availWidth-6, availWidth*.95); // TODO: move this to CSS if (levelI) { // indented and thin outerWidth = availWidth / (levelI + forward + 1); }else{ if (forward) { // moderately wide, aligned left still outerWidth = ((availWidth / (forward + 1)) - (12/2)) * 2; // 12 is the predicted width of resizer = }else{ // can be entire width, aligned left outerWidth = availWidth; } } left = leftmost + // leftmost possible (availWidth / (levelI + forward + 1) * levelI) // indentation * dis + (rtl ? availWidth - outerWidth : 0); // rtl seg.top = top; seg.left = left; seg.outerWidth = outerWidth; seg.outerHeight = bottom - top; html += slotSegHtml(event, seg); } slotSegmentContainer[0].innerHTML = html; // faster than html() eventElements = slotSegmentContainer.children(); // retrieve elements, run through eventRender callback, bind event handlers for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; eventElement = $(eventElements[i]); // faster than eq() triggerRes = trigger('eventRender', event, event, eventElement); if (triggerRes === false) { eventElement.remove(); }else{ if (triggerRes && triggerRes !== true) { eventElement.remove(); eventElement = $(triggerRes) .css({ position: 'absolute', top: seg.top, left: seg.left }) .appendTo(slotSegmentContainer); } seg.element = eventElement; if (event._id === modifiedEventId) { bindSlotSeg(event, eventElement, seg); }else{ eventElement[0]._fci = i; // for lazySegBind } reportEventElement(event, eventElement); } } lazySegBind(slotSegmentContainer, segs, bindSlotSeg); // record event sides and title positions for (i=0; i<segCnt; i++) { seg = segs[i]; if (eventElement = seg.element) { val = vsideCache[key = seg.key = cssKey(eventElement[0])]; seg.vsides = val === undefined ? (vsideCache[key] = vsides(eventElement, true)) : val; val = hsideCache[key]; seg.hsides = val === undefined ? (hsideCache[key] = hsides(eventElement, true)) : val; contentElement = eventElement.find('div.fc-event-content'); if (contentElement.length) { seg.contentTop = contentElement[0].offsetTop; } } } // set all positions/dimensions at once for (i=0; i<segCnt; i++) { seg = segs[i]; if (eventElement = seg.element) { eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px'; height = Math.max(0, seg.outerHeight - seg.vsides); eventElement[0].style.height = height + 'px'; event = seg.event; if (seg.contentTop !== undefined && height - seg.contentTop < 10) { // not enough room for title, put it in the time header eventElement.find('div.fc-event-time') .text(formatDate(event.start, opt('timeFormat')) + ' - ' + event.title); eventElement.find('div.fc-event-title') .remove(); } trigger('eventAfterRender', event, event, eventElement); } } } function slotSegHtml(event, seg) { var html = "<"; var url = event.url; var skinCss = getSkinCss(event, opt); var skinCssAttr = (skinCss ? " style='" + skinCss + "'" : ''); var classes = ['fc-event', 'fc-event-skin', 'fc-event-vert']; if (isEventDraggable(event)) { classes.push('fc-event-draggable'); } if (seg.isStart) { classes.push('fc-corner-top'); } if (seg.isEnd) { classes.push('fc-corner-bottom'); } classes = classes.concat(event.className); if (event.source) { classes = classes.concat(event.source.className || []); } if (url) { html += "a href='" + htmlEscape(event.url) + "'"; }else{ html += "div"; } html += " class='" + classes.join(' ') + "'" + " style='position:absolute;z-index:8;top:" + seg.top + "px;left:" + seg.left + "px;" + skinCss + "'" + ">" + "<div class='fc-event-inner fc-event-skin'" + skinCssAttr + ">" + "<div class='fc-event-head fc-event-skin'" + skinCssAttr + ">" + "<div class='fc-event-time'>" + htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + "</div>" + "</div>" + "<div class='fc-event-content'>" + "<div class='fc-event-title'>" + htmlEscape(event.title) + "</div>" + "</div>" + "<div class='fc-event-bg'></div>" + "</div>"; // close inner if (seg.isEnd && isEventResizable(event)) { html += "<div class='ui-resizable-handle ui-resizable-s'>=</div>"; } html += "</" + (url ? "a" : "div") + ">"; return html; } function bindDaySeg(event, eventElement, seg) { if (isEventDraggable(event)) { draggableDayEvent(event, eventElement, seg.isStart); } if (seg.isEnd && isEventResizable(event)) { resizableDayEvent(event, eventElement, seg); } eventElementHandlers(event, eventElement); // needs to be after, because resizableDayEvent might stopImmediatePropagation on click } function bindSlotSeg(event, eventElement, seg) { var timeElement = eventElement.find('div.fc-event-time'); if (isEventDraggable(event)) { draggableSlotEvent(event, eventElement, timeElement); } if (seg.isEnd && isEventResizable(event)) { resizableSlotEvent(event, eventElement, timeElement); } eventElementHandlers(event, eventElement); } /* Dragging -----------------------------------------------------------------------------------*/ // when event starts out FULL-DAY function draggableDayEvent(event, eventElement, isStart) { var origWidth; var revert; var allDay=true; var dayDelta; var dis = opt('isRTL') ? -1 : 1; var hoverListener = getHoverListener(); var colWidth = getColWidth(); var slotHeight = getSlotHeight(); var minMinute = getMinMinute(); eventElement.draggable({ zIndex: 9, opacity: opt('dragOpacity', 'month'), // use whatever the month view was using revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); origWidth = eventElement.width(); hoverListener.start(function(cell, origCell, rowDelta, colDelta) { clearOverlays(); if (cell) { //setOverflowHidden(true); revert = false; dayDelta = colDelta * dis; if (!cell.row) { // on full-days renderDayOverlay( addDays(cloneDate(event.start), dayDelta), addDays(exclEndDay(event), dayDelta) ); resetElement(); }else{ // mouse is over bottom slots if (isStart) { if (allDay) { // convert event to temporary slot-event eventElement.width(colWidth - 10); // don't use entire width setOuterHeight( eventElement, slotHeight * Math.round( (event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) / opt('slotMinutes') ) ); eventElement.draggable('option', 'grid', [colWidth, 1]); allDay = false; } }else{ revert = true; } } revert = revert || (allDay && !dayDelta); }else{ resetElement(); //setOverflowHidden(false); revert = true; } eventElement.draggable('option', 'revert', revert); }, ev, 'drag'); }, stop: function(ev, ui) { hoverListener.stop(); clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (revert) { // hasn't moved or is out of bounds (draggable has already reverted) resetElement(); eventElement.css('filter', ''); // clear IE opacity side-effects showEvents(event, eventElement); }else{ // changed! var minuteDelta = 0; if (!allDay) { minuteDelta = Math.round((eventElement.offset().top - getBodyContent().offset().top) / slotHeight) * opt('slotMinutes') + minMinute - (event.start.getHours() * 60 + event.start.getMinutes()); } eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui); } //setOverflowHidden(false); } }); function resetElement() { if (!allDay) { eventElement .width(origWidth) .height('') .draggable('option', 'grid', null); allDay = true; } } } // when event starts out IN TIMESLOTS function draggableSlotEvent(event, eventElement, timeElement) { var origPosition; var allDay=false; var dayDelta; var minuteDelta; var prevMinuteDelta; var dis = opt('isRTL') ? -1 : 1; var hoverListener = getHoverListener(); var colCnt = getColCnt(); var colWidth = getColWidth(); var slotHeight = getSlotHeight(); eventElement.draggable({ zIndex: 9, scroll: false, grid: [colWidth, slotHeight], axis: colCnt==1 ? 'y' : false, opacity: opt('dragOpacity'), revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); origPosition = eventElement.position(); minuteDelta = prevMinuteDelta = 0; hoverListener.start(function(cell, origCell, rowDelta, colDelta) { eventElement.draggable('option', 'revert', !cell); clearOverlays(); if (cell) { dayDelta = colDelta * dis; if (opt('allDaySlot') && !cell.row) { // over full days if (!allDay) { // convert to temporary all-day event allDay = true; timeElement.hide(); eventElement.draggable('option', 'grid', null); } renderDayOverlay( addDays(cloneDate(event.start), dayDelta), addDays(exclEndDay(event), dayDelta) ); }else{ // on slots resetElement(); } } }, ev, 'drag'); }, drag: function(ev, ui) { minuteDelta = Math.round((ui.position.top - origPosition.top) / slotHeight) * opt('slotMinutes'); if (minuteDelta != prevMinuteDelta) { if (!allDay) { updateTimeText(minuteDelta); } prevMinuteDelta = minuteDelta; } }, stop: function(ev, ui) { var cell = hoverListener.stop(); clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (cell && (dayDelta || minuteDelta || allDay)) { // changed! eventDrop(this, event, dayDelta, allDay ? 0 : minuteDelta, allDay, ev, ui); }else{ // either no change or out-of-bounds (draggable has already reverted) resetElement(); eventElement.css('filter', ''); // clear IE opacity side-effects eventElement.css(origPosition); // sometimes fast drags make event revert to wrong position updateTimeText(0); showEvents(event, eventElement); } } }); function updateTimeText(minuteDelta) { var newStart = addMinutes(cloneDate(event.start), minuteDelta); var newEnd; if (event.end) { newEnd = addMinutes(cloneDate(event.end), minuteDelta); } timeElement.text(formatDates(newStart, newEnd, opt('timeFormat'))); } function resetElement() { // convert back to original slot-event if (allDay) { timeElement.css('display', ''); // show() was causing display=inline eventElement.draggable('option', 'grid', [colWidth, slotHeight]); allDay = false; } } } /* Resizing --------------------------------------------------------------------------------------*/ function resizableSlotEvent(event, eventElement, timeElement) { var slotDelta, prevSlotDelta; var slotHeight = getSlotHeight(); eventElement.resizable({ handles: { s: 'div.ui-resizable-s' }, grid: slotHeight, start: function(ev, ui) { slotDelta = prevSlotDelta = 0; hideEvents(event, eventElement); eventElement.css('z-index', 9); trigger('eventResizeStart', this, event, ev, ui); }, resize: function(ev, ui) { // don't rely on ui.size.height, doesn't take grid into account slotDelta = Math.round((Math.max(slotHeight, eventElement.height()) - ui.originalSize.height) / slotHeight); if (slotDelta != prevSlotDelta) { timeElement.text( formatDates( event.start, (!slotDelta && !event.end) ? null : // no change, so don't display time range addMinutes(eventEnd(event), opt('slotMinutes')*slotDelta), opt('timeFormat') ) ); prevSlotDelta = slotDelta; } }, stop: function(ev, ui) { trigger('eventResizeStop', this, event, ev, ui); if (slotDelta) { eventResize(this, event, 0, opt('slotMinutes')*slotDelta, ev, ui); }else{ eventElement.css('z-index', 8); showEvents(event, eventElement); // BUG: if event was really short, need to put title back in span } } }); } } function countForwardSegs(levels) { var i, j, k, level, segForward, segBack; for (i=levels.length-1; i>0; i--) { level = levels[i]; for (j=0; j<level.length; j++) { segForward = level[j]; for (k=0; k<levels[i-1].length; k++) { segBack = levels[i-1][k]; if (segsCollide(segForward, segBack)) { segBack.forward = Math.max(segBack.forward||0, (segForward.forward||0)+1); } } } } } function View(element, calendar, viewName) { var t = this; // exports t.element = element; t.calendar = calendar; t.name = viewName; t.opt = opt; t.trigger = trigger; //t.setOverflowHidden = setOverflowHidden; t.isEventDraggable = isEventDraggable; t.isEventResizable = isEventResizable; t.reportEvents = reportEvents; t.eventEnd = eventEnd; t.reportEventElement = reportEventElement; t.reportEventClear = reportEventClear; t.eventElementHandlers = eventElementHandlers; t.showEvents = showEvents; t.hideEvents = hideEvents; t.eventDrop = eventDrop; t.eventResize = eventResize; // t.title // t.start, t.end // t.visStart, t.visEnd // imports var defaultEventEnd = t.defaultEventEnd; var normalizeEvent = calendar.normalizeEvent; // in EventManager var reportEventChange = calendar.reportEventChange; // locals var eventsByID = {}; var eventElements = []; var eventElementsByID = {}; var options = calendar.options; function opt(name, viewNameOverride) { var v = options[name]; if (typeof v == 'object') { return smartProperty(v, viewNameOverride || viewName); } return v; } function trigger(name, thisObj) { return calendar.trigger.apply( calendar, [name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t]) ); } /* function setOverflowHidden(bool) { element.css('overflow', bool ? 'hidden' : ''); } */ function isEventDraggable(event) { return isEventEditable(event) && !opt('disableDragging'); } function isEventResizable(event) { // but also need to make sure the seg.isEnd == true return isEventEditable(event) && !opt('disableResizing'); } function isEventEditable(event) { return firstDefined(event.editable, (event.source || {}).editable, opt('editable')); } /* Event Data ------------------------------------------------------------------------------*/ // report when view receives new events function reportEvents(events) { // events are already normalized at this point eventsByID = {}; var i, len=events.length, event; for (i=0; i<len; i++) { event = events[i]; if (eventsByID[event._id]) { eventsByID[event._id].push(event); }else{ eventsByID[event._id] = [event]; } } } // returns a Date object for an event's end function eventEnd(event) { return event.end ? cloneDate(event.end) : defaultEventEnd(event); } /* Event Elements ------------------------------------------------------------------------------*/ // report when view creates an element for an event function reportEventElement(event, element) { eventElements.push(element); if (eventElementsByID[event._id]) { eventElementsByID[event._id].push(element); }else{ eventElementsByID[event._id] = [element]; } } function reportEventClear() { eventElements = []; eventElementsByID = {}; } // attaches eventClick, eventMouseover, eventMouseout function eventElementHandlers(event, eventElement) { eventElement .click(function(ev) { if (!eventElement.hasClass('ui-draggable-dragging') && !eventElement.hasClass('ui-resizable-resizing')) { return trigger('eventClick', this, event, ev); } }) .hover( function(ev) { trigger('eventMouseover', this, event, ev); }, function(ev) { trigger('eventMouseout', this, event, ev); } ); // TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element) // TODO: same for resizing } function showEvents(event, exceptElement) { eachEventElement(event, exceptElement, 'show'); } function hideEvents(event, exceptElement) { eachEventElement(event, exceptElement, 'hide'); } function eachEventElement(event, exceptElement, funcName) { var elements = eventElementsByID[event._id], i, len = elements.length; for (i=0; i<len; i++) { if (!exceptElement || elements[i][0] != exceptElement[0]) { elements[i][funcName](); } } } /* Event Modification Reporting ---------------------------------------------------------------------------------*/ function eventDrop(e, event, dayDelta, minuteDelta, allDay, ev, ui) { var oldAllDay = event.allDay; var eventId = event._id; moveEvents(eventsByID[eventId], dayDelta, minuteDelta, allDay); trigger( 'eventDrop', e, event, dayDelta, minuteDelta, allDay, function() { // TODO: investigate cases where this inverse technique might not work moveEvents(eventsByID[eventId], -dayDelta, -minuteDelta, oldAllDay); reportEventChange(eventId); }, ev, ui ); reportEventChange(eventId); } function eventResize(e, event, dayDelta, minuteDelta, ev, ui) { var eventId = event._id; elongateEvents(eventsByID[eventId], dayDelta, minuteDelta); trigger( 'eventResize', e, event, dayDelta, minuteDelta, function() { // TODO: investigate cases where this inverse technique might not work elongateEvents(eventsByID[eventId], -dayDelta, -minuteDelta); reportEventChange(eventId); }, ev, ui ); reportEventChange(eventId); } /* Event Modification Math ---------------------------------------------------------------------------------*/ function moveEvents(events, dayDelta, minuteDelta, allDay) { minuteDelta = minuteDelta || 0; for (var e, len=events.length, i=0; i<len; i++) { e = events[i]; if (allDay !== undefined) { e.allDay = allDay; } addMinutes(addDays(e.start, dayDelta, true), minuteDelta); if (e.end) { e.end = addMinutes(addDays(e.end, dayDelta, true), minuteDelta); } normalizeEvent(e, options); } } function elongateEvents(events, dayDelta, minuteDelta) { minuteDelta = minuteDelta || 0; for (var e, len=events.length, i=0; i<len; i++) { e = events[i]; e.end = addMinutes(addDays(eventEnd(e), dayDelta, true), minuteDelta); normalizeEvent(e, options); } } } function DayEventRenderer() { var t = this; // exports t.renderDaySegs = renderDaySegs; t.resizableDayEvent = resizableDayEvent; // imports var opt = t.opt; var trigger = t.trigger; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var eventEnd = t.eventEnd; var reportEventElement = t.reportEventElement; var showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventResize = t.eventResize; var getRowCnt = t.getRowCnt; var getColCnt = t.getColCnt; var getColWidth = t.getColWidth; var allDayRow = t.allDayRow; var allDayBounds = t.allDayBounds; var colContentLeft = t.colContentLeft; var colContentRight = t.colContentRight; var dayOfWeekCol = t.dayOfWeekCol; var dateCell = t.dateCell; var compileDaySegs = t.compileDaySegs; var getDaySegmentContainer = t.getDaySegmentContainer; var bindDaySeg = t.bindDaySeg; //TODO: streamline this var formatDates = t.calendar.formatDates; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var clearSelection = t.clearSelection; /* Rendering -----------------------------------------------------------------------------*/ function renderDaySegs(segs, modifiedEventId) { var segmentContainer = getDaySegmentContainer(); var rowDivs; var rowCnt = getRowCnt(); var colCnt = getColCnt(); var i = 0; var rowI; var levelI; var colHeights; var j; var segCnt = segs.length; var seg; var top; var k; segmentContainer[0].innerHTML = daySegHTML(segs); // faster than .html() daySegElementResolve(segs, segmentContainer.children()); daySegElementReport(segs); daySegHandlers(segs, segmentContainer, modifiedEventId); daySegCalcHSides(segs); daySegSetWidths(segs); daySegCalcHeights(segs); rowDivs = getRowDivs(); // set row heights, calculate event tops (in relation to row top) for (rowI=0; rowI<rowCnt; rowI++) { levelI = 0; colHeights = []; for (j=0; j<colCnt; j++) { colHeights[j] = 0; } while (i<segCnt && (seg = segs[i]).row == rowI) { // loop through segs in a row top = arrayMax(colHeights.slice(seg.startCol, seg.endCol)); seg.top = top; top += seg.outerHeight; for (k=seg.startCol; k<seg.endCol; k++) { colHeights[k] = top; } i++; } rowDivs[rowI].height(arrayMax(colHeights)); } daySegSetTops(segs, getRowTops(rowDivs)); } function renderTempDaySegs(segs, adjustRow, adjustTop) { var tempContainer = $("<div/>"); var elements; var segmentContainer = getDaySegmentContainer(); var i; var segCnt = segs.length; var element; tempContainer[0].innerHTML = daySegHTML(segs); // faster than .html() elements = tempContainer.children(); segmentContainer.append(elements); daySegElementResolve(segs, elements); daySegCalcHSides(segs); daySegSetWidths(segs); daySegCalcHeights(segs); daySegSetTops(segs, getRowTops(getRowDivs())); elements = []; for (i=0; i<segCnt; i++) { element = segs[i].element; if (element) { if (segs[i].row === adjustRow) { element.css('top', adjustTop); } elements.push(element[0]); } } return $(elements); } function daySegHTML(segs) { // also sets seg.left and seg.outerWidth var rtl = opt('isRTL'); var i; var segCnt=segs.length; var seg; var event; var url; var classes; var bounds = allDayBounds(); var minLeft = bounds.left; var maxLeft = bounds.right; var leftCol; var rightCol; var left; var right; var skinCss; var html = ''; // calculate desired position/dimensions, create html for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; classes = ['fc-event', 'fc-event-skin', 'fc-event-hori']; if (isEventDraggable(event)) { classes.push('fc-event-draggable'); } if (rtl) { if (seg.isStart) { classes.push('fc-corner-right'); } if (seg.isEnd) { classes.push('fc-corner-left'); } leftCol = dayOfWeekCol(seg.end.getDay()-1); rightCol = dayOfWeekCol(seg.start.getDay()); left = seg.isEnd ? colContentLeft(leftCol) : minLeft; right = seg.isStart ? colContentRight(rightCol) : maxLeft; }else{ if (seg.isStart) { classes.push('fc-corner-left'); } if (seg.isEnd) { classes.push('fc-corner-right'); } leftCol = dayOfWeekCol(seg.start.getDay()); rightCol = dayOfWeekCol(seg.end.getDay()-1); left = seg.isStart ? colContentLeft(leftCol) : minLeft; right = seg.isEnd ? colContentRight(rightCol) : maxLeft; } classes = classes.concat(event.className); if (event.source) { classes = classes.concat(event.source.className || []); } url = event.url; skinCss = getSkinCss(event, opt); if (url) { html += "<a href='" + htmlEscape(url) + "'"; }else{ html += "<div"; } html += " class='" + classes.join(' ') + "'" + " style='position:absolute;z-index:8;left:"+left+"px;" + skinCss + "'" + ">" + "<div" + " class='fc-event-inner fc-event-skin'" + (skinCss ? " style='" + skinCss + "'" : '') + ">"; if (!event.allDay && seg.isStart) { html += "<span class='fc-event-time'>" + htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + "</span>"; } html += "<span class='fc-event-title'>" + htmlEscape(event.title) + "</span>" + "</div>"; if (seg.isEnd && isEventResizable(event)) { html += "<div class='ui-resizable-handle ui-resizable-" + (rtl ? 'w' : 'e') + "'>" + "&nbsp;&nbsp;&nbsp;" + // makes hit area a lot better for IE6/7 "</div>"; } html += "</" + (url ? "a" : "div" ) + ">"; seg.left = left; seg.outerWidth = right - left; seg.startCol = leftCol; seg.endCol = rightCol + 1; // needs to be exclusive } return html; } function daySegElementResolve(segs, elements) { // sets seg.element var i; var segCnt = segs.length; var seg; var event; var element; var triggerRes; for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; element = $(elements[i]); // faster than .eq() triggerRes = trigger('eventRender', event, event, element); if (triggerRes === false) { element.remove(); }else{ if (triggerRes && triggerRes !== true) { triggerRes = $(triggerRes) .css({ position: 'absolute', left: seg.left }); element.replaceWith(triggerRes); element = triggerRes; } seg.element = element; } } } function daySegElementReport(segs) { var i; var segCnt = segs.length; var seg; var element; for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { reportEventElement(seg.event, element); } } } function daySegHandlers(segs, segmentContainer, modifiedEventId) { var i; var segCnt = segs.length; var seg; var element; var event; // retrieve elements, run through eventRender callback, bind handlers for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { event = seg.event; if (event._id === modifiedEventId) { bindDaySeg(event, element, seg); }else{ element[0]._fci = i; // for lazySegBind } } } lazySegBind(segmentContainer, segs, bindDaySeg); } function daySegCalcHSides(segs) { // also sets seg.key var i; var segCnt = segs.length; var seg; var element; var key, val; var hsideCache = {}; // record event horizontal sides for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { key = seg.key = cssKey(element[0]); val = hsideCache[key]; if (val === undefined) { val = hsideCache[key] = hsides(element, true); } seg.hsides = val; } } } function daySegSetWidths(segs) { var i; var segCnt = segs.length; var seg; var element; for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { element[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px'; } } } function daySegCalcHeights(segs) { var i; var segCnt = segs.length; var seg; var element; var key, val; var vmarginCache = {}; // record event heights for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { key = seg.key; // created in daySegCalcHSides val = vmarginCache[key]; if (val === undefined) { val = vmarginCache[key] = vmargins(element); } seg.outerHeight = element[0].offsetHeight + val; } } } function getRowDivs() { var i; var rowCnt = getRowCnt(); var rowDivs = []; for (i=0; i<rowCnt; i++) { rowDivs[i] = allDayRow(i) .find('td:first div.fc-day-content > div'); // optimal selector? } return rowDivs; } function getRowTops(rowDivs) { var i; var rowCnt = rowDivs.length; var tops = []; for (i=0; i<rowCnt; i++) { tops[i] = rowDivs[i][0].offsetTop; // !!?? but this means the element needs position:relative if in a table cell!!!! } return tops; } function daySegSetTops(segs, rowTops) { // also triggers eventAfterRender var i; var segCnt = segs.length; var seg; var element; var event; for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { element[0].style.top = rowTops[seg.row] + (seg.top||0) + 'px'; event = seg.event; trigger('eventAfterRender', event, event, element); } } } /* Resizing -----------------------------------------------------------------------------------*/ function resizableDayEvent(event, element, seg) { var rtl = opt('isRTL'); var direction = rtl ? 'w' : 'e'; var handle = element.find('div.ui-resizable-' + direction); var isResizing = false; // TODO: look into using jquery-ui mouse widget for this stuff disableTextSelection(element); // prevent native <a> selection for IE element .mousedown(function(ev) { // prevent native <a> selection for others ev.preventDefault(); }) .click(function(ev) { if (isResizing) { ev.preventDefault(); // prevent link from being visited (only method that worked in IE6) ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called // (eventElementHandlers needs to be bound after resizableDayEvent) } }); handle.mousedown(function(ev) { if (ev.which != 1) { return; // needs to be left mouse button } isResizing = true; var hoverListener = t.getHoverListener(); var rowCnt = getRowCnt(); var colCnt = getColCnt(); var dis = rtl ? -1 : 1; var dit = rtl ? colCnt-1 : 0; var elementTop = element.css('top'); var dayDelta; var helpers; var eventCopy = $.extend({}, event); var minCell = dateCell(event.start); clearSelection(); $('body') .css('cursor', direction + '-resize') .one('mouseup', mouseup); trigger('eventResizeStart', this, event, ev); hoverListener.start(function(cell, origCell) { if (cell) { var r = Math.max(minCell.row, cell.row); var c = cell.col; if (rowCnt == 1) { r = 0; // hack for all-day area in agenda views } if (r == minCell.row) { if (rtl) { c = Math.min(minCell.col, c); }else{ c = Math.max(minCell.col, c); } } dayDelta = (r*7 + c*dis+dit) - (origCell.row*7 + origCell.col*dis+dit); var newEnd = addDays(eventEnd(event), dayDelta, true); if (dayDelta) { eventCopy.end = newEnd; var oldHelpers = helpers; helpers = renderTempDaySegs(compileDaySegs([eventCopy]), seg.row, elementTop); helpers.find('*').css('cursor', direction + '-resize'); if (oldHelpers) { oldHelpers.remove(); } hideEvents(event); }else{ if (helpers) { showEvents(event); helpers.remove(); helpers = null; } } clearOverlays(); renderDayOverlay(event.start, addDays(cloneDate(newEnd), 1)); // coordinate grid already rebuild at hoverListener.start } }, ev); function mouseup(ev) { trigger('eventResizeStop', this, event, ev); $('body').css('cursor', ''); hoverListener.stop(); clearOverlays(); if (dayDelta) { eventResize(this, event, dayDelta, 0, ev); // event redraw will clear helpers } // otherwise, the drag handler already restored the old events setTimeout(function() { // make this happen after the element's click event isResizing = false; },0); } }); } } //BUG: unselect needs to be triggered when events are dragged+dropped function SelectionManager() { var t = this; // exports t.select = select; t.unselect = unselect; t.reportSelection = reportSelection; t.daySelectionMousedown = daySelectionMousedown; // imports var opt = t.opt; var trigger = t.trigger; var defaultSelectionEnd = t.defaultSelectionEnd; var renderSelection = t.renderSelection; var clearSelection = t.clearSelection; // locals var selected = false; // unselectAuto if (opt('selectable') && opt('unselectAuto')) { $(document).mousedown(function(ev) { var ignore = opt('unselectCancel'); if (ignore) { if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match return; } } unselect(ev); }); } function select(startDate, endDate, allDay) { unselect(); if (!endDate) { endDate = defaultSelectionEnd(startDate, allDay); } renderSelection(startDate, endDate, allDay); reportSelection(startDate, endDate, allDay); } function unselect(ev) { if (selected) { selected = false; clearSelection(); trigger('unselect', null, ev); } } function reportSelection(startDate, endDate, allDay, ev) { selected = true; trigger('select', null, startDate, endDate, allDay, ev); } function daySelectionMousedown(ev) { // not really a generic manager method, oh well var cellDate = t.cellDate; var cellIsAllDay = t.cellIsAllDay; var hoverListener = t.getHoverListener(); var reportDayClick = t.reportDayClick; // this is hacky and sort of weird if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button unselect(ev); var _mousedownElement = this; var dates; hoverListener.start(function(cell, origCell) { // TODO: maybe put cellDate/cellIsAllDay info in cell clearSelection(); if (cell && cellIsAllDay(cell)) { dates = [ cellDate(origCell), cellDate(cell) ].sort(cmp); renderSelection(dates[0], dates[1], true); }else{ dates = null; } }, ev); $(document).one('mouseup', function(ev) { hoverListener.stop(); if (dates) { if (+dates[0] == +dates[1]) { reportDayClick(dates[0], true, ev); } reportSelection(dates[0], dates[1], true, ev); } }); } } } function OverlayManager() { var t = this; // exports t.renderOverlay = renderOverlay; t.clearOverlays = clearOverlays; // locals var usedOverlays = []; var unusedOverlays = []; function renderOverlay(rect, parent) { var e = unusedOverlays.shift(); if (!e) { e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>"); } if (e[0].parentNode != parent[0]) { e.appendTo(parent); } usedOverlays.push(e.css(rect).show()); return e; } function clearOverlays() { var e; while (e = usedOverlays.shift()) { unusedOverlays.push(e.hide().unbind()); } } } function CoordinateGrid(buildFunc) { var t = this; var rows; var cols; t.build = function() { rows = []; cols = []; buildFunc(rows, cols); }; t.cell = function(x, y) { var rowCnt = rows.length; var colCnt = cols.length; var i, r=-1, c=-1; for (i=0; i<rowCnt; i++) { if (y >= rows[i][0] && y < rows[i][1]) { r = i; break; } } for (i=0; i<colCnt; i++) { if (x >= cols[i][0] && x < cols[i][1]) { c = i; break; } } return (r>=0 && c>=0) ? { row:r, col:c } : null; }; t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive var origin = originElement.offset(); return { top: rows[row0][0] - origin.top, left: cols[col0][0] - origin.left, width: cols[col1][1] - cols[col0][0], height: rows[row1][1] - rows[row0][0] }; }; } function HoverListener(coordinateGrid) { var t = this; var bindType; var change; var firstCell; var cell; t.start = function(_change, ev, _bindType) { change = _change; firstCell = cell = null; coordinateGrid.build(); mouse(ev); bindType = _bindType || 'mousemove'; $(document).bind(bindType, mouse); }; function mouse(ev) { var newCell = coordinateGrid.cell(ev.pageX, ev.pageY); if (!newCell != !cell || newCell && (newCell.row != cell.row || newCell.col != cell.col)) { if (newCell) { if (!firstCell) { firstCell = newCell; } change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col); }else{ change(newCell, firstCell); } cell = newCell; } } t.stop = function() { $(document).unbind(bindType, mouse); return cell; }; } function HorizontalPositionCache(getElement) { var t = this, elements = {}, lefts = {}, rights = {}; function e(i) { return elements[i] = elements[i] || getElement(i); } t.left = function(i) { return lefts[i] = lefts[i] === undefined ? e(i).position().left : lefts[i]; }; t.right = function(i) { return rights[i] = rights[i] === undefined ? t.left(i) + e(i).width() : rights[i]; }; t.clear = function() { elements = {}; lefts = {}; rights = {}; }; } })(jQuery); /* * FullCalendar v1.5.1 Google Calendar Plugin * * Copyright (c) 2011 Adam Shaw * Dual licensed under the MIT and GPL licenses, located in * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. * * Date: Sat Apr 9 14:09:51 2011 -0700 * */ (function($) { var fc = $.fullCalendar; var formatDate = fc.formatDate; var parseISO8601 = fc.parseISO8601; var addDays = fc.addDays; var applyAll = fc.applyAll; fc.sourceNormalizers.push(function(sourceOptions) { if (sourceOptions.dataType == 'gcal' || sourceOptions.dataType === undefined && (sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) { sourceOptions.dataType = 'gcal'; if (sourceOptions.editable === undefined) { sourceOptions.editable = false; } } }); fc.sourceFetchers.push(function(sourceOptions, start, end) { if (sourceOptions.dataType == 'gcal') { return transformOptions(sourceOptions, start, end); } }); function transformOptions(sourceOptions, start, end) { var success = sourceOptions.success; var data = $.extend({}, sourceOptions.data || {}, { 'start-min': formatDate(start, 'u'), 'start-max': formatDate(end, 'u'), 'singleevents': true, 'max-results': 9999 }); var ctz = sourceOptions.currentTimezone; if (ctz) { data.ctz = ctz = ctz.replace(' ', '_'); } return $.extend({}, sourceOptions, { url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?', dataType: 'jsonp', data: data, startParam: false, endParam: false, success: function(data) { var events = []; if (data.feed.entry) { $.each(data.feed.entry, function(i, entry) { var startStr = entry['gd$when'][0]['startTime']; var start = parseISO8601(startStr, true); var end = parseISO8601(entry['gd$when'][0]['endTime'], true); var allDay = startStr.indexOf('T') == -1; var url; $.each(entry.link, function(i, link) { if (link.type == 'text/html') { url = link.href; if (ctz) { url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz; } } }); if (allDay) { addDays(end, -1); // make inclusive } events.push({ id: entry['gCal$uid']['value'], title: entry['title']['$t'], url: url, start: start, end: end, allDay: allDay, location: entry['gd$where'][0]['valueString'], description: entry['content']['$t'] }); }); } var args = [events].concat(Array.prototype.slice.call(arguments, 1)); var res = applyAll(success, this, args); if ($.isArray(res)) { return res; } return events; } }); } // legacy fc.gcalFeed = function(url, sourceOptions) { return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' }); }; })(jQuery); });
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Fileexplorer v 1.0 by revaxarts.com /* description: makes a Fileexplorer /* dependency: elFinder plugin (elfinder.js) /*----------------------------------------------------------------------*/ $.fn.wl_Fileexplorer = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Fileexplorer.methods[method]) { return $.fn.wl_Fileexplorer.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Fileexplorer')) { var opts = $.extend({}, $this.data('wl_Fileexplorer'), method); } else { var opts = $.extend({}, $.fn.wl_Fileexplorer.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Fileexplorer')) { $this.data('wl_Fileexplorer', {}); //simple: call the plugin! //this has potential. maybe there are some options in future updates $this.elfinder(opts); } else { } if (opts) $.extend($this.data('wl_Fileexplorer'), opts); }); }; $.fn.wl_Fileexplorer.defaults = { url: 'elfinder/php/connector.php', toolbar: [ ['back', 'reload', 'open', 'select', 'quicklook', 'info', 'rename', 'copy', 'cut', 'paste', 'rm', 'mkdir', 'mkfile', 'upload', 'duplicate', 'edit', 'archive', 'extract', 'resize', 'icons', 'list', 'help'] ] }; $.fn.wl_Fileexplorer.version = '1.0'; $.fn.wl_Fileexplorer.methods = { set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Fileexplorer.defaults[key] !== undefined || $.fn.wl_Fileexplorer.defaults[key] == null) { $this.data('wl_Fileexplorer')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Chart v 1.3 by revaxarts.com /* description: extends the flot library /* dependency: flot library /*----------------------------------------------------------------------*/ $.fn.wl_Chart = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Chart.methods[method]) { return $.fn.wl_Chart.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Chart')) { var opts = $.extend({}, $this.data('wl_Chart'), method); } else { var opts = $.extend({}, $.fn.wl_Chart.defaults, method, $this.data()); } } else { try { return $this.data('wl_Chart').plot[method](args[1], args[2]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } //throw an error if wrong chart typ is set if (!/^(lines|bars|pie)$/.test(opts.type)) { $.error('Type of "' + opts.type + '" is not allowed'); } if (!$this.data('wl_Chart')) { $this.data('wl_Chart', {}); //bind a resize event to redraw the chart if the window size change $(window).bind('resize.wl_Chart', function () { $this.data('wl_Chart').holder.width('99%'); $.fn.wl_Chart.methods.draw.call($this[0]); }); //make a holder for the chart and set the width too 99% (100% causes overflow problems in some browsers) opts.holder = $('<div/>', { 'class': 'chart' }).css({ width: (opts.width || $this.width() || '100%') / 100 * 99, height: opts.height || 300 })[(opts.tableBefore) ? 'insertAfter' : 'insertBefore']($this); } else { //quick destroy opts.holder.unbind("plothover").unbind('mouseout'); } //set the width opts.width = opts.holder.width(); //show or hide the table (opts.hideTable) ? $this.hide() : $this.show(); //bind the click event on the stats opts.holder.bind("plotclick", function (event, pos, item) { if (item) { var patt = {}; switch (opts.type) { case 'bars': patt['value'] = item.datapoint[1]; patt['label'] = item.series.xaxis.ticks[item.dataIndex].label; patt['id'] = item.seriesIndex; break; case 'pie': patt['value'] = item.datapoint[1][0][1]; patt['label'] = item.series.xaxis.options.ticks[0][1]; patt['id'] = item.seriesIndex; break; default: patt['value'] = item.datapoint[1]; patt['label'] = item.series.xaxis.ticks[item.datapoint[0]].label; patt['id'] = item.seriesIndex; } patt['legend'] = item.series.label; opts.onClick.call($this[0], patt['value'], patt['legend'], patt['label'], patt['id'], item); } }); //We have a tooltip if (opts.tooltip) { //attach the tipsy tooltip to the holder opts.holder.tipsy($.extend({}, config.tooltip, { fallback: '', followMouse: true, gravity: opts.tooltipGravity || 'n' })); var prev = null, text; //bind a hover event to the graph opts.holder.bind("plothover", function (e, pos, item) { if (item) { //check if we don't have to do the same stuff more then once if (item.datapoint.toString() != prev) { var patt = {}; prev = item.datapoint.toString(); switch (opts.type) { case 'bars': //stacked bars have an offset (http://support.revaxarts-themes.com/discussion/165/tooltip-on-a-stacked-chart) patt['value'] = (opts.stack) ? item.datapoint[1]-item.datapoint[2] : item.datapoint[1]; patt['label'] = item.series.xaxis.ticks[item.dataIndex].label; patt['id'] = item.seriesIndex; break; case 'pie': patt['value'] = item.datapoint[1][0][1]; patt['label'] = item.series.xaxis.options.ticks[0][1]; patt['id'] = item.seriesIndex; break; default: patt['value'] = item.datapoint[1]; patt['label'] = item.series.xaxis.ticks[item.datapoint[0]].label; patt['id'] = item.seriesIndex; } patt['legend'] = item.series.label; //is the pattern a function or a simple string? if ($.isFunction(opts.tooltipPattern)) { text = opts.tooltipPattern.call($this[0], patt['value'], patt['legend'], patt['label'], patt['id'], item); } else { text = opts.tooltipPattern.replace(/%1/g, patt['value']).replace(/%2/g, patt['legend']).replace(/%3/g, patt['label']).replace(/%4/g, patt['id']); } //set the title and show the tooltip opts.holder.tipsy('setTitel', text); opts.holder.tipsy('show'); } else { return; } } else { //hide tooltip if we leave the point opts.holder.tipsy('hide'); prev = null; } }).bind('mouseout', function () { //hide tooltip if we leave the plot opts.holder.tipsy('hide'); prev = null; }); } //the colors are maybe not an array if they a specified within a data attribute if (!$.isArray(opts.colors)) { opts.colors = $.parseData(opts.colors, true); } var colors = []; //a data object is set (no table) if (!$.isEmptyObject(opts.data)) { //labels on the x axis are set if (opts.xlabels) { //convert them in the proper format opts.xlabels = $.map(opts.xlabels, function (value, key) { return [[key, value]]; }); //no labels are set } else { //get labels out of the data opts.xlabels = function () { var ret = []; $.each(opts.data, function (i, e) { $.map(opts.data[i].data, function (value, key) { ret[value[0]] = key; }); }); return $.map(ret, function (value, key) { return key; }); }(); } //define colors in a loop colors = $.map(opts.data, function (value, key) { return opts.colors[key % opts.colors.length]; }); //data is from a table } else if ($.isEmptyObject(opts.data) && $this.is('table')) { opts.xlabels = opts.xlabels || []; opts.data = []; switch (opts.orientation) { //table is in horizontal mode (normal) case 'horizontal': var $xlabels = $this.find('thead th'), $legends = $this.find('tbody th'), $rows = $this.find('tbody tr'); var legendlength = $legends.length; //strip the very first cell because it's not necessary if (legendlength) $xlabels = $xlabels.slice(1); //fetch each row of the table $rows.each(function (i, row) { var data = $(row).find('td'), _d = []; //fetch each cell of the row data.each(function (j, td) { var d = parseFloat(td.innerHTML); //only numbers are valid if (!isNaN(d)) _d.push([j, (d || 0)]); //some stuff for the labels on the x axis opts.xlabels.push([j, $xlabels.eq(j).text()]); }); //push the data in the data-object for this row (label) opts.data.push({ 'label': $legends.eq(i).text(), 'data': (opts.type != 'pie') ? _d : _d[0][1] }); //define colors in a loop colors[i] = $rows.eq(i).data('color') || opts.colors[i] || colors[i % opts.colors.length]; }); break; //table is in vertical mode case 'vertical': var $xlabels = $this.find('tbody th'), $legends = $this.find('thead th'), $rows = $this.find('tbody tr'); var legendlength = $legends.length; if (legendlength) { $legends = $legends.slice(1); legendlength--; } var _d = []; //fetch each row of the table $rows.each(function (i, row) { var data = $(row).find('td'); data.each(function (j, td) { var d = parseFloat(td.innerHTML); _d[j] = _d[j] || []; //only numbers are valid if (!isNaN(d)) _d[j].push([i, (d || 0)]); }); //some stuff for the labels on the x axis opts.xlabels.push([i, $xlabels.eq(i).text()]); }); //push the data in the data-object for this row (label) and define the colors for (var i = 0; i < legendlength; i++) { opts.data.push({ 'label': $legends.eq(i).text(), 'data': _d[i] }); colors[i] = opts.colors[i] || colors[i % opts.colors.length]; } break; default: //trigger an error $.error('Orientation "' + opts.orientation + '" is not allowed'); } } else { //trigger an error id no data or ttable is set $.error('No data or data table!'); } opts.colors = colors; var std = {}; //define some chart type specific standards switch (opts.type) { case 'bars': std = { points: { show: (opts.points !== null) ? opts.points : false }, bars: { order: (opts.stack) ? null : true, show: true, border: false, fill: (opts.fill !== null) ? opts.fill : true, fillColor: (opts.fillColor !== null) ? opts.fillColor : null, align: opts.align || 'center', horizontal: opts.horizontal || false, barWidth: opts.barWidth || (opts.stack) ? 0.85 : 0.85 / opts.data.length, lineWidth: (opts.lineWidth !== null) ? opts.lineWidth : 0 }, lines: { show: false }, pie: { show: false } }; break; case 'pie': std = { points: { show: (opts.points !== null) ? opts.points : true }, bars: { show: false }, lines: { show: false }, pie: { show: true, label: true, tilt: opts.tilt || 1, innerRadius: (opts.innerRadius) ? opts.innerRadius : 0, radius: (opts.tilt && !opts.radius) ? 0.8 : opts.radius || 1, shadowSize: 2 } }; break; case 'lines': default: std = { points: { show: (opts.points !== null) ? opts.points : true }, bars: { show: false }, lines: { show: true, lineWidth: (opts.lineWidth !== null) ? opts.lineWidth : 4, fill: (opts.fill !== null) ? opts.fill : false, fillColor: (opts.fillColor !== null) ? opts.fillColor : null }, pie: { show: false } }; } //some more standards and maybe the flot object var options = $.extend(true, {}, { series: $.extend(true, {}, { //must set to null not to false stack: (opts.stack) ? true : null, points: { show: opts.points } }, std), shadowSize: opts.shadowSize || 0, grid: { hoverable: opts.tooltip, clickable: true, color: '#666', borderWidth: null }, legend: { show: opts.legend, position: (/^(ne|nw|se|sw)$/.test(opts.legendPosition)) ? opts.legendPosition : 'ne' }, colors: opts.colors, xaxis: { ticks: opts.xlabels } }, opts.flot); //extend the flot object opts.flotobj = $.extend({}, opts.flotobj, options); if (opts) $.extend($this.data('wl_Chart'), opts); //let's draw the graph $.fn.wl_Chart.methods.draw.call(this); }); }; $.fn.wl_Chart.defaults = { width: null, height: 300, hideTable: true, tableBefore: false, data: {}, stack: false, type: 'lines', points: null, shadowSize: 2, fill: null, fillColor: null, lineWidth: null, legend: true, legendPosition: "ne", // or "nw" or "se" or "sw" tooltip: true, tooltipGravity: 'n', tooltipPattern: function (value, legend, label, id, itemobj) { return "value is " + value + " from " + legend + " at " + label + " (" + id + ")"; }, orientation: 'horizontal', colors: ['#b2e7b2', '#f0b7b7', '#b5f0f0', '#e8e8b3', '#efb7ef', '#bbb6f0'], flot: {}, onClick: function (value, legend, label, id, itemobj) {} }; $.fn.wl_Chart.version = '1.3'; $.fn.wl_Chart.methods = { draw: function () { var $this = $(this), _opts = $this.data('wl_Chart'); //draw the chart and save it within the DOM $this.data('wl_Chart').plot = $.plot(_opts.holder, _opts.data, _opts.flotobj); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Chart.defaults[key] !== undefined || $.fn.wl_Chart.defaults[key] == null) { $this.data('wl_Chart')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Valid v 1.0 by revaxarts.com /* description: validates an input /* dependency: /*----------------------------------------------------------------------*/ $.fn.wl_Valid = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Valid.methods[method]) { return $.fn.wl_Valid.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Valid')) { var opts = $.extend({}, $this.data('wl_Valid'), method); } else { var opts = $.extend({}, $.fn.wl_Valid.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } //regex is a string => convert it if (typeof opts.regex === 'string') { opts.regex = new RegExp(opts.regex); } if (!$this.data('wl_Valid')) { $this.data('wl_Valid', {}); $this.bind({ //validate on change event 'change.wl_Valid': function () { var opts = $this.data('wl_Valid') || opts; $.fn.wl_Valid.methods.validate.call($this[0]); //callback opts.onChange.call($this[0], $this, $this.val()); if (!opts.valid) { //error callback opts.onError.call($this[0], $this, $this.val()); } }, //for instant callback 'keyup.wl_Valid': function () { var opts = $this.data('wl_Valid') || opts; if (opts.instant) { //validate only if minlength is reached if ($this.val().length >= $this.data('wl_Valid').minLength) { $this.wl_Valid('validate'); } } } }); } else { } if (opts) $.extend($this.data('wl_Valid'), opts); $.fn.wl_Valid.methods.validate.call($this); }); }; $.fn.wl_Valid.defaults = { errorClass: 'error', instant: true, regex: /.*/, minLength: 0, onChange: function ($this, value) {}, onError: function ($this, value) {} }; $.fn.wl_Valid.version = '1.0'; $.fn.wl_Valid.methods = { validate: function () { var $this = $(this), opts = $this.data('wl_Valid') || opts, value = $this.val(); //check for validation, empty is valid too! opts.valid = (!value || opts.regex.test(value)); //field is valid or equal to a placeholder attribute if (opts.valid || (value == $this.attr('placeholder'))) { $this.removeClass(opts.errorClass); } else { $this.addClass(opts.errorClass); } }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Valid.defaults[key] !== undefined || $.fn.wl_Valid.defaults[key] == null) { switch (key) { case 'regex': value = new RegExp(value); break; default: } $this.data('wl_Valid')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } }; /*----------------------------------------------------------------------*/ /* wl_Mail by revaxarts.com /* description: Shorthand for wl_Valid for email addresses /* dependency: wl_Valid /*----------------------------------------------------------------------*/ $.fn.wl_Mail = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Valid.methods[method]) { return $.fn.wl_Valid.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Valid')) { var opts = $.extend({}, $this.data('wl_Valid'), method); } else { var opts = $.extend({}, $.fn.wl_Mail.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } $this.wl_Valid(opts); if (opts) $.extend($this.data('wl_Valid'), opts); }); }; $.fn.wl_Mail.defaults = { regex: /^([\w-]+(?:\.[\w-]+)*)\@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$|(\[?(\d{1,3}\.){3}\d{1,3}\]?)$/i, onChange: function (element, value) { element.val(value.toLowerCase()); } }; /*----------------------------------------------------------------------*/ /* wl_URL by revaxarts.com /* description: Shorthand for wl_Valid for urls /* dependency: wl_Valid /*----------------------------------------------------------------------*/ $.fn.wl_URL = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Valid.methods[method]) { return $.fn.wl_Valid.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Valid')) { var opts = $.extend({}, $this.data('wl_Valid'), method); } else { var opts = $.extend({}, $.fn.wl_URL.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } $this.wl_Valid(opts); if (opts) $.extend($this.data('wl_Valid'), opts); }); }; $.fn.wl_URL.defaults = { regex: /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w]))*\.+(([\w#!:.?+=&%@!\-\/]))?/, instant: false, onChange: function (element, value) { if (value != '' && !/^(ftp|http|https):\/\//.test(value)) element.val('http://' + value).trigger('change.wl_Valid'); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Widget v 1.2 by revaxarts.com /* description: handles all function for the widgets /* dependency: wl_Store, jquery sortable a.d. /*----------------------------------------------------------------------*/ $.fn.wl_Widget = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Widget.methods[method]) { return $.fn.wl_Widget.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Widget')) { var opts = $.extend({}, $this.data('wl_Widget'), method); } else { var opts = $.extend({}, $.fn.wl_Widget.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Widget')) { $this.data('wl_Widget', {}); //find the widgets within the conatainer var $widgets = $this.find('div.widget'); //iterate thru the widgets $widgets.each(function () { var $widget = $(this), _opts = $.extend({}, opts, $widget.data()), $handle = $widget.find('h3.handle'), $content = $widget.find('div').eq(0), $container = $widget.parent(); $widget.data('wl_Widget', {}); //set an icon if (_opts.icon) { $handle.addClass('icon'); $('<a>', { 'class': 'icon i_' + _opts.icon }).appendTo($handle); } //if sortable add a class if (_opts.sortable) { $widget.addClass('sortable'); } //if collapsible if(_opts.collapsible){ //add the collapse button $('<a>', { 'class': 'collapse', 'title': _opts.text.collapse }).appendTo($handle); //collapse if set if (_opts.collapsed) { $content.hide(); $widget.addClass('collapsed'); $handle.find('a.collapse').attr('title',_opts.text.expand); } //handle the collapse button (touchstart is required for iOS devices) $handle.delegate('a.collapse', 'click.wl_Widget touchstart.wl_Widget', function (event) { var _opts = $widget.data('wl_Widget') || _opts, _content = $widget.find('div').eq(0); if (_content.is(':hidden')) { //expand hidden content _content.slideDown(100, function () { $widget.removeClass('collapsed').data('wl_Widget').collapsed = false; $handle.find('a.collapse').attr('title',_opts.text.collapse); //callback _opts.onExpand.call($widget[0]); //save $.fn.wl_Widget.methods.save(); //trigger resize for some plugins $(window).resize(); }); } else { //hide content $content.slideUp(100, function () { $widget.addClass('collapsed').data('wl_Widget').collapsed = true; $handle.find('a.collapse').attr('title',_opts.text.expand); //callback _opts.onCollapse.call($widget[0]); //save $.fn.wl_Widget.methods.save(); }); } return false; //doublclick is equal to collapse button }).bind('dblclick', function () { $handle.find('a.collapse').trigger('click'); return false; }); } //handle the reload button (touchstart is required for iOS devices) $handle.delegate('a.reload', 'click.wl_Widget touchstart.wl_Widget', function (event) { var _opts = $widget.data('wl_Widget') || _opts, _content = $widget.find('div').eq(0); $widget.addClass('loading'); //set height to prevent "jumping" _content.height($content.height()); //removeContent and replace it with a loading information if (_opts.removeContent) { _content.html(_opts.text.loading); } _content.load(_opts.load, function (response, status, xhr) { $widget.removeClass('loading'); _content.height('auto'); //error occured if (status == "error") { _content.html(xhr.status + " " + xhr.statusText); } //autoreload is set if (_opts.reload) { clearTimeout($widget.data('wl_Widget').timeout); $widget.data('wl_Widget').timeout = setTimeout(function () { $handle.find('a.reload').trigger('click.wl_Widget'); }, _opts.reload * 1000); } }); return false; }); //prevent other anochrs to bubble up the DOM $handle.delegate('a', 'click.wl_Widget', function (event) { event.stopPropagation(); return false; }); if (_opts) $.extend($widget.data('wl_Widget'), _opts); //ajax widgets get a reload button if (_opts.load) { $('<a>', { 'class': 'reload', 'title': _opts.text.reload }).appendTo($handle).trigger('click.wl_Widget'); } }); //Handling sortable and restoring positions var $maincontent = $('#content'); //save the total count of widgets if (!$maincontent.data('wl_Widget')) { $maincontent.data('wl_Widget', { containercount: $('div.widgets').length, currentid: 1 }); } //if all widgets are initialized if ($maincontent.data('wl_Widget').currentid++ >= $maincontent.data('wl_Widget').containercount) { var $container = $('div.widgets'); //get data from the storage var wl_Store = new $.wl_Store('wl_' + location.pathname.toString()); //iterate thru the containers $container.each(function (i, cont) { var widgets = wl_Store.get('widgets_' + i), $cont = $(this); if (!widgets) return false; //iterate thru the widgets from the container id i $.each(widgets, function (widget, options) { var _widget = $('#' + widget); //widget should be collpased (options.collapsed && _widget.data('wl_Widget').collapsible) ? _widget.addClass('collapsed').find('div').eq(0).hide().data('wl_Widget', { collapsed: true }) : _widget.removeClass('collapsed').find('div').eq(0).show().data('wl_Widget', { collapsed: false }); //position handling if (_widget.length && (_widget.prevAll('div').length != options.position || _widget.parent()[0] !== $cont[0])) { children = $cont.children('div.widget'); if (children.eq(options.position).length) { _widget.insertBefore(children.eq(options.position)); } else if (children.length) { _widget.insertAfter(children.eq(options.position - 1)); } else { _widget.appendTo($cont); } } }); }); //use jQuery UI sortable plugin for the widget sortable function $container.sortable({ items: $container.find('div.widget.sortable'), containment: '#content', opacity: 0.8, distance: 5, handle: 'h3.handle', connectWith: $container, forceHelperSize: true, placeholder: 'sortable_placeholder', forcePlaceholderSize: true, zIndex: 10000, start: function (event, ui) { ui.item.data('wl_Widget').onDrag.call(ui.item[0]); }, stop: function (event, ui) { ui.item.data('wl_Widget').onDrop.call(ui.item[0]); $.fn.wl_Widget.methods.save(); } }); } } else { } if (opts) $.extend($this.data('wl_Widget'), opts); }); }; $.fn.wl_Widget.defaults = { collapsed: false, load: null, reload: false, removeContent: true, collapsible: true, sortable: true, text: { loading: 'loading...', reload: 'reload', collapse: 'collapse widget', expand: 'expand widget' }, onDrag: function () {}, onDrop: function () {}, onExpand: function () {}, onCollapse: function () {} }; $.fn.wl_Widget.version = '1.2'; $.fn.wl_Widget.methods = { save: function () { var $containers = $('div.widgets'), wl_Store = new $.wl_Store('wl_' + location.pathname.toString()); //iterate thru the containers $containers.each(function (containerid, e) { var _widgets = {}; //get info from all widgets from that container $(this).find('div.widget').each(function (pos, e) { var _t = $(this); _widgets[this.id] = { position: pos, collapsed: _t.find('div').eq(0).is(':hidden') }; }); //store the info wl_Store.save('widgets_' + containerid, _widgets); }); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Widget.defaults[key] !== undefined || $.fn.wl_Widget.defaults[key] == null) { $this.data('wl_Widget')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Number v 1.0 by revaxarts.com /* description: Make a Number field out of an input field /* dependency: mousewheel plugin /*----------------------------------------------------------------------*/ $.fn.wl_Number = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Number.methods[method]) { return $.fn.wl_Number.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Number')) { var opts = $.extend({}, $this.data('wl_Number'), method); } else { var opts = $.extend({}, $.fn.wl_Number.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Number')) { $this.data('wl_Number', {}); //fetch the nativ attributes opts.min = $this.attr('min') || opts.min; opts.max = $this.attr('max') || opts.max; opts.step = $this.attr('step') || opts.step; $this.bind({ //bind the mouswheel event 'mousewheel.wl_Number': function (event, delta) { var opts = $this.data('wl_Number') || opts; if (opts.mousewheel) { event.preventDefault(); //delta must be 1 or -1 (different on macs and with shiftkey pressed) delta = (delta < 0) ? -1 : 1; //multiply with 10 if shift key is pressed if (event.shiftKey) delta *= 10; $.fn.wl_Number.methods.change.call($this[0], delta); } }, 'change.wl_Number': function () { var _this = $(this); //correct the input $.fn.wl_Number.methods.correct.call($this[0]); //callback _this.data('wl_Number').onChange.call($this[0], _this.val()); } }); } else { } if (opts) $.extend($this.data('wl_Number'), opts); }); }; $.fn.wl_Number.defaults = { step: 1, decimals: 0, start: 0, min: null, max: null, mousewheel: true, onChange: function (value) {}, onError: function (value) {} }; $.fn.wl_Number.version = '1.0'; $.fn.wl_Number.methods = { correct: function () { var $this = $(this), //replace ',' with '.' because in some countries comma is the separator val = $this.val().replace(/,/g, '.'); if (val) $.fn.wl_Number.methods.printValue.call(this, parseFloat(val)); }, change: function (delta) { var $this = $(this), //the current value _current = $this.val() || $this.data('wl_Number').start, //calculate the new value _new = parseFloat(_current, 10) + (delta * $this.data('wl_Number').step); $.fn.wl_Number.methods.printValue.call(this, _new); $this.trigger('change.wl_Number'); }, printValue: function (value) { var $this = $(this), opts = $this.data('wl_Number') || opts; //is not a number if (isNaN(value) && value != '') { //callback opts.onError.call(this, $this.val()); //write '0', focus and select it $this.val(0).focus().select(); $this.trigger('change.wl_Number'); return; } //don't go over min and max values if (opts.min != null) value = Math.max(opts.min, value); if (opts.max != null) value = Math.min(opts.max, value); //decimals? use parseFloat if yes or round the value if it is an integer (no decimals) (opts.decimals) ? value = parseFloat(value, opts.decimals).toFixed(opts.decimals) : value = Math.round(value); //write value $this.val(value); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Number.defaults[key] !== undefined || $.fn.wl_Number.defaults[key] == null) { $this.data('wl_Number')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Form v 1.3.5 by revaxarts.com /* description: handles the serialization, unserialization and sending /* of a form /* dependency: $.confirm, wl_Number*, wl_Slider*, wl_Date*, wl_Value*, /* wl_Password*, wl_File*, wl_Multiselect* /* * only when fields are within the form /*----------------------------------------------------------------------*/ $.fn.wl_Form = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Form.methods[method]) { return $.fn.wl_Form.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Form')) { var opts = $.extend({}, $this.data('wl_Form'), method); } else { var opts = $.extend({}, $.fn.wl_Form.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } //all fields within that form var $inputs = $this.find('input,textarea,select,div.date,div.slider'), //$required = $inputs.filter('[required]'), //Does not work on IE7/8 $submitbtn = (opts.submitButton instanceof jQuery) ? opts.submitButton : $this.find(opts.submitButton), $resetbtn = (opts.resetButton instanceof jQuery) ? opts.resetButton : $this.find(opts.resetButton); if (!$this.data('wl_Form')) { $this.data('wl_Form', {}); //get options from the forms nativ attributes opts.action = $this.attr('action') || opts.action; opts.method = $this.attr('method') || opts.method; //prevent the forms default behaviour $this.bind({ 'submit.wl_Form': function (event) { event.preventDefault(); return false; }, 'reset.wl_Form': function (event) { event.preventDefault(); return false; } }); //bind the click action to the submit button $submitbtn.bind('click.wl_Form', function (event) { $.fn.wl_Form.methods.submit.call($this[0]); return false; }); //bind the click action to the submit button $resetbtn.bind('click.wl_Form', function (event) { $.fn.wl_Form.methods.reset.call($this[0]); return false; }); //iterate through the fields $inputs.each(function () { var _this = $(this), _row = _this.closest('section'), //the label should be nice readable _label = _row.find('label').eq(0).html() || this.name || this.id || ''; //This is required because IEs < 9 can't handle this as expected if (_this.is('[required]') || typeof _this.prop('required') == 'string') { _this.data('required', true); //only append one required asterix if(!_row.find('span.required').length) _row.find('label').eq(0).append('&nbsp;<span class="required">&nbsp;</span>'); } //add the label to the field (and strip out unwanted info) _this.data('wl_label', _label.replace(/<span>([^<]+)<\/span>|<([^>]+)\/?>/g, '')); //set initial data for Form reset _this.data('wl_initdata', function () { var _type = _this.attr("type"); if (_type == "checkbox" || _type == "radio") { return _this.prop("checked"); //datepicker } else if (_this.data('wl_Date')) { return _this.datepicker('getDate'); //slider } else if (_this.data('wl_Slider')) { if (!_this.data('wl_Slider').connect) { if (_this.data('wl_Slider').range) { return _this.slider('option', 'values'); } else { return _this.slider('option', 'value'); } } //other fields } else { return _this.val(); } }()); }); //set the form status after the submit button if status is true if (opts.status && !$submitbtn.closest('div').is('span.wl_formstatus')) { $submitbtn.closest('div').append('<span class="wl_formstatus"></span>'); } //parse the location.search parameters if (opts.parseQuery) { $this.wl_Form.methods.unserialize.call(this); } } else { } if (opts) $.extend($this.data('wl_Form'), opts); }); }; $.fn.wl_Form.defaults = { submitButton: 'button.submit', resetButton: 'button.reset', method: 'post', action: null, ajax: true, serialize: false, parseQuery: true, dataType: 'text', status: true, sent: false, confirmSend: true, text: { required: 'This field is required', valid: 'This field is invalid', password: 'This password is to short', passwordmatch: 'This password doesn\'t match', fileinqueue: 'There is at least one file in the queue', incomplete: 'Please fill out the form correctly!', send: 'send form...', sendagain: 'send again?', success: 'form sent!', error: 'error while sending!', parseerror: 'Can\'t unserialize query string:\n %e' }, tooltip: { gravity: 'nw' }, onRequireError: function (element) {}, onValidError: function (element) {}, onPasswordError: function (element) {}, onFileError: function (element) {}, onBeforePrepare: function () {}, onBeforeSubmit: function (data) {}, onReset: function () {}, onComplete: function (textStatus, jqXHR) {}, onError: function (textStatus, error, jqXHR) {}, onSuccess: function (data, textStatus, jqXHR) {} }; $.fn.wl_Form.version = '1.3.5'; $.fn.wl_Form.methods = { disable: function () { var $this = $(this), _inputs = $this.find($this.data('wl_Form').submitButton + ',input,textarea,select,div.date,div.slider'); //iterate through all fields _inputs.each(function () { var _this = $(this); if (_this.is('div')) { //disable slider and datefields if (_this.is('div.slider') && _this.data('wl_Slider')) { _this.wl_Slider('disable'); } else if (_this.is('div.date') && _this.data('wl_Date')) { _this.wl_Date('disable'); } } else { //disable normal fields _this.prop('disabled', true); } }); $this.data('wl_Form').disabled = true; }, enable: function () { var $this = $(this), _inputs = $this.find($this.data('wl_Form').submitButton + ',input,textarea,select,div.date,div.slider'); //iterate through all fields _inputs.each(function () { var _this = $(this); if (_this.is('div')) { //enable slider and datefields if (_this.is('div.slider') && _this.data('wl_Slider')) { _this.wl_Slider('enable'); } else if (_this.is('div.date') && _this.data('wl_Date')) { _this.wl_Date('enable'); } } else { //enable normal fields _this.prop('disabled', false); } }); $this.data('wl_Form').disabled = false; }, reset: function () { var $this = $(this), _inputs = $this.find('input,textarea,select,div.date,div.slider'); //trigger callback if ($this.data('wl_Form').onReset.call($this[0]) === false) return false; //remove all errorclasses $this.find('section.error').removeClass('error'); //iterate through all fields _inputs.each(function () { var _this = $(this), _type = _this.attr("type"); if (_type == "checkbox") { _this.prop("checked", _this.data('wl_initdata')).trigger('change'); //radio buttons } else if (_type == "radio") { _this.prop("checked", _this.data('wl_initdata')).trigger('change'); //datepicker } else if (_this.data('wl_Date')) { _this.datepicker('setDate', _this.data('wl_initdata')); //time } else if (_this.data('wl_Time')) { _this.val(_this.data('wl_initdata')); //multi select } else if (_this.data('wl_Multiselect')) { _this.wl_Multiselect('clear'); _this.wl_Multiselect('select', _this.data('wl_initdata')); //slider } else if (_this.data('wl_Slider')) { if (!_this.data('wl_Slider').connect) { if (_this.data('wl_Slider').range) { _this.slider('option', 'values', $.parseData(_this.data('wl_initdata'))); } else { _this.slider('option', 'value', _this.data('wl_initdata')); } _this.wl_Slider("change"); _this.wl_Slider("slide"); } //prevent file inputs to get triggered } else if (_this.data('wl_File')) { _this.wl_File('reset'); //wysiwyg editor } else if (_this.data('wl_Editor')) { _this.val(_this.data('wl_initdata')).wysiwyg("setContent", _this.data('wl_initdata')); //colorpicker } else if (_this.data('wl_Color')) { _this.wl_Color('set', 'value', _this.data('wl_initdata')); //other fields } else { _this.val(_this.data('wl_initdata')).trigger('change'); //placeholder text needs some CSS if (_this.is('[placeholder]')) { if (_this.data('wl_initdata') == "" || _this.data('wl_initdata') == _this.attr("placeholder")) { _this.addClass("placeholder").val(_this.attr("placeholder")).data("uservalue", false); } else { _this.removeClass("placeholder").data("uservalue", true); } } } }); }, submit: function () { //collect some required info var $this = $(this), _data = {}, _opts = $this.data('wl_Form'), _inputs = $this.find('input,textarea,select,div.date,div.slider'), _statusel = $this.find('.wl_formstatus'), _requiredelements = Array(), _validelements = Array(), _passwordelements = Array(), _fileelements = Array(), _submit = true, _submitbtn = (_opts.submitButton instanceof jQuery) ? _opts.submitButton : $this.find(_opts.submitButton), _callbackReturn, _addHiddenField = function (after, id, name, value) { if (!$('#' + id).length) $('<input>', { type: 'hidden', id: id, name: name, value: value }).insertAfter(after); }; //status reset _statusel.text(""); //iterate through all fields _inputs.each(function (i, e) { var _this = $(this), _row = _this.closest('section'); //remove all error classes _row.removeClass('error'); //if a placeholder is set remove the value temporary if (_this.prop('placeholder') && _this.val() == _this.prop('placeholder') && !_this.data('uservalue')) { _this.val(''); } //if field is required and a value isn't set or it is a checkbox and the checkbox isn't checked or it is a file upload with no files if (_this.data('required')) { if ((!_this.val() || _this.is(':checkbox') && !_this.is(':checked')) && !_this.data('wl_File')) { _requiredelements.push(_this); _submit = false; } else if (_this.is(':radio')) { //get all checked radios; var checked = $('input[name='+_this.attr('name')+']:checked'); //no radio button is selected if(!checked.length){ _requiredelements.push(_this); _submit = false; } } else if (_this.data('wl_File') && !_this.data('wl_File').files.length) { //use the filepool for the tooltip _requiredelements.push(_row.find('.fileuploadpool').eq(0)); _submit = false; } } //if it is a valid field but it isn't valid if (_this.data('wl_Valid') && !_this.data('wl_Valid').valid) { _validelements.push(_this); _submit = false; } //check if there is a file in the queue if (_this.data('wl_File') && !$.isEmptyObject(_this.data('wl_File').queue)) { //use the filepool for the tooltip _fileelements.push(_row.find('.fileuploadpool').eq(0)); _submit = false; } //if it is a password if (_this.data('wl_Password')) { var value = _this.val(); //password confirmation is set and the confirmation isn't equal the password or the password is shorter than the minlength of the password field if ((_this.data('wl_Password').confirm && _this.data('wl_Password').connect && value != $('#' + _this.data('wl_Password').connect).val()) || (value && value.length < _this.data('wl_Password').minLength)) { //_row.addClass('error'); _passwordelements.push(_this); _submit = false; } }; }); //if some of the above errors occures if (!_submit) { //iterate through all required fields $.each(_requiredelements, function (i, e) { var _row = e.closest('section'); _row.addClass('error'); //callback _opts.onRequireError.call(e[0], e); //store the old tooltip if set var orgtitle = e.attr('original-title'); if(orgtitle) e.removeData('tipsy').removeAttr('original-title'); //use tipsy for a tooltip e.tipsy($.extend({}, config.tooltip, _opts.tooltip, { trigger: 'manual', fallback: e.data('errortext') || _opts.text.required })); e.tipsy('show'); //hide the tooltip on every radio button if(e.is(':radio')){ var radiosiblings = $('input[name='+e.attr('name')+']'); radiosiblings.bind('focus.tooltip, click.tooltip, change.tooltip', function () { e.unbind('focus.tooltip, click.tooltip, change.tooltip').tipsy('hide'); //restore the old tooltip if(orgtitle) e.attr('title',orgtitle).tipsy(config.tooltip); }); }else{ //hide tooltip on fieldfocus or change e.bind('focus.tooltip, click.tooltip, change.tooltip', function () { $(this).unbind('focus.tooltip, click.tooltip, change.tooltip').tipsy('hide'); //restore the old tooltip if(orgtitle) e.attr('original-title',orgtitle).tipsy(config.tooltip); }); } }); //iterate through all valid fields $.each(_validelements, function (i, e) { var _row = e.closest('section'); //highlight the row _row.addClass('error'); //callback _opts.onValidError.call(e[0], e); //store the old tooltip if set var orgtitle = e.attr('original-title'); if(orgtitle) e.removeData('tipsy').removeAttr('original-title'); //use tipsy for a tooltip e.tipsy($.extend({}, config.tooltip, _opts.tooltip, { trigger: 'manual', fallback: e.data('errortext') || e.data('wl_Valid').errortext || _opts.text.valid })); e.tipsy('show'); //hide tooltip on fieldfocus e.bind('focus.tooltip, click.tooltip', function () { $(this).unbind('focus.tooltip, click.tooltip').tipsy('hide'); //restore the old tooltip if(orgtitle) e.attr('original-title',orgtitle).tipsy(config.tooltip); }); }); //iterate through all password fields $.each(_passwordelements, function (i, e) { var text = '', value = e.val(), _row = e.closest('section'); //highlight the row _row.addClass('error'); //store the old tooltip if set var orgtitle = e.attr('original-title'); if(orgtitle) e.removeData('tipsy').removeAttr('original-title'); //confirmation is set if (e.data('wl_Password').confirm) { var connect = $('#' + e.data('wl_Password').connect); //but password is not equal confimration if (value != connect.val()) { //tipsy on the confirmation field connect.tipsy($.extend({}, config.tooltip, _opts.tooltip, { trigger: 'manual', fallback: connect.data('errortext') || _opts.text.passwordmatch })); connect.tipsy('show'); //hide tooltip in fieldfocus connect.bind('focus.tooltip, click.tooltip', function () { $(this).unbind('focus.tooltip, click.tooltip').tipsy('hide'); //restore the old tooltip if(orgtitle) e.attr('original-title',orgtitle).tipsy(config.tooltip); }); } } //length is to short if (value.length < e.data('wl_Password').minLength) { _opts.onPasswordError.call(e[0], e); //tipsy e.tipsy($.extend({}, config.tooltip, _opts.tooltip, { trigger: 'manual', fallback: e.data('errortext') || _opts.text.password })); e.tipsy('show'); //hide tooltip in fieldfocus e.bind('focus.tooltip, click.tooltip', function () { $(this).unbind('focus.tooltip, click.tooltip').tipsy('hide'); //restore the old tooltip if(orgtitle) e.attr('original-title',orgtitle).tipsy(config.tooltip); }); } }); //iterate through all file upload fields $.each(_fileelements, function (i, e) { var _row = e.closest('section'); //highlight the row _row.addClass('error'); //callback _opts.onFileError.call(e[0], e); //use tipsy for a tooltip e.tipsy($.extend({}, config.tooltip, _opts.tooltip, { trigger: 'manual', fallback: e.data('errortext') || _opts.text.fileinqueue })); e.tipsy('show'); //hide tooltip on fieldfocus or change e.bind('focus.tooltip, click.tooltip, change.tooltip', function () { $(this).unbind('focus.tooltip, click.tooltip, change.tooltip').tipsy('hide'); }); }); //Set status message _statusel.text(_opts.text.incomplete); return false; } //confirmation is required if the form was allready sent if (_opts.confirmSend && _opts.sent === true) { $.confirm(_opts.text.sendagain, function () { _opts.sent = false; $.fn.wl_Form.methods.submit.call($this[0]); }); return false; } //callback can return false if (_opts.onBeforePrepare.call($this[0]) === false) { return false; } //iterate through all fields and prepare data _inputs.each(function (i, e) { var _el = $(e), key = _el.attr('name') || e.id, value = null; //datepicker if (_el.data('wl_Date')) { var connect = $this.find('input[data-connect=' + e.id + ']').eq(0), dateobj = new Date(_el.datepicker('getDate')), //format: YYYY-MM-DD date = dateobj.getFullYear() + '-' + $.leadingZero(dateobj.getMonth() + 1) + '-' + $.leadingZero(dateobj.getDate()); if (dateobj.getTime()) { //is connected to a timefield if (connect.length) { value = date + ' ' + (connect.data('wl_Time').time || '00:00'); //insert a hidden field for non ajax submit if (!_opts.ajax) _addHiddenField(_el, key + '_wlHidden', key, value); } else { value = date; //correct the format on nativ submit if (!_opts.ajax) _el.val(value); } } //inline Date needs a hidden input for nativ submit if (!_opts.ajax && _el.is('div')) { _addHiddenField(_el, key + '_wlHidden', key, value) } _data[key] = value; //slider } else if (_el.data('wl_Slider')) { //if it is connected we have a input field too so skip it if (!_el.data('wl_Slider').connect) { if (_el.data('wl_Slider').range !== true) { value = _el.slider('option', 'value'); //insert a hidden field for non ajax submit if (!_opts.ajax) _addHiddenField(_el, key + '_wlHidden', key, value); } else { value = _el.slider('option', 'values'); //insert hidden fields for non ajax submit if (!_opts.ajax) { for (var i = value.length - 1; i >= 0; i--) { _addHiddenField(_el, key + '_' + i + '_wlHidden', key + '[]', value[i]); } } } _data[key] = value; } else { //form needs a name attribute for nativ submit if (!_opts.ajax) { if (_el.data('wl_Slider').range !== true) { var input = $('#' + _el.data('wl_Slider').connect); if (!input.attr('name')) input.attr('name', _el.data('wl_Slider').connect); } else { var connect = $.parseData(_el.data('wl_Slider').connect, true); var input1 = $('#' + connect[0]); var input2 = $('#' + connect[1]); if (!input1.attr('name')) input1.attr('name', connect[0]); if (!input2.attr('name')) input2.attr('name', connect[1]); } } } //wysiwyg editor } else if (_el.data('wl_Editor')) { //copy the content to the textarea _el.wysiwyg('save'); _data[key] = _el.val(); //file upload } else if (_el.data('wl_File')) { _data[key] = _el.data('wl_File').files; //if no file was uploaded value is null if ($.isEmptyObject(_data[key])) { _data[key] = null; //insert a hidden field for non ajax submit if (!_opts.ajax) _addHiddenField(_el, key + '_wlHidden', key, 'null'); } else { //insert hidden fields for non ajax submit if (!_opts.ajax) { for (var i = _data[key].length - 1; i >= 0; i--) { _addHiddenField(_el, key + '_' + i + '_wlHidden', key + '[]', _data[key][i]); } } } //timefield } else if (_el.data('wl_Time')) { //if it is connected we have a datefield too so skip it if (!_el.data('wl_Time').connect) { _data[key] = _el.data('wl_Time').time; //insert a hidden field for non ajax submit if (!_opts.ajax) _addHiddenField(_el, key + '_wlHidden', key, _el.data('wl_Time').time); } //password } else if (_el.data('wl_Password')) { //only add if it's not the confirmation field if (!_el.data('wl_Password').confirmfield) _data[key] = _el.val(); if (!_opts.ajax && _el.data('wl_Password').confirmfield) _el.prop('disabled', true); //radio buttons } else if (_el.is(':radio')) { if (_el.is(':checked')) { //use the value attribute if present or id as fallback (new in 1.1) _data[key] = (_el.val() != 'on') ? _el.val() : e.id; } //checkbox } else if (_el.is(':checkbox')) { //if checkbox name has '[]' at the and we need an array if (/\[\]$/.test(key)) { _data[key] = _data[key] || []; //checkbox is checked if (_el.is(':checked')) { //if value = 'on' value isn't set use id or val if id isn't defined var val = _el.val(); _data[key].push((val != 'on') ? val : _el.attr('id') || val); } } else { //use value if set and true or false if not set if (_el.is(':checked')) { var val = _el.val(); _data[key] = (val != 'on') ? val : _el.is(':checked') || (_el.attr('id') || val); }else{ //use always 0 (false) if unchecked _data[key] = 0; } } //convert true to 1 and false to 0 if(_data[key] === true) { _data[key] = 1; }else if(_data[key] === false) { _data[key] = 0; } //insert a hidden field for non ajax submit if (!_opts.ajax) _addHiddenField(_el, key + '_wlHidden', key, _data[key]); //number field } else if (_el.data('wl_Number')) { value = _el.val(); if (isNaN(value)) { value = null; } _data[key] = value; //other fields } else { var val = _el.val(); //if name attribute has '[]' at the and we need an array if (/\[\]$/.test(key) && !$.isArray(val)) { _data[key] = _data[key] || []; _data[key].push(val); } else { _data[key] = val; } } }); //add the name attribut of the submit button to the data (native behavior) var submitbtnname = _submitbtn.attr('name'); if(submitbtnname){ _data[submitbtnname] = _submitbtn.attr('value') || true; //insert a hidden field for non ajax submit if (!_opts.ajax) _addHiddenField(_submitbtn, submitbtnname + '_wlHidden', submitbtnname, _data[submitbtnname]); } //callback _callbackReturn = _opts.onBeforeSubmit.call($this[0], _data); //can return false to prevent sending if (_callbackReturn === false) { return false; //can return an object to modifie the _data } else if (typeof _callbackReturn == 'object') { _data = _callbackReturn; } //should we serialize it? (key=value&key2=value2&...) if (_opts.serialize) { _data = $.param(_data); } //set status text _statusel.text(_opts.text.send); //send the form natively if (!_opts.ajax) { $this.unbind('submit.wl_Form'); $this.submit(); return false; } //now disable it $.fn.wl_Form.methods.disable.call(this); //send the form $.ajax({ url: _opts.action, type: _opts.method, data: _data, dataType: _opts.dataType, //callback on success success: function (data, textStatus, jqXHR) { _statusel.textFadeOut(_opts.text.success); _opts.onSuccess.call($this[0], data, textStatus, jqXHR); }, //callback on complete complete: function (jqXHR, textStatus) { $.fn.wl_Form.methods.enable.call($this[0]); _opts.sent = true; _opts.onComplete.call($this[0], textStatus, jqXHR); }, //callback on error error: function (jqXHR, textStatus, error) { _statusel.text(_opts.text.error); _opts.onError.call($this[0], textStatus, error, jqXHR); } }); }, unserialize: function (string) { var $this = $(this), _searchquery = string || location.search.substr(1); //parse only if we have something to parse if (_searchquery) { //could throw an error because its an userinput try { //prepare string to get a clean array with with key => value values = decodeURIComponent(_searchquery).split('&'); var serialized_values = []; $.each(values, function () { var properties = this.split("="), key = properties.shift(); properties = properties.join('='); if ((typeof key !== 'undefined') && (typeof properties !== 'undefined')) { key = key.replace(/\+/g, " "); //handle Array if (/\[\]$/.test(key)) { key = key.replace('[]', ''); serialized_values[key] = serialized_values[key] || []; serialized_values[key].push(properties.replace(/\+/g, " ")); } else { serialized_values[key] = properties.replace(/\+/g, " "); } } }); values = serialized_values; // Iterate through each element $this.find("input,textarea,select,div.date,div.slider").each(function () { var _this = $(this), _type = _this.attr("type"), tag_name = this.name || this.id; //remove '[]' if present if (/\[\]$/.test(tag_name)) tag_name = tag_name.replace('[]', ''); // Set the values to field if (values[tag_name] != null) { //chechboxes if (_type == "checkbox") { _this.data('wl_initdata', (values[tag_name] == 'true')).prop("checked", (values[tag_name] == 'true')); //radio buttons } else if (_type == "radio") { $('input[id="' + values[tag_name] + '"]').data('wl_initdata', true).attr("checked", true); //password } else if (_type == "password") { //don't write passwords for security reasons //_this.val(values[tag_name]).trigger('change') //datepicker } else if (_this.data('wl_Date') && _this.is('input')) { if (/(\d\d:\d\d)$/.test(values[tag_name])) { var time = values[tag_name].substr(11), date = values[tag_name].substr(0, 10); _this.data('wl_initdata', new Date(date)).datepicker('setDate', new Date(date)); $('input[data-connect="' + tag_name + '"]').data('wl_initdata', time).val(time).data('wl_Time').time = time; } else { _this.data('wl_initdata', new Date(values[tag_name])).datepicker('setDate', new Date(values[tag_name])); } //inline datepicker } else if (_this.data('wl_Date') && _this.is('div')) { _this.data('wl_initdata', new Date(values[tag_name])).datepicker('setDate', new Date(values[tag_name])); //colorpicker } else if (_this.data('wl_Color')) { _this.data('wl_initdata', values[tag_name]).wl_Color('set', 'value', values[tag_name]); //Slider } else if (_this.data('wl_Slider')) { if (!_this.data('wl_Slider').connect) { if (_this.data('wl_Slider').range) { _this.slider('option', 'values', $.parseData(values[tag_name])); } else { _this.slider('option', 'value', values[tag_name]); } _this.data('wl_initdata', values[tag_name]); _this.wl_Slider("change"); _this.wl_Slider("slide"); } //Multiselect } else if (_this.data('wl_Multiselect')) { _this.data('wl_initdata', values[tag_name]).wl_Multiselect('select', values[tag_name]); //wysiwyg editor } else if (_this.data('wl_Editor')) { _this.data('wl_initdata', values[tag_name]).val(values[tag_name]).wysiwyg("setContent", values[tag_name]); //other fields } else { _this.data('wl_initdata', values[tag_name]).val(values[tag_name]).trigger('change'); } } }); } catch (e) { //call a message to prevent crashing the application $.msg($this.data('wl_Form').text.parseerror.replace('%e', e)); } } }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Form.defaults[key] !== undefined && $.fn.wl_Form.defaults[key] !== null) { $this.data('wl_Form')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Gallery v 1.3 by revaxarts.com /* description: makes a sortable gallery /* dependency: jQuery UI sortable /*----------------------------------------------------------------------*/ $.fn.wl_Gallery = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Gallery.methods[method]) { return $.fn.wl_Gallery.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Gallery')) { var opts = $.extend({}, $this.data('wl_Gallery'), method); } else { var opts = $.extend({}, $.fn.wl_Gallery.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } var $items = $this.find('a'); if (!$this.data('wl_Gallery')) { $this.data('wl_Gallery', {}); //make it sortable $this.sortable({ containment: $this, opacity: 0.8, distance: 5, handle: 'img', forceHelperSize: true, placeholder: 'sortable_placeholder', forcePlaceholderSize: true, start: function (event, ui) { $this.dragging = true; ui.item.trigger('mouseleave'); }, stop: function (event, ui) { $this.dragging = false; }, update: function (event, ui) { var _a = ui.item.find('a').eq(0); //callback action opts.onMove.call($this[0], ui.item, _a.attr('href'), _a.attr('title'), $this.find('li')); } }); opts.images = []; //add the rel attribut for the fancybox $items.attr('rel', opts.group).fancybox(opts.fancybox); $items.each(function () { var _this = $(this), _image = _this.find('img'), _append = $('<span>'); //add edit and delete buttons if(opts.editBtn) _append.append('<a class="edit">Edit</a>'); if(opts.deleteBtn) _append.append('<a class="delete">Delete</a>'); if(opts.deleteBtn || opts.editBtn) _this.append(_append); //store images within the DOM opts.images.push({ image: _image.attr('rel') || _image.attr('src'), thumb: _image.attr('src'), title: _image.attr('title'), description: _image.attr('alt') }); }); if(opts.deleteBtn || opts.editBtn){ //bind the mouseenter animation $this.delegate('li', 'mouseenter', function (event) { if (!$this.dragging) { var _this = $(this), _img = _this.find('img'), _pan = _this.find('span'); _img.animate({ top: -20 }, 200); _pan.animate({ top: 80 }, 200); } //bind the mouseleave animation }).delegate('li', 'mouseleave', function (event) { var _this = $(this), _img = _this.find('img'), _pan = _this.find('span'); _img.animate({ top: 0 }, 200); _pan.animate({ top: 140 }, 200); }); } if(opts.editBtn){ //bind the edit event to the button $this.find('a.edit').bind('click.wl_Gallery touchstart.wl_Gallery', function (event) { event.stopPropagation(); event.preventDefault(); var opts = $this.data('wl_Gallery') || opts, _this = $(this), _element = _this.parent().parent().parent(), _href = _element.find('a')[0].href, _title = _element.find('a')[0].title; //callback action opts.onEdit.call($this[0], _element, _href, _title); return false; }); } if(opts.deleteBtn){ //bind the delete event to the button $this.find('a.delete').bind('click.wl_Gallery touchstart.wl_Gallery', function (event) { event.stopPropagation(); event.preventDefault(); var opts = $this.data('wl_Gallery') || opts, _this = $(this), _element = _this.parent().parent().parent(), _href = _element.find('a')[0].href, _title = _element.find('a')[0].title; //callback action opts.onDelete.call($this[0], _element, _href, _title); return false; }); } } else { } if (opts) $.extend($this.data('wl_Gallery'), opts); }); }; $.fn.wl_Gallery.defaults = { group: 'wl_gallery', editBtn: true, deleteBtn: true, fancybox: {}, onEdit: function (element, href, title) {}, onDelete: function (element, href, title) {}, onMove: function (element, href, title, newOrder) {} }; $.fn.wl_Gallery.version = '1.3'; $.fn.wl_Gallery.methods = { set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Gallery.defaults[key] !== undefined || $.fn.wl_Gallery.defaults[key] == null) { $this.data('wl_Gallery')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_File v 1.2 by revaxarts.com /* description:makes a fancy html5 file upload input field /* dependency: jQuery File Upload Plugin 5.0.2 /*----------------------------------------------------------------------*/ $.fn.wl_File = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_File.methods[method]) { return $.fn.wl_File.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_File')) { var opts = $.extend({}, $this.data('wl_File'), method); } else { var opts = $.extend({}, $.fn.wl_File.defaults, method, $this.data()); } } else { try { return $this.fileupload(method, args[1], args[2], args[3], args[4]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_File')) { $this.data('wl_File', {}); //The queue, the upload files and drag&drop support of the current browser var queue = {}, files = [], queuelength = 0, tempdata, maxNumberOfFiles, dragdropsupport = isEventSupported('dragstart') && isEventSupported('drop') && !! window.FileReader; //get native multiple attribute or use defined one opts.multiple = ($this.is('[multiple]') || typeof $this.prop('multiple') === 'string') || opts.multiple; //used for the form opts.queue = {}; opts.files = []; if (typeof opts.allowedExtensions === 'string') opts.allowedExtensions = $.parseData(opts.allowedExtensions); //the container for the buttons opts.ui = $('<div>', { 'class': 'fileuploadui' }).insertAfter($this); //start button only if autoUpload is false if (!opts.autoUpload) { opts.uiStart = $('<a>', { 'class': 'btn small fileupload_start', 'title': opts.text.start }).html(opts.text.start).bind('click', function () { $.each(queue, function (file) { upload(queue[file].data); }); }).appendTo(opts.ui); } //cancel/remove all button opts.uiCancel = $('<a>', { 'class': 'btn small fileupload_cancel', 'title': opts.text.cancel_all }).html(opts.text.cancel_all).appendTo(opts.ui).bind('click', function () { var _this = $(this), el = opts.filepool.find('li'); el.addClass('error'); //IE and Opera delete the data on submit so we store it temporarily if (!$this.data('wl_File')) $this.data('wl_File', tempdata); files = $this.data('wl_File').files = []; queuelength = 0; $.each(queue, function (name) { if (queue[name]) { queue[name].fileupload.abort(); delete queue[name]; } }); el.delay(700).fadeOut(function () { //trigger a change for required inputs opts.filepool.trigger('change'); _this.text(opts.text.cancel_all).attr('title', opts.text.cancel_all); $(this).remove(); }); //trigger delete event opts.onDelete.call($this[0], $.map(el,function(k,v){return $(k).data('fileName');})); }); //filepool and dropzone opts.filepool = $('<ul>', { 'class': 'fileuploadpool' }).insertAfter($this) //cancel one files .delegate('a.cancel', 'click', function () { var el = $(this).parent(), name = el.data('fileName'); //IE and Opera delete the data on submit so we store it temporarily if (!$this.data('wl_File')) $this.data('wl_File', tempdata); //remove clicked file from the list $this.data('wl_File').files = files = $.map(files, function (filename) { if (filename != name) return filename; }); //abort upload queue[name].fileupload.abort(); //remove from queue delete queue[name]; queuelength--; el.addClass('error').delay(700).fadeOut(); //trigger cancel event opts.onCancel.call($this[0], name); //trigger a change for required inputs opts.filepool.trigger('change'); }) //remove file from list .delegate('a.remove', 'click', function () { var el = $(this).parent(), name = el.data('fileName'); if (!$this.data('wl_File')) $this.data('wl_File', tempdata); //remove clicked file from the list $this.data('wl_File').files = files = $.map(files, function (filename) { if (filename != name) return filename; }); el.fadeOut(); //trigger cancel event opts.onDelete.call($this[0], [name]); //trigger a change for required inputs opts.filepool.trigger('change'); }) //add some classes to the filepool .addClass((!opts.multiple) ? 'single' : 'multiple').addClass((dragdropsupport) ? 'drop' : 'nodrop'); //call the fileupload plugin $this.fileupload({ url: opts.url, dropZone: (opts.dragAndDrop) ? opts.filepool : null, fileInput: $this, //required singleFileUploads: true, sequentialUploads: opts.sequentialUploads, //must be an array paramName: opts.paramName + '[]', formData: opts.formData, add: function (e, data) { //cancel current upload and remove item on single upload field if (!opts.multiple) { opts.uiCancel.click(); opts.filepool.find('li').remove(); } //add files to the queue $.each(data.files, function (i, file) { file.ext = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase(); queuelength++; var error = getError(file); if (!error) { //add file to queue and to filepool addFile(file, data); } else { //reduces queuelength queuelength--; //throw error opts.onFileError.call($this[0], error, file); } }); //IE and Opera delete the data on submit so we store it temporarily if ($this.data('wl_File')) { $this.data('wl_File').queue = queue; tempdata = $this.data('wl_File'); } else if (tempdata) { tempdata.queue = queue; } //trigger a change for required inputs opts.filepool.trigger('change'); opts.onAdd.call($this[0], e, data); //start upload if autoUpload is true if (opts.autoUpload) upload(data); }, send: function (e, data) { $.each(data.files, function (i, file) { queue[file.name].element.addClass(data.textStatus); queue[file.name].progress.width('100%'); queue[file.name].status.text(opts.text.uploading); }); //rename cancel button opts.uiCancel.text(opts.text.cancel_all).attr('title', opts.text.cancel_all); return opts.onSend.call($this[0], e, data); }, done: function (e, data) { $this.data('wl_File', tempdata); //set states for each file and push them in the list $.each(data.files, function (i, file) { if (queue[file.name]) { queue[file.name].element.addClass(data.textStatus); queue[file.name].progress.width('100%'); queue[file.name].status.text(opts.text.done); queue[file.name].cancel.removeAttr('class').addClass('remove').attr('title', opts.text.remove); if ($.inArray(file.name, files) == -1) { files.push(file.name); $this.data('wl_File').files = files; } //delete from the queue queuelength--; delete queue[file.name]; } }); opts.onDone.call($this[0], e, data); //empty queue => all files uploaded if ($.isEmptyObject(queue)) { //trigger a change for required inputs opts.filepool.trigger('change'); opts.uiCancel.text(opts.text.remove_all).attr('title', opts.text.remove_all); opts.onFinish.call($this[0], e, data); } }, fail: function (e, data) { opts.onFail.call($this[0], e, data); }, always: function (e, data) { opts.onAlways.call($this[0], e, data); }, progress: function (e, data) { //calculate progress for each file $.each(data.files, function (i, file) { if (queue[file.name]) { var percentage = Math.round(parseInt(data.loaded / data.total * 100, 10)); queue[file.name].progress.width(percentage + '%'); queue[file.name].status.text(opts.text.uploading + percentage + '%'); } }); opts.onProgress.call($this[0], e, data); }, progressall: function (e, data) { opts.onProgressAll.call($this[0], e, data); }, start: function (e) { opts.onStart.call($this[0], e); }, stop: function (e) { opts.onStop.call($this[0], e); }, change: function (e, data) { opts.onChange.call($this[0], e, data); }, drop: function (e, data) { opts.onDrop.call($this[0], e, data); }, dragover: function (e) { opts.onDragOver.call($this[0], e); } }); } else { } //upload method function upload(data) { $.each(data.files, function (i, file) { if (queue[file.name]) queue[file.name].fileupload = data.submit(); }); } //add files to the queue and to the filepool function addFile(file, data) { var name = file.name; var html = $('<li><span class="name">' + name + '</span><span class="progress"></span><span class="status">' + opts.text.ready + '</span><a class="cancel" title="' + opts.text.cancel + '">' + opts.text.cancel + '</a></li>').data('fileName', name).appendTo(opts.filepool); queue[name] = { element: html, data: data, progress: html.find('.progress'), status: html.find('.status'), cancel: html.find('.cancel') }; } //check for errors function getError(file) { if (opts.maxNumberOfFiles && (files.length >= opts.maxNumberOfFiles || queuelength > opts.maxNumberOfFiles)) { return { msg: 'maxNumberOfFiles', code: 1 }; } if (opts.allowedExtensions && $.inArray(file.ext, opts.allowedExtensions) == -1) { return { msg: 'allowedExtensions', code: 2 }; } if (typeof file.size === 'number' && opts.maxFileSize && file.size > opts.maxFileSize) { return { msg: 'maxFileSize', code: 3 }; } if (typeof file.size === 'number' && opts.minFileSize && file.size < opts.minFileSize) { return { msg: 'minFileSize', code: 4 }; } return null; } //took from the modernizr script (thanks paul) function isEventSupported(eventName) { var element = document.createElement('div'); eventName = 'on' + eventName; // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those var isSupported = eventName in element; if (!isSupported) { // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element if (!element.setAttribute) { element = document.createElement('div'); } if (element.setAttribute && element.removeAttribute) { element.setAttribute(eventName, ''); isSupported = typeof element[eventName] == 'function'; // If property was created, "remove it" (by setting value to `undefined`) if (typeof element[eventName] != undefined) { element[eventName] = undefined; } element.removeAttribute(eventName); } } element = null; return isSupported; } if (opts) $.extend($this.data('wl_File'), opts); }); }; $.fn.wl_File.defaults = { url: 'upload.php', autoUpload: true, paramName: 'files', multiple: false, allowedExtensions: false, maxNumberOfFiles: 0, maxFileSize: 0, minFileSize: 0, sequentialUploads: false, dragAndDrop: true, formData: {}, text: { ready: 'ready', cancel: 'cancel', remove: 'remove', uploading: 'uploading...', done: 'done', start: 'start upload', add_files: 'add files', cancel_all: 'cancel upload', remove_all: 'remove all' }, onAdd: function (e, data) {}, onDelete:function(files){}, onCancel:function(file){}, onSend: function (e, data) {}, onDone: function (e, data) {}, onFinish: function (e, data) {}, onFail: function (e, data) {}, onAlways: function (e, data) {}, onProgress: function (e, data) {}, onProgressAll: function (e, data) {}, onStart: function (e) {}, onStop: function (e) {}, onChange: function (e, data) {}, onDrop: function (e, data) {}, onDragOver: function (e) {}, onFileError: function (error, fileobj) {} }; $.fn.wl_File.version = '1.2'; $.fn.wl_File.methods = { reset: function () { var $this = $(this), opts = $this.data('wl_File'); //default value if uniform is used if($.uniform)$this.next().html($.uniform.options.fileDefaultText); //empty file pool opts.filepool.empty(); //reset button opts.uiCancel.attr('title',opts.text.cancel_all).text(opts.text.cancel_all); //clear array $this.data('wl_File').files = []; }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_File.defaults[key] !== undefined || $.fn.wl_File.defaults[key] == null) { $this.data('wl_File')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Date v 1.0 by revaxarts.com /* description: extends the Datepicker /* dependency: jQuery Datepicker, mousewheel plugin /*----------------------------------------------------------------------*/ $.fn.wl_Date = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Date.methods[method]) { return $.fn.wl_Date.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Date')) { var opts = $.extend({}, $this.data('wl_Date'), method); } else { var opts = $.extend({}, $.fn.wl_Date.defaults, method, $this.data()); } } else { try { return $this.datepicker(method, args[1], args[2]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_Date')) { $this.data('wl_Date', {}); //call the jQuery UI datepicker plugin $this.datepicker(opts); //bind a mousewheel event to the input field $this.bind('mousewheel.wl_Date', function (event, delta) { if (opts.mousewheel) { event.preventDefault(); //delta must be 1 or -1 (different on macs and with shiftkey pressed) delta = (delta < 0) ? -1 : 1; //shift key is pressed if (event.shiftKey) { var _date = $this.datepicker('getDate'); //new delta is the current month day count (month in days) delta *= new Date(_date.getFullYear(), _date.getMonth() + 1, 0).getDate(); } //call the method $.fn.wl_Date.methods.changeDay.call($this[0], delta); } }); //value is set and has to get translated (self-explanatory) if (opts.value) { var today = new Date().getTime(); switch (opts.value) { case 'now': case 'today': $this.datepicker('setDate', new Date()); break; case 'next': case 'tomorrow': $this.datepicker('setDate', new Date(today + 864e5 * 1)); break; case 'prev': case 'yesterday': $this.datepicker('setDate', new Date(today + 864e5 * -1)); break; default: //if a valid number add them as days to the date field if (!isNaN(opts.value)) $this.datepicker('setDate', new Date(today + 864e5 * opts.value)); } } //disable if set if (opts.disabled) { $.fn.wl_Date.methods.disable.call(this); } } else { } if (opts) $.extend($this.data('wl_Date'), opts); }); }; $.fn.wl_Date.defaults = { value: null, mousewheel: true }; $.fn.wl_Date.version = '1.0'; $.fn.wl_Date.methods = { disable: function () { var $this = $(this); //disable the datepicker $this.datepicker('disable'); $this.data('wl_Date').disabled = true; }, enable: function () { var $this = $(this); //enable the datepicker $this.datepicker('enable'); $this.data('wl_Date').disabled = false; }, next: function () { //select next day $.fn.wl_Date.methods.changeDay.call(this, 1); }, prev: function () { //select previous day $.fn.wl_Date.methods.changeDay.call(this, -1); }, changeDay: function (delta) { var $this = $(this), _current = $this.datepicker('getDate') || new Date(); //set day to currentday + delta _current.setDate(_current.getDate() + delta); $this.datepicker('setDate', _current); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Date.defaults[key] !== undefined || $.fn.wl_Date.defaults[key] == null) { $this.data('wl_Date')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* Set some Standards /* This file not required! It just demonstrate how you can define /* standards in one configuration file /*----------------------------------------------------------------------*/ var config = { tooltip :{ gravity: 'nw', fade: false, opacity: 1, offset: 0 } }; //wrap them because of some jQuery Elements $(document).ready(function() { if($.fn.wl_Alert) $.fn.wl_Alert.defaults = { speed: 500, sticky: false, onBeforeClose: function (element) {}, onClose: function (element) {} }; if($.fn.wl_Autocomplete) $.fn.wl_Autocomplete.defaults = { //check http://jqueryui.com/demos/autocomplete/ for all options }; if($.fn.wl_Breadcrump) $.fn.wl_Breadcrump.defaults = { start: 0, numbers: false, allownextonly: false, disabled: false, connect: null, onChange: function () {} }; if($.fn.wl_Calendar) $.fn.wl_Calendar.defaults = { //check http://arshaw.com/fullcalendar/ for all options }; if($.fn.wl_Chart) $.fn.wl_Chart.defaults = { width: null, height: 300, hideTable: true, tableBefore: false, data: {}, stack: false, type: 'lines', points: null, shadowSize: 2, fill: null, fillColor: null, lineWidth: null, legend: true, legendPosition: "ne", // or "nw" or "se" or "sw" tooltip: true, tooltipGravity: 'n', tooltipPattern: function (value, legend, label, id, itemobj) { return "value is " + value + " from " + legend + " at " + label + " (" + id + ")"; }, //tooltipPattern: "value is %1 from %2 at %3 (%4)", //also possible orientation: 'horizontal', colors: ['#b2e7b2', '#f0b7b7', '#b5f0f0', '#e8e8b3', '#efb7ef', '#bbb6f0'], flot: {}, onClick: function (value, legend, label, id, itemobj) {} }; if($.fn.wl_Color) $.fn.wl_Color.defaults = { mousewheel: true, onChange: function (hsb, rgb) {} }; if($.fn.wl_Date) $.fn.wl_Date.defaults = { value: null, mousewheel: true, //some datepicker standards dayNames : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], dayNamesMin : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], dayNamesShort : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], firstDay: 0, nextText: 'next', prevText: 'prev', currentText: 'Today', showWeek: true, dateFormat: 'mm/dd/yy' }; if($.confirm) $.confirm.defaults = { text:{ header: 'Please confirm', ok: 'Yes', cancel: 'No' } }; if($.prompt) $.prompt.defaults = { text:{ header: 'Please prompt', ok: 'OK', cancel: 'Cancel' } }; if($.alert) $.alert.defaults = { nativ: false, resizable: false, modal: true, text:{ header: 'Notification', ok: 'OK' } }; if($.fn.wl_Editor) $.fn.wl_Editor.defaults = { css: 'css/light/editor.css', buttons: 'bold|italic|underline|strikeThrough|justifyLeft|justifyCenter|justifyRight|justifyFull|highlight|colorpicker|indent|outdent|subscript|superscript|undo|redo|insertOrderedList|insertUnorderedList|insertHorizontalRule|createLink|insertImage|h1|h2|h3|h4|h5|h6|paragraph|rtl|ltr|cut|copy|paste|increaseFontSize|decreaseFontSize|html|code|removeFormat|insertTable', initialContent: '' }; if($.fn.wl_File) $.fn.wl_File.defaults = { url: 'upload.php', autoUpload: true, paramName: 'files', multiple: false, allowedExtensions: ['jpg','jpeg','gif','png','doc','zip','docx','txt','pdf'], maxNumberOfFiles: 0, maxFileSize: 0, minFileSize: 0, sequentialUploads: false, dragAndDrop: true, formData: {}, text: { ready: 'ready', cancel: 'cancel', remove: 'remove', uploading: 'uploading...', done: 'done', start: 'start upload', add_files: 'add files', cancel_all: 'cancel upload', remove_all: 'remove all' }, onAdd: function (e, data) {}, onDelete:function(files){}, onCancel:function(file){}, onSend: function (e, data) {}, onDone: function (e, data) {}, onFinish: function (e, data) {}, onFail: function (e, data) {}, onAlways: function (e, data) {}, onProgress: function (e, data) {}, onProgressAll: function (e, data) {}, onStart: function (e) {}, onStop: function (e) {}, onChange: function (e, data) {}, onDrop: function (e, data) {}, onDragOver: function (e) {}, onFileError: function (error, fileobj) { $.msg('file is not allowed: ' + fileobj.name, { header: error.msg + ' (' + error.code + ')' }); } }; if($.fn.wl_Fileexplorer) $.fn.wl_Fileexplorer.defaults = { url: 'elfinder/php/connector.php', toolbar: [ ['back', 'reload', 'open', 'select', 'quicklook', 'info', 'rename', 'copy', 'cut', 'paste', 'rm', 'mkdir', 'mkfile', 'upload', 'duplicate', 'edit', 'archive', 'extract', 'resize', 'icons', 'list', 'help'] ] }; if($.fn.wl_Form) $.fn.wl_Form.defaults = { submitButton: 'button.submit', resetButton: 'button.reset', method: 'post', action: null, ajax: true, serialize: false, parseQuery: true, dataType: 'text', status: true, sent: false, confirmSend: true, text: { required: 'This field is required', valid: 'This field is invalid', password: 'This password is to short', passwordmatch: 'This password doesn\'t match', fileinqueue: 'There is at least one file in the queue', incomplete: 'Please fill out the form correctly!', send: 'send form...', sendagain: 'send again?', success: 'form sent!', error: 'error while sending!', parseerror: 'Can\'t unserialize query string:\n %e' }, tooltip: { gravity: 'nw' }, onRequireError: function (element) {}, onValidError: function (element) {}, onPasswordError: function (element) {}, onFileError: function (element) {}, onBeforePrepare: function () {}, onBeforeSubmit: function (data) {}, onReset: function () {}, onComplete: function (textStatus, jqXHR) {}, onError: function (textStatus, error, jqXHR) {}, onSuccess: function (data, textStatus, jqXHR) {} }; if($.fn.wl_Gallery) $.fn.wl_Gallery.defaults = { group: 'wl_gallery', editBtn: true, deleteBtn: true, fancybox: {}, onEdit: function (element, href, title) {}, onDelete: function (element, href, title) {}, onMove: function (element, href, title, newOrder) {} }; if($.fn.wl_Multiselect) $.fn.wl_Multiselect.defaults = { height: 200, items: [], selected: [], showUsed: false, searchfield: true, onAdd: function (values) {}, onRemove: function (values) {}, onSelect: function (values) {}, onUnselect: function (values) {}, onSort: function (values) {} }; if($.fn.wl_Number) $.fn.wl_Number.defaults = { step: 1, decimals: 0, start: 0, min: null, max: null, mousewheel: true, onChange: function (value) {}, onError: function (value) {} }; if($.fn.wl_Password) $.fn.wl_Password.defaults = { confirm: true, showStrength: true, words: ['too short', 'bad', 'medium', 'good', 'very good', 'excellent'], minLength: 3, text: { confirm: 'please confirm', nomatch: 'password doesn\'t match' } }; if($.fn.wl_Slider) $.fn.wl_Slider.defaults = { min: 0, max: 100, step: 1, animate: false, disabled: false, orientation: 'horizontal', range: false, mousewheel: true, connect: null, tooltip: false, tooltipGravity: ['s','w'], tooltipPattern: "%n", onSlide: function (value) {}, onChange: function (value) {} }; if($.fn.wl_Time) $.fn.wl_Time.defaults = { step: 5, timeformat: 24, roundtime: true, time: null, value: null, mousewheel: true, onDateChange: function (offset) {}, onHourChange: function (offset) {}, onChange: function (value) {} }; if($.fn.wl_Valid) $.fn.wl_Valid.defaults = { errorClass: 'error', instant: true, regex: /.*/, minLength: 0, onChange: function ($this, value) {}, onError: function ($this, value) {} }; if($.fn.wl_Mail) $.fn.wl_Mail.defaults = { regex: /^([\w-]+(?:\.[\w-]+)*)\@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$|(\[?(\d{1,3}\.){3}\d{1,3}\]?)$/i, onChange: function (element, value) { element.val(value.toLowerCase()); } }; if($.fn.wl_URL) $.fn.wl_URL.defaults = { regex: /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w]))*\.+(([\w#!:.?+=&%@!\-\/]))?/, instant: false, onChange: function (element, value) { if (value != '' && !/^(ftp|http|https):\/\//.test(value)) element.val('http://' + value).trigger('change.wl_Valid'); } }; if($.fn.wl_Widget) $.fn.wl_Widget.defaults = { collapsed: false, load: null, reload: false, removeContent: true, collapsible: true, sortable: true, text: { loading: 'loading...', reload: 'reload', collapse: 'collapse widget', expand: 'expand widget' }, onDrag: function () {}, onDrop: function () {}, onExpand: function () {}, onCollapse: function () {} }; });
JavaScript
$(document).ready(function () { /** * WYSIWYG - jQuery plugin 0.97 * (0.97.2 - From infinity) * * Copyright (c) 2008-2009 Juan M Martinez, 2010-2011 Akzhan Abdulin and all contributors * https://github.com/akzhan/jwysiwyg * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /*jslint browser: true, forin: true */ (function ($) { "use strict"; /* Wysiwyg namespace: private properties and methods */ var console = window.console ? window.console : { log: $.noop, error: function (msg) { $.error(msg); } }; var supportsProp = (('prop' in $.fn) && ('removeProp' in $.fn)); function Wysiwyg() { this.controls = { bold: { groupIndex: 0, visible: false, tags: ["b", "strong"], css: { fontWeight: "bold" }, tooltip: "Bold", hotkey: { "ctrl": 1, "key": 66 } }, copy: { groupIndex: 8, visible: false, tooltip: "Copy" }, colorpicker: { visible: false, groupIndex: 1, tooltip: "Colorpicker", exec: function() { $.wysiwyg.controls.colorpicker.init(this); } }, createLink: { groupIndex: 6, visible: false, exec: function () { var self = this; if ($.wysiwyg.controls && $.wysiwyg.controls.link) { $.wysiwyg.controls.link.init(this); } else if ($.wysiwyg.autoload) { $.wysiwyg.autoload.control("wysiwyg.link.js", function () { self.controls.createLink.exec.apply(self); }); } else { console.error("$.wysiwyg.controls.link not defined. You need to include wysiwyg.link.js file"); } }, tags: ["a"], tooltip: "Create link" }, cut: { groupIndex: 8, visible: false, tooltip: "Cut" }, decreaseFontSize: { groupIndex: 9, visible: false, tags: ["small"], tooltip: "Decrease font size", exec: function () { this.decreaseFontSize(); } }, h1: { groupIndex: 7, visible: false, className: "h1", command: ($.browser.msie || $.browser.safari || $.browser.opera) ? "FormatBlock" : "heading", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<h1>" : "h1", tags: ["h1"], tooltip: "Header 1" }, h2: { groupIndex: 7, visible: false, className: "h2", command: ($.browser.msie || $.browser.safari || $.browser.opera) ? "FormatBlock" : "heading", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<h2>" : "h2", tags: ["h2"], tooltip: "Header 2" }, h3: { groupIndex: 7, visible: false, className: "h3", command: ($.browser.msie || $.browser.safari || $.browser.opera) ? "FormatBlock" : "heading", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<h3>" : "h3", tags: ["h3"], tooltip: "Header 3" }, h4: { groupIndex: 7, visible: false, className: "h4", command: ($.browser.msie || $.browser.safari || $.browser.opera) ? "FormatBlock" : "heading", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<h4>" : "h4", tags: ["h4"], tooltip: "Header 4" }, h5: { groupIndex: 7, visible: false, className: "h5", command: ($.browser.msie || $.browser.safari || $.browser.opera) ? "FormatBlock" : "heading", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<h5>" : "h5", tags: ["h5"], tooltip: "Header 5" }, h6: { groupIndex: 7, visible: false, className: "h6", command: ($.browser.msie || $.browser.safari || $.browser.opera) ? "FormatBlock" : "heading", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<h6>" : "h6", tags: ["h6"], tooltip: "Header 6" }, highlight: { tooltip: "Highlight", className: "highlight", groupIndex: 1, visible: false, css: { backgroundColor: "rgb(255, 255, 102)" }, exec: function () { var command, node, selection, args; if ($.browser.msie || $.browser.safari) { command = "backcolor"; } else { command = "hilitecolor"; } if ($.browser.msie) { node = this.getInternalRange().parentElement(); } else { selection = this.getInternalSelection(); node = selection.extentNode || selection.focusNode; while (node.style === undefined) { node = node.parentNode; if (node.tagName && node.tagName.toLowerCase() === "body") { return; } } } if (node.style.backgroundColor === "rgb(255, 255, 102)" || node.style.backgroundColor === "#ffff66") { args = "#ffffff"; } else { args = "#ffff66"; } this.editorDoc.execCommand(command, false, args); } }, html: { groupIndex: 10, visible: false, exec: function () { var elementHeight; if (this.options.resizeOptions && $.fn.resizable) { elementHeight = this.element.height(); } if (this.viewHTML) { this.setContent(this.original.value); $(this.original).hide(); this.editor.show(); if (this.options.resizeOptions && $.fn.resizable) { // if element.height still the same after frame was shown if (elementHeight === this.element.height()) { this.element.height(elementHeight + this.editor.height()); } this.element.resizable($.extend(true, { alsoResize: this.editor }, this.options.resizeOptions)); } this.ui.toolbar.find("li").each(function () { var li = $(this); if (li.hasClass("html")) { li.removeClass("active"); } else { li.removeClass('disabled'); } }); } else { this.saveContent(); $(this.original).css({ width: this.element.outerWidth() - 6, height: this.element.height() - this.ui.toolbar.height() - 6, resize: "none" }).show(); this.editor.hide(); if (this.options.resizeOptions && $.fn.resizable) { // if element.height still the same after frame was hidden if (elementHeight === this.element.height()) { this.element.height(this.ui.toolbar.height()); } this.element.resizable("destroy"); } this.ui.toolbar.find("li").each(function () { var li = $(this); if (li.hasClass("html")) { li.addClass("active"); } else { if (false === li.hasClass("fullscreen")) { li.removeClass("active").addClass('disabled'); } } }); } this.viewHTML = !(this.viewHTML); }, tooltip: "View source code" }, increaseFontSize: { groupIndex: 9, visible: false, tags: ["big"], tooltip: "Increase font size", exec: function () { this.increaseFontSize(); } }, insertImage: { groupIndex: 6, visible: false, exec: function () { var self = this; if ($.wysiwyg.controls && $.wysiwyg.controls.image) { $.wysiwyg.controls.image.init(this); } else if ($.wysiwyg.autoload) { $.wysiwyg.autoload.control("wysiwyg.image.js", function () { self.controls.insertImage.exec.apply(self); }); } else { console.error("$.wysiwyg.controls.image not defined. You need to include wysiwyg.image.js file"); } }, tags: ["img"], tooltip: "Insert image" }, insertOrderedList: { groupIndex: 5, visible: false, tags: ["ol"], tooltip: "Insert Ordered List" }, insertTable: { groupIndex: 6, visible: false, exec: function () { var self = this; if ($.wysiwyg.controls && $.wysiwyg.controls.table) { $.wysiwyg.controls.table(this); } else if ($.wysiwyg.autoload) { $.wysiwyg.autoload.control("wysiwyg.table.js", function () { self.controls.insertTable.exec.apply(self); }); } else { console.error("$.wysiwyg.controls.table not defined. You need to include wysiwyg.table.js file"); } }, tags: ["table"], tooltip: "Insert table" }, insertUnorderedList: { groupIndex: 5, visible: false, tags: ["ul"], tooltip: "Insert Unordered List" }, italic: { groupIndex: 0, visible: false, tags: ["i", "em"], css: { fontStyle: "italic" }, tooltip: "Italic", hotkey: { "ctrl": 1, "key": 73 } }, justifyLeft: { visible: false, groupIndex: 1, css: { textAlign: "left" }, tooltip: "Justify Left" }, justifyCenter: { groupIndex: 1, visible: false, tags: ["center"], css: { textAlign: "center" }, tooltip: "Justify Center" }, justifyRight: { groupIndex: 1, visible: false, css: { textAlign: "right" }, tooltip: "Justify Right" }, justifyFull: { groupIndex: 1, visible: false, css: { textAlign: "justify" }, tooltip: "Justify Full" }, ltr: { groupIndex: 9, visible: false, exec: function () { var p = this.dom.getElement("p"); if (!p) { return false; } $(p).attr("dir", "ltr"); return true; }, tooltip: "Left to Right" }, rtl: { groupIndex: 9, visible: false, exec: function () { var p = this.dom.getElement("p"); if (!p) { return false; } $(p).attr("dir", "rtl"); return true; }, tooltip: "Right to Left" }, indent: { groupIndex: 2, visible: false, tooltip: "Indent" }, outdent: { groupIndex: 2, visible: false, tooltip: "Outdent" }, insertHorizontalRule: { groupIndex: 5, visible: false, tags: ["hr"], tooltip: "Insert Horizontal Rule" }, paragraph: { groupIndex: 7, visible: false, className: "paragraph", command: "FormatBlock", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<p>" : "p", tags: ["p"], tooltip: "Paragraph" }, paste: { groupIndex: 8, visible: false, tooltip: "Paste" }, undo: { groupIndex: 4, visible: false, tooltip: "Undo" }, redo: { groupIndex: 4, visible: false, tooltip: "Redo" }, removeFormat: { groupIndex: 10, visible: false, exec: function () { this.removeFormat(); }, tooltip: "Remove formatting" }, underline: { groupIndex: 0, visible: false, tags: ["u"], css: { textDecoration: "underline" }, tooltip: "Underline", hotkey: { "ctrl": 1, "key": 85 } }, strikeThrough: { groupIndex: 0, visible: false, tags: ["s", "strike"], css: { textDecoration: "line-through" }, tooltip: "Strike-through" }, subscript: { groupIndex: 3, visible: false, tags: ["sub"], tooltip: "Subscript" }, superscript: { groupIndex: 3, visible: false, tags: ["sup"], tooltip: "Superscript" }, code: { visible: false, groupIndex: 6, tooltip: "Code snippet", exec: function () { var range = this.getInternalRange(), common = $(range.commonAncestorContainer), $nodeName = range.commonAncestorContainer.nodeName.toLowerCase(); if (common.parent("code").length) { common.unwrap(); } else { if ($nodeName !== "body") { common.wrap("<code/>"); } } } }, cssWrap: { visible: false, groupIndex: 6, tooltip: "CSS Wrapper", exec: function () { $.wysiwyg.controls.cssWrap.init(this); } } }; this.defaults = { html: '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>INITIAL_CONTENT</body></html>', debug: false, controls: {}, css: {}, events: {}, autoGrow: false, autoSave: true, brIE: true, // http://code.google.com/p/jwysiwyg/issues/detail?id=15 formHeight: 270, formWidth: 440, iFrameClass: null, initialContent: "<p>Initial content</p>", maxHeight: 10000, // see autoGrow maxLength: 0, messages: { nonSelection: "Select the text you wish to link" }, toolbarHtml: '<ul role="menu" class="toolbar"></ul>', removeHeadings: false, replaceDivWithP: false, resizeOptions: false, rmUnusedControls: false, // https://github.com/akzhan/jwysiwyg/issues/52 rmUnwantedBr: true, // http://code.google.com/p/jwysiwyg/issues/detail?id=11 tableFiller: null, initialMinHeight: null, controlImage: { forceRelativeUrls: false }, controlLink: { forceRelativeUrls: false }, plugins: { // placeholder for plugins settings autoload: false, i18n: false, rmFormat: { rmMsWordMarkup: false } } }; this.availableControlProperties = ["arguments", "callback", "className", "command", "css", "custom", "exec", "groupIndex", "hotkey", "icon", "tags", "tooltip", "visible"]; this.editor = null; this.editorDoc = null; this.element = null; this.options = {}; this.original = null; this.savedRange = null; this.timers = []; this.validKeyCodes = [8, 9, 13, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46]; this.isDestroyed = false; this.dom = { // DOM related properties and methods ie: { parent: null // link to dom }, w3c: { parent: null // link to dom } }; this.dom.parent = this; this.dom.ie.parent = this.dom; this.dom.w3c.parent = this.dom; this.ui = {}; // UI related properties and methods this.ui.self = this; this.ui.toolbar = null; this.ui.initialHeight = null; // ui.grow this.dom.getAncestor = function (element, filterTagName) { filterTagName = filterTagName.toLowerCase(); while (element && "body" !== element.tagName.toLowerCase()) { if (filterTagName === element.tagName.toLowerCase()) { return element; } element = element.parentNode; } return null; }; this.dom.getElement = function (filterTagName) { var dom = this; if (window.getSelection) { return dom.w3c.getElement(filterTagName); } else { return dom.ie.getElement(filterTagName); } }; this.dom.ie.getElement = function (filterTagName) { var dom = this.parent, selection = dom.parent.getInternalSelection(), range = selection.createRange(), element; if ("Control" === selection.type) { // control selection if (1 === range.length) { element = range.item(0); } else { // multiple control selection return null; } } else { element = range.parentElement(); } return dom.getAncestor(element, filterTagName); }; this.dom.w3c.getElement = function (filterTagName) { var dom = this.parent, range = dom.parent.getInternalRange(), element; if (!range) { return null; } element = range.commonAncestorContainer; if (3 === element.nodeType) { element = element.parentNode; } // if startContainer not Text, Comment, or CDATASection element then // startOffset is the number of child nodes between the start of the // startContainer and the boundary point of the Range if (element === range.startContainer) { element = element.childNodes[range.startOffset]; } return dom.getAncestor(element, filterTagName); }; this.ui.addHoverClass = function () { $(this).addClass("wysiwyg-button-hover"); }; this.ui.appendControls = function () { var ui = this, self = this.self, controls = self.parseControls(), hasVisibleControls = true, // to prevent separator before first item groups = [], controlsByGroup = {}, i, currentGroupIndex, // jslint wants all vars at top of function iterateGroup = function (controlName, control) { if (control.groupIndex && currentGroupIndex !== control.groupIndex) { currentGroupIndex = control.groupIndex; hasVisibleControls = false; } if (!control.visible) { return; } if (!hasVisibleControls) { ui.appendItemSeparator(); hasVisibleControls = true; } if (control.custom) { ui.appendItemCustom(controlName, control); } else { ui.appendItem(controlName, control); } }; $.each(controls, function (name, c) { var index = "empty"; if (undefined !== c.groupIndex) { if ("" === c.groupIndex) { index = "empty"; } else { index = c.groupIndex; } } if (undefined === controlsByGroup[index]) { groups.push(index); controlsByGroup[index] = {}; } controlsByGroup[index][name] = c; }); groups.sort(function (a, b) { if ("number" === typeof (a) && typeof (a) === typeof (b)) { return (a - b); } else { a = a.toString(); b = b.toString(); if (a > b) { return 1; } if (a === b) { return 0; } return -1; } }); if (0 < groups.length) { // set to first index in groups to proper placement of separator currentGroupIndex = groups[0]; } for (i = 0; i < groups.length; i += 1) { $.each(controlsByGroup[groups[i]], iterateGroup); } }; this.ui.appendItem = function (name, control) { var self = this.self, className = control.className || control.command || name || "empty", tooltip = control.tooltip || control.command || name || ""; return $('<li role="menuitem" unselectable="on">' + (className) + "</li>").addClass(className).attr("title", tooltip).hover(this.addHoverClass, this.removeHoverClass).click(function () { if ($(this).hasClass("disabled")) { return false; } self.triggerControl.apply(self, [name, control]); this.blur(); self.ui.returnRange(); self.ui.focus(); return true; }).appendTo(self.ui.toolbar); }; this.ui.appendItemCustom = function (name, control) { var self = this.self, tooltip = control.tooltip || control.command || name || ""; if (control.callback) { $(window).bind("trigger-" + name + ".wysiwyg", control.callback); } return $('<li role="menuitem" unselectable="on" style="background: url(\'' + control.icon + '\') no-repeat;"></li>').addClass("custom-command-" + name).addClass("wysiwyg-custom-command").addClass(name).attr("title", tooltip).hover(this.addHoverClass, this.removeHoverClass).click(function () { if ($(this).hasClass("disabled")) { return false; } self.triggerControl.apply(self, [name, control]); this.blur(); self.ui.returnRange(); self.ui.focus(); self.triggerControlCallback(name); return true; }).appendTo(self.ui.toolbar); }; this.ui.appendItemSeparator = function () { var self = this.self; return $('<li role="separator" class="separator"></li>').appendTo(self.ui.toolbar); }; this.autoSaveFunction = function () { this.saveContent(); }; this.ui.checkTargets = function (element) { var self = this.self; $.each(self.options.controls, function (name, control) { var className = control.className || control.command || name || "empty", tags, elm, css, el, checkActiveStatus = function (cssProperty, cssValue) { var handler; if ("function" === typeof (cssValue)) { handler = cssValue; if (handler(el.css(cssProperty).toString().toLowerCase(), self)) { self.ui.toolbar.find("." + className).addClass("active"); } } else { if (el.css(cssProperty).toString().toLowerCase() === cssValue) { self.ui.toolbar.find("." + className).addClass("active"); } } }; if ("fullscreen" !== className) { self.ui.toolbar.find("." + className).removeClass("active"); } if (control.tags || (control.options && control.options.tags)) { tags = control.tags || (control.options && control.options.tags); elm = element; while (elm) { if (elm.nodeType !== 1) { break; } if ($.inArray(elm.tagName.toLowerCase(), tags) !== -1) { self.ui.toolbar.find("." + className).addClass("active"); } elm = elm.parentNode; } } if (control.css || (control.options && control.options.css)) { css = control.css || (control.options && control.options.css); el = $(element); while (el) { if (el[0].nodeType !== 1) { break; } $.each(css, checkActiveStatus); el = el.parent(); } } }); }; this.ui.designMode = function () { var attempts = 3, self = this.self, runner; runner = function (attempts) { if ("on" === self.editorDoc.designMode) { if (self.timers.designMode) { window.clearTimeout(self.timers.designMode); } // IE needs to reget the document element (this.editorDoc) after designMode was set if (self.innerDocument() !== self.editorDoc) { self.ui.initFrame(); } return; } try { self.editorDoc.designMode = "on"; } catch (e) {} attempts -= 1; if (attempts > 0) { self.timers.designMode = window.setTimeout(function () { runner(attempts); }, 100); } }; runner(attempts); }; this.destroy = function () { this.isDestroyed = true; var i, $form = this.element.closest("form"); for (i = 0; i < this.timers.length; i += 1) { window.clearTimeout(this.timers[i]); } // Remove bindings $form.unbind(".wysiwyg"); this.element.remove(); $.removeData(this.original, "wysiwyg"); $(this.original).show(); return this; }; this.getRangeText = function () { var r = this.getInternalRange(); if (r.toString) { r = r.toString(); } else if (r.text) { // IE r = r.text; } return r; }; //not used? this.execute = function (command, arg) { if (typeof (arg) === "undefined") { arg = null; } this.editorDoc.execCommand(command, false, arg); }; this.extendOptions = function (options) { var controls = {}; /** * If the user set custom controls, we catch it, and merge with the * defaults controls later. */ if ("object" === typeof options.controls) { controls = options.controls; delete options.controls; } options = $.extend(true, {}, this.defaults, options); options.controls = $.extend(true, {}, controls, this.controls, controls); if (options.rmUnusedControls) { $.each(options.controls, function (controlName) { if (!controls[controlName]) { delete options.controls[controlName]; } }); } return options; }; this.ui.focus = function () { var self = this.self; self.editor.get(0).contentWindow.focus(); return self; }; this.ui.returnRange = function () { var self = this.self, sel; if (self.savedRange !== null) { if (window.getSelection) { //non IE and there is already a selection sel = window.getSelection(); if (sel.rangeCount > 0) { sel.removeAllRanges(); } try { sel.addRange(self.savedRange); } catch (e) { console.error(e); } } else if (window.document.createRange) { // non IE and no selection window.getSelection().addRange(self.savedRange); } else if (window.document.selection) { //IE self.savedRange.select(); } self.savedRange = null; } }; this.increaseFontSize = function () { if ($.browser.mozilla || $.browser.opera) { this.editorDoc.execCommand('increaseFontSize', false, null); } else if ($.browser.safari) { var newNode = this.editorDoc.createElement('big'); this.getInternalRange().surroundContents(newNode); } else { console.error("Internet Explorer?"); } }; this.decreaseFontSize = function () { if ($.browser.mozilla || $.browser.opera) { this.editorDoc.execCommand('decreaseFontSize', false, null); } else if ($.browser.safari) { var newNode = this.editorDoc.createElement('small'); this.getInternalRange().surroundContents(newNode); } else { console.error("Internet Explorer?"); } }; this.getContent = function () { if (this.viewHTML) { this.setContent(this.original.value); } return this.events.filter('getContent', this.editorDoc.body.innerHTML); }; /** * A jWysiwyg specific event system. * * Example: * * $("#editor").getWysiwyg().events.bind("getContent", function (orig) { * return "<div id='content'>"+orgi+"</div>"; * }); * * This makes it so that when ever getContent is called, it is wrapped in a div#content. */ this.events = { _events: {}, /** * Similar to jQuery's bind, but for jWysiwyg only. */ bind: function (eventName, callback) { if (typeof (this._events.eventName) !== "object") { this._events[eventName] = []; } this._events[eventName].push(callback); }, /** * Similar to jQuery's trigger, but for jWysiwyg only. */ trigger: function (eventName, args) { if (typeof (this._events.eventName) === "object") { var editor = this.editor; $.each(this._events[eventName], function (k, v) { if (typeof (v) === "function") { v.apply(editor, args); } }); } }, /** * This "filters" `originalText` by passing it as the first argument to every callback * with the name `eventName` and taking the return value and passing it to the next function. * * This function returns the result after all the callbacks have been applied to `originalText`. */ filter: function (eventName, originalText) { if (typeof (this._events[eventName]) === "object") { var editor = this.editor, args = Array.prototype.slice.call(arguments, 1); $.each(this._events[eventName], function (k, v) { if (typeof (v) === "function") { originalText = v.apply(editor, args); } }); } return originalText; } }; this.getElementByAttributeValue = function (tagName, attributeName, attributeValue) { var i, value, elements = this.editorDoc.getElementsByTagName(tagName); for (i = 0; i < elements.length; i += 1) { value = elements[i].getAttribute(attributeName); if ($.browser.msie) { /** IE add full path, so I check by the last chars. */ value = value.substr(value.length - attributeValue.length); } if (value === attributeValue) { return elements[i]; } } return false; }; this.getInternalRange = function () { var selection = this.getInternalSelection(); if (!selection) { return null; } if (selection.rangeCount && selection.rangeCount > 0) { // w3c return selection.getRangeAt(0); } else if (selection.createRange) { // ie return selection.createRange(); } return null; }; this.getInternalSelection = function () { // firefox: document.getSelection is deprecated if (this.editor.get(0).contentWindow) { if (this.editor.get(0).contentWindow.getSelection) { return this.editor.get(0).contentWindow.getSelection(); } if (this.editor.get(0).contentWindow.selection) { return this.editor.get(0).contentWindow.selection; } } if (this.editorDoc.getSelection) { return this.editorDoc.getSelection(); } if (this.editorDoc.selection) { return this.editorDoc.selection; } return null; }; this.getRange = function () { var selection = this.getSelection(); if (!selection) { return null; } if (selection.rangeCount && selection.rangeCount > 0) { // w3c selection.getRangeAt(0); } else if (selection.createRange) { // ie return selection.createRange(); } return null; }; this.getSelection = function () { return (window.getSelection) ? window.getSelection() : window.document.selection; }; // :TODO: you can type long string and letters will be hidden because of overflow this.ui.grow = function () { var self = this.self, innerBody = $(self.editorDoc.body), innerHeight = $.browser.msie ? innerBody[0].scrollHeight : innerBody.height() + 2 + 20, // 2 - borders, 20 - to prevent content jumping on grow minHeight = self.ui.initialHeight, height = Math.max(innerHeight, minHeight); height = Math.min(height, self.options.maxHeight); self.editor.attr("scrolling", height < self.options.maxHeight ? "no" : "auto"); // hide scrollbar firefox innerBody.css("overflow", height < self.options.maxHeight ? "hidden" : ""); // hide scrollbar chrome self.editor.get(0).height = height; return self; }; this.init = function (element, options) { var self = this, $form = $(element).closest("form"), newX = element.width || element.clientWidth || 0, newY = element.height || element.clientHeight || 0; this.options = this.extendOptions(options); this.original = element; this.ui.toolbar = $(this.options.toolbarHtml); if ($.browser.msie && parseInt($.browser.version, 10) < 8) { this.options.autoGrow = false; } if (newX === 0 && element.cols) { newX = (element.cols * 8) + 21; } if (newY === 0 && element.rows) { newY = (element.rows * 16) + 16; } this.editor = $(window.location.protocol === "https:" ? '<iframe src="javascript:false;"></iframe>' : "<iframe></iframe>").attr("frameborder", "0"); if (this.options.iFrameClass) { this.editor.addClass(this.options.iFrameClass); } else { this.editor.css({ minHeight: (newY - 6).toString() + "px", // fix for issue 12 ( http://github.com/akzhan/jwysiwyg/issues/issue/12 ) width: (newX > 50) ? (newX - 8).toString() + "px" : "" }); if ($.browser.msie && parseInt($.browser.version, 10) < 7) { this.editor.css("height", newY.toString() + "px"); } } /** * http://code.google.com/p/jwysiwyg/issues/detail?id=96 */ this.editor.attr("tabindex", $(element).attr("tabindex")); this.element = $("<div/>").addClass("wysiwyg"); if (!this.options.iFrameClass) { this.element.css({ width: (newX > 0) ? newX.toString() + "px" : "100%" }); } $(element).hide().before(this.element); this.viewHTML = false; /** * @link http://code.google.com/p/jwysiwyg/issues/detail?id=52 */ this.initialContent = $(element).val(); this.ui.initFrame(); if (this.options.resizeOptions && $.fn.resizable) { this.element.resizable($.extend(true, { alsoResize: this.editor }, this.options.resizeOptions)); } if (this.options.autoSave) { $form.bind("submit.wysiwyg", function () { self.autoSaveFunction(); }); } $form.bind("reset.wysiwyg", function () { self.resetFunction(); }); }; this.ui.initFrame = function () { var self = this.self, stylesheet, growHandler, saveHandler; self.ui.appendControls(); self.element.append(self.ui.toolbar).append($("<div><!-- --></div>").css({ clear: "both" })).append(self.editor); self.editorDoc = self.innerDocument(); if (self.isDestroyed) { return null; } self.ui.designMode(); self.editorDoc.open(); self.editorDoc.write( self.options.html /** * @link http://code.google.com/p/jwysiwyg/issues/detail?id=144 */ .replace(/INITIAL_CONTENT/, function () { return self.wrapInitialContent(); })); self.editorDoc.close(); $.wysiwyg.plugin.bind(self); $(self.editorDoc).trigger("initFrame.wysiwyg"); $(self.editorDoc).bind("click.wysiwyg", function (event) { self.ui.checkTargets(event.target ? event.target : event.srcElement); }); /** * @link http://code.google.com/p/jwysiwyg/issues/detail?id=20 */ $(self.original).focus(function () { if ($(this).filter(":visible")) { return; } self.ui.focus(); }); $(self.editorDoc).keydown(function (event) { var emptyContentRegex; if (event.keyCode === 8) { // backspace emptyContentRegex = /^<([\w]+)[^>]*>(<br\/?>)?<\/\1>$/; if (emptyContentRegex.test(self.getContent())) { // if content is empty event.stopPropagation(); // prevent remove single empty tag return false; } } return true; }); if (!$.browser.msie) { $(self.editorDoc).keydown(function (event) { var controlName; /* Meta for Macs. tom@punkave.com */ if (event.ctrlKey || event.metaKey) { for (controlName in self.controls) { if (self.controls[controlName].hotkey && self.controls[controlName].hotkey.ctrl) { if (event.keyCode === self.controls[controlName].hotkey.key) { self.triggerControl.apply(self, [controlName, self.controls[controlName]]); return false; } } } } return true; }); } else if (self.options.brIE) { $(self.editorDoc).keydown(function (event) { if (event.keyCode === 13) { var rng = self.getRange(); rng.pasteHTML("<br/>"); rng.collapse(false); rng.select(); return false; } return true; }); } if (self.options.plugins.rmFormat.rmMsWordMarkup) { $(self.editorDoc).bind("keyup.wysiwyg", function (event) { if (event.ctrlKey || event.metaKey) { // CTRL + V (paste) if (86 === event.keyCode) { if ($.wysiwyg.rmFormat) { if ("object" === typeof (self.options.plugins.rmFormat.rmMsWordMarkup)) { $.wysiwyg.rmFormat.run(self, { rules: { msWordMarkup: self.options.plugins.rmFormat.rmMsWordMarkup } }); } else { $.wysiwyg.rmFormat.run(self, { rules: { msWordMarkup: { enabled: true } } }); } } } } }); } if (self.options.autoSave) { $(self.editorDoc).keydown(function () { self.autoSaveFunction(); }).keyup(function () { self.autoSaveFunction(); }).mousedown(function () { self.autoSaveFunction(); }).bind($.support.noCloneEvent ? "input.wysiwyg" : "paste.wysiwyg", function () { self.autoSaveFunction(); }); } if (self.options.autoGrow) { if (self.options.initialMinHeight !== null) { self.ui.initialHeight = self.options.initialMinHeight; } else { self.ui.initialHeight = $(self.editorDoc).height(); } $(self.editorDoc.body).css("border", "1px solid white"); // cancel margin collapsing growHandler = function () { self.ui.grow(); }; $(self.editorDoc).keyup(growHandler); $(self.editorDoc).bind("editorRefresh.wysiwyg", growHandler); // fix when content height > textarea height self.ui.grow(); } if (self.options.css) { if (String === self.options.css.constructor) { if ($.browser.msie) { stylesheet = self.editorDoc.createStyleSheet(self.options.css); $(stylesheet).attr({ "media": "all" }); } else { stylesheet = $("<link/>").attr({ "href": self.options.css, "media": "all", "rel": "stylesheet", "type": "text/css" }); $(self.editorDoc).find("head").append(stylesheet); } } else { self.timers.initFrame_Css = window.setTimeout(function () { $(self.editorDoc.body).css(self.options.css); }, 0); } } if (self.initialContent.length === 0) { if ("function" === typeof (self.options.initialContent)) { self.setContent(self.options.initialContent()); } else { self.setContent(self.options.initialContent); } } if (self.options.maxLength > 0) { $(self.editorDoc).keydown(function (event) { if ($(self.editorDoc).text().length >= self.options.maxLength && $.inArray(event.which, self.validKeyCodes) === -1) { event.preventDefault(); } }); } // Support event callbacks $.each(self.options.events, function (key, handler) { $(self.editorDoc).bind(key + ".wysiwyg", function (event) { // Trigger event handler, providing the event and api to // support additional functionality. handler.apply(self.editorDoc, [event, self]); }); }); // restores selection properly on focus if ($.browser.msie) { // Event chain: beforedeactivate => focusout => blur. // Focusout & blur fired too late to handle internalRange() in dialogs. // When clicked on input boxes both got range = null $(self.editorDoc).bind("beforedeactivate.wysiwyg", function () { self.savedRange = self.getInternalRange(); }); } else { $(self.editorDoc).bind("blur.wysiwyg", function () { self.savedRange = self.getInternalRange(); }); } $(self.editorDoc.body).addClass("wysiwyg"); if (self.options.events && self.options.events.save) { saveHandler = self.options.events.save; $(self.editorDoc).bind("keyup.wysiwyg", saveHandler); $(self.editorDoc).bind("change.wysiwyg", saveHandler); if ($.support.noCloneEvent) { $(self.editorDoc).bind("input.wysiwyg", saveHandler); } else { $(self.editorDoc).bind("paste.wysiwyg", saveHandler); $(self.editorDoc).bind("cut.wysiwyg", saveHandler); } } /** * XHTML5 {@link https://github.com/akzhan/jwysiwyg/issues/152} */ if (self.options.xhtml5 && self.options.unicode) { var replacements = { ne: 8800, le: 8804, para: 182, xi: 958, darr: 8595, nu: 957, oacute: 243, Uacute: 218, omega: 969, prime: 8242, pound: 163, igrave: 236, thorn: 254, forall: 8704, emsp: 8195, lowast: 8727, brvbar: 166, alefsym: 8501, nbsp: 160, delta: 948, clubs: 9827, lArr: 8656, Omega: 937, Auml: 196, cedil: 184, and: 8743, plusmn: 177, ge: 8805, raquo: 187, uml: 168, equiv: 8801, laquo: 171, rdquo: 8221, Epsilon: 917, divide: 247, fnof: 402, chi: 967, Dagger: 8225, iacute: 237, rceil: 8969, sigma: 963, Oslash: 216, acute: 180, frac34: 190, lrm: 8206, upsih: 978, Scaron: 352, part: 8706, exist: 8707, nabla: 8711, image: 8465, prop: 8733, zwj: 8205, omicron: 959, aacute: 225, Yuml: 376, Yacute: 221, weierp: 8472, rsquo: 8217, otimes: 8855, kappa: 954, thetasym: 977, harr: 8596, Ouml: 214, Iota: 921, ograve: 242, sdot: 8901, copy: 169, oplus: 8853, acirc: 226, sup: 8835, zeta: 950, Iacute: 205, Oacute: 211, crarr: 8629, Nu: 925, bdquo: 8222, lsquo: 8216, apos: 39, Beta: 914, eacute: 233, egrave: 232, lceil: 8968, Kappa: 922, piv: 982, Ccedil: 199, ldquo: 8220, Xi: 926, cent: 162, uarr: 8593, hellip: 8230, Aacute: 193, ensp: 8194, sect: 167, Ugrave: 217, aelig: 230, ordf: 170, curren: 164, sbquo: 8218, macr: 175, Phi: 934, Eta: 919, rho: 961, Omicron: 927, sup2: 178, euro: 8364, aring: 229, Theta: 920, mdash: 8212, uuml: 252, otilde: 245, eta: 951, uacute: 250, rArr: 8658, nsub: 8836, agrave: 224, notin: 8713, ndash: 8211, Psi: 936, Ocirc: 212, sube: 8838, szlig: 223, micro: 181, not: 172, sup1: 185, middot: 183, iota: 953, ecirc: 234, lsaquo: 8249, thinsp: 8201, sum: 8721, ntilde: 241, scaron: 353, cap: 8745, atilde: 227, lang: 10216, __replacement: 65533, isin: 8712, gamma: 947, Euml: 203, ang: 8736, upsilon: 965, Ntilde: 209, hearts: 9829, Alpha: 913, Tau: 932, spades: 9824, dagger: 8224, THORN: 222, "int": 8747, lambda: 955, Eacute: 201, Uuml: 220, infin: 8734, rlm: 8207, Aring: 197, ugrave: 249, Egrave: 200, Acirc: 194, rsaquo: 8250, ETH: 208, oslash: 248, alpha: 945, Ograve: 210, Prime: 8243, mu: 956, ni: 8715, real: 8476, bull: 8226, beta: 946, icirc: 238, eth: 240, prod: 8719, larr: 8592, ordm: 186, perp: 8869, Gamma: 915, reg: 174, ucirc: 251, Pi: 928, psi: 968, tilde: 732, asymp: 8776, zwnj: 8204, Agrave: 192, deg: 176, AElig: 198, times: 215, Delta: 916, sim: 8764, Otilde: 213, Mu: 924, uArr: 8657, circ: 710, theta: 952, Rho: 929, sup3: 179, diams: 9830, tau: 964, Chi: 935, frac14: 188, oelig: 339, shy: 173, or: 8744, dArr: 8659, phi: 966, iuml: 239, Lambda: 923, rfloor: 8971, iexcl: 161, cong: 8773, ccedil: 231, Icirc: 206, frac12: 189, loz: 9674, rarr: 8594, cup: 8746, radic: 8730, frasl: 8260, euml: 235, OElig: 338, hArr: 8660, Atilde: 195, Upsilon: 933, there4: 8756, ouml: 246, oline: 8254, Ecirc: 202, yacute: 253, auml: 228, permil: 8240, sigmaf: 962, iquest: 191, empty: 8709, pi: 960, Ucirc: 219, supe: 8839, Igrave: 204, yen: 165, rang: 10217, trade: 8482, lfloor: 8970, minus: 8722, Zeta: 918, sub: 8834, epsilon: 949, yuml: 255, Sigma: 931, Iuml: 207, ocirc: 244 }; self.events.bind("getContent", function (text) { return text.replace(/&(?:amp;)?(?!amp|lt|gt|quot)([a-z][a-z0-9]*);/gi, function (str, p1) { if (!replacements[p1]) { p1 = p1.toLowerCase(); if (!replacements[p1]) { p1 = "__replacement"; } } var num = replacements[p1]; /* Numeric return if ever wanted: return replacements[p1] ? "&#"+num+";" : ""; */ return String.fromCharCode(num); }); }); } }; this.innerDocument = function () { var element = this.editor.get(0); if (element.nodeName.toLowerCase() === "iframe") { if (element.contentDocument) { // Gecko return element.contentDocument; } else if (element.contentWindow) { // IE return element.contentWindow.document; } if (this.isDestroyed) { return null; } console.error("Unexpected error in innerDocument"); /* return ( $.browser.msie ) ? document.frames[element.id].document : element.contentWindow.document // contentDocument; */ } return element; }; this.insertHtml = function (szHTML) { var img, range; if (!szHTML || szHTML.length === 0) { return this; } if ($.browser.msie) { this.ui.focus(); this.editorDoc.execCommand("insertImage", false, "#jwysiwyg#"); img = this.getElementByAttributeValue("img", "src", "#jwysiwyg#"); if (img) { $(img).replaceWith(szHTML); } } else { if ($.browser.mozilla) { // @link https://github.com/akzhan/jwysiwyg/issues/50 if (1 === $(szHTML).length) { range = this.getInternalRange(); range.deleteContents(); range.insertNode($(szHTML).get(0)); } else { this.editorDoc.execCommand("insertHTML", false, szHTML); } } else { if (!this.editorDoc.execCommand("insertHTML", false, szHTML)) { this.editor.focus(); /* :TODO: place caret at the end if (window.getSelection) { } else { } this.editor.focus(); */ this.editorDoc.execCommand("insertHTML", false, szHTML); } } } this.saveContent(); return this; }; this.parseControls = function () { var self = this; $.each(this.options.controls, function (controlName, control) { $.each(control, function (propertyName) { if (-1 === $.inArray(propertyName, self.availableControlProperties)) { throw controlName + '["' + propertyName + '"]: property "' + propertyName + '" not exists in Wysiwyg.availableControlProperties'; } }); }); if (this.options.parseControls) { return this.options.parseControls.call(this); } return this.options.controls; }; this.removeFormat = function () { if ($.browser.msie) { this.ui.focus(); } if (this.options.removeHeadings) { this.editorDoc.execCommand("formatBlock", false, "<p>"); // remove headings } this.editorDoc.execCommand("removeFormat", false, null); this.editorDoc.execCommand("unlink", false, null); if ($.wysiwyg.rmFormat && $.wysiwyg.rmFormat.enabled) { if ("object" === typeof (this.options.plugins.rmFormat.rmMsWordMarkup)) { $.wysiwyg.rmFormat.run(this, { rules: { msWordMarkup: this.options.plugins.rmFormat.rmMsWordMarkup } }); } else { $.wysiwyg.rmFormat.run(this, { rules: { msWordMarkup: { enabled: true } } }); } } return this; }; this.ui.removeHoverClass = function () { $(this).removeClass("wysiwyg-button-hover"); }; this.resetFunction = function () { this.setContent(this.initialContent); }; this.saveContent = function () { if (this.viewHTML) { return; // no need } if (this.original) { var content, newContent; content = this.getContent(); if (this.options.rmUnwantedBr) { content = content.replace(/<br\/?>$/, ""); } if (this.options.replaceDivWithP) { newContent = $("<div/>").addClass("temp").append(content); newContent.children("div").each(function () { var element = $(this), p = element.find("p"), i; if (0 === p.length) { p = $("<p></p>"); if (this.attributes.length > 0) { for (i = 0; i < this.attributes.length; i += 1) { p.attr(this.attributes[i].name, element.attr(this.attributes[i].name)); } } p.append(element.html()); element.replaceWith(p); } }); content = newContent.html(); } $(this.original).val(content); if (this.options.events && this.options.events.save) { this.options.events.save.call(this); } } return this; }; this.setContent = function (newContent) { this.editorDoc.body.innerHTML = newContent; this.saveContent(); return this; }; this.triggerControl = function (name, control) { var cmd = control.command || name, args = control["arguments"] || []; if (control.exec) { control.exec.apply(this); } else { this.ui.focus(); this.ui.withoutCss(); // when click <Cut>, <Copy> or <Paste> got "Access to XPConnect service denied" code: "1011" // in Firefox untrusted JavaScript is not allowed to access the clipboard try { this.editorDoc.execCommand(cmd, false, args); } catch (e) { console.error(e); } } if (this.options.autoSave) { this.autoSaveFunction(); } }; this.triggerControlCallback = function (name) { $(window).trigger("trigger-" + name + ".wysiwyg", [this]); }; this.ui.withoutCss = function () { var self = this.self; if ($.browser.mozilla) { try { self.editorDoc.execCommand("styleWithCSS", false, false); } catch (e) { try { self.editorDoc.execCommand("useCSS", false, true); } catch (e2) {} } } return self; }; this.wrapInitialContent = function () { var content = this.initialContent, found = content.match(/<\/?p>/gi); if (!found) { return "<p>" + content + "</p>"; } else { // :TODO: checking/replacing } return content; }; } /* * Wysiwyg namespace: public properties and methods */ $.wysiwyg = { messages: { noObject: "Something goes wrong, check object" }, /** * Custom control support by Alec Gorge ( http://github.com/alecgorge ) */ addControl: function (object, name, settings) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"), customControl = {}, toolbar; if (!oWysiwyg) { return this; } customControl[name] = $.extend(true, { visible: true, custom: true }, settings); $.extend(true, oWysiwyg.options.controls, customControl); // render new toolbar toolbar = $(oWysiwyg.options.toolbarHtml); oWysiwyg.ui.toolbar.replaceWith(toolbar); oWysiwyg.ui.toolbar = toolbar; oWysiwyg.ui.appendControls(); }); }, clear: function (object) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } oWysiwyg.setContent(""); }); }, console: console, // let our console be available for extensions destroy: function (object) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } oWysiwyg.destroy(); }); }, "document": function (object) { // no chains because of return var oWysiwyg = object.data("wysiwyg"); if (!oWysiwyg) { return undefined; } return $(oWysiwyg.editorDoc); }, getContent: function (object) { // no chains because of return var oWysiwyg = object.data("wysiwyg"); if (!oWysiwyg) { return undefined; } return oWysiwyg.getContent(); }, init: function (object, options) { return object.each(function () { var opts = $.extend(true, {}, options), obj; // :4fun: // remove this textarea validation and change line in this.saveContent function // $(this.original).val(content); to $(this.original).html(content); // now you can make WYSIWYG editor on h1, p, and many more tags if (("textarea" !== this.nodeName.toLowerCase()) || $(this).data("wysiwyg")) { return; } obj = new Wysiwyg(); obj.init(this, opts); $.data(this, "wysiwyg", obj); $(obj.editorDoc).trigger("afterInit.wysiwyg"); }); }, insertHtml: function (object, szHTML) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } oWysiwyg.insertHtml(szHTML); }); }, plugin: { listeners: {}, bind: function (Wysiwyg) { var self = this; $.each(this.listeners, function (action, handlers) { var i, plugin; for (i = 0; i < handlers.length; i += 1) { plugin = self.parseName(handlers[i]); $(Wysiwyg.editorDoc).bind(action + ".wysiwyg", { plugin: plugin }, function (event) { $.wysiwyg[event.data.plugin.name][event.data.plugin.method].apply($.wysiwyg[event.data.plugin.name], [Wysiwyg]); }); } }); }, exists: function (name) { var plugin; if ("string" !== typeof (name)) { return false; } plugin = this.parseName(name); if (!$.wysiwyg[plugin.name] || !$.wysiwyg[plugin.name][plugin.method]) { return false; } return true; }, listen: function (action, handler) { var plugin; plugin = this.parseName(handler); if (!$.wysiwyg[plugin.name] || !$.wysiwyg[plugin.name][plugin.method]) { return false; } if (!this.listeners[action]) { this.listeners[action] = []; } this.listeners[action].push(handler); return true; }, parseName: function (name) { var elements; if ("string" !== typeof (name)) { return false; } elements = name.split("."); if (2 > elements.length) { return false; } return { name: elements[0], method: elements[1] }; }, register: function (data) { if (!data.name) { console.error("Plugin name missing"); } $.each($.wysiwyg, function (pluginName) { if (pluginName === data.name) { console.error("Plugin with name '" + data.name + "' was already registered"); } }); $.wysiwyg[data.name] = data; return true; } }, removeFormat: function (object) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } oWysiwyg.removeFormat(); }); }, save: function (object) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } oWysiwyg.saveContent(); }); }, selectAll: function (object) { var oWysiwyg = object.data("wysiwyg"), oBody, oRange, selection; if (!oWysiwyg) { return this; } oBody = oWysiwyg.editorDoc.body; if (window.getSelection) { selection = oWysiwyg.getInternalSelection(); selection.selectAllChildren(oBody); } else { oRange = oBody.createTextRange(); oRange.moveToElementText(oBody); oRange.select(); } }, setContent: function (object, newContent) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } oWysiwyg.setContent(newContent); }); }, triggerControl: function (object, controlName) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } if (!oWysiwyg.controls[controlName]) { console.error("Control '" + controlName + "' not exists"); } oWysiwyg.triggerControl.apply(oWysiwyg, [controlName, oWysiwyg.controls[controlName]]); }); }, support: { prop: supportsProp }, utils: { extraSafeEntities: [ ["<", ">", "'", '"', " "], [32] ], encodeEntities: function (str) { var self = this, aStr, aRet = []; if (this.extraSafeEntities[1].length === 0) { $.each(this.extraSafeEntities[0], function (i, ch) { self.extraSafeEntities[1].push(ch.charCodeAt(0)); }); } aStr = str.split(""); $.each(aStr, function (i) { var iC = aStr[i].charCodeAt(0); if ($.inArray(iC, self.extraSafeEntities[1]) && (iC < 65 || iC > 127 || (iC > 90 && iC < 97))) { aRet.push('&#' + iC + ';'); } else { aRet.push(aStr[i]); } }); return aRet.join(''); } } }; $.fn.wysiwyg = function (method) { var args = arguments, plugin; if ("undefined" !== typeof $.wysiwyg[method]) { // set argument object to undefined args = Array.prototype.concat.call([args[0]], [this], Array.prototype.slice.call(args, 1)); return $.wysiwyg[method].apply($.wysiwyg, Array.prototype.slice.call(args, 1)); } else if ("object" === typeof method || !method) { Array.prototype.unshift.call(args, this); return $.wysiwyg.init.apply($.wysiwyg, args); } else if ($.wysiwyg.plugin.exists(method)) { plugin = $.wysiwyg.plugin.parseName(method); args = Array.prototype.concat.call([args[0]], [this], Array.prototype.slice.call(args, 1)); return $.wysiwyg[plugin.name][plugin.method].apply($.wysiwyg[plugin.name], Array.prototype.slice.call(args, 1)); } else { console.error("Method '" + method + "' does not exist on jQuery.wysiwyg.\nTry to include some extra controls or plugins"); } }; $.fn.getWysiwyg = function () { return $.data(this, "wysiwyg"); }; })(jQuery); /** * Controls: Image plugin * * Depends on jWYSIWYG */ (function ($) { if (undefined === $.wysiwyg) { throw "wysiwyg.image.js depends on $.wysiwyg"; } if (!$.wysiwyg.controls) { $.wysiwyg.controls = {}; } /* * Wysiwyg namespace: public properties and methods */ $.wysiwyg.controls.image = { init: function (Wysiwyg) { var self = this, elements, dialog, formImageHtml, dialogReplacements, key, translation, img = { alt: "", self: Wysiwyg.dom.getElement("img"), // link to element node src: "http://", title: "" }; dialogReplacements = { legend: "Insert Image", preview: "Preview", url: "URL", title: "Title", description: "Description", width: "Width", height: "Height", original: "Original W x H", "float": "Float", floatNone: "None", floatLeft: "Left", floatRight: "Right", submit: "Insert Image", loading: "loading", reset: "Cancel" }; formImageHtml = '<form class="wysiwyg" title="{legend}">' + '<img src="" alt="{preview}" width="100%"><br>' + '{url}: <input type="text" name="src" value=""><br>' + '{title}: <input type="text" name="imgtitle" value=""><br>' + '{description}: <input type="text" name="description" value=""><br>' + '{width} x {height}: <input type="text" name="width" value="" class="width integer"> x <input type="text" name="height" value="" class="height integer"><br>' + '{float}: <select name="float">' + '<option value="">{floatNone}</option>' + '<option value="left">{floatLeft}</option>' + '<option value="right">{floatRight}</option></select></label><hr>' + '<button class="button" id="wysiwyg_submit">{submit}</button> ' + '<button class="button" id="wysiwyg_reset">{reset}</button></form>'; for (key in dialogReplacements) { if ($.wysiwyg.i18n) { translation = $.wysiwyg.i18n.t(dialogReplacements[key], "dialogs.image"); if (translation === dialogReplacements[key]) { // if not translated search in dialogs translation = $.wysiwyg.i18n.t(dialogReplacements[key], "dialogs"); } dialogReplacements[key] = translation; } formImageHtml = formImageHtml.replace("{" + key + "}", dialogReplacements[key]); } if (img.self) { img.src = img.self.src ? img.self.src : ""; img.alt = img.self.alt ? img.self.alt : ""; img.title = img.self.title ? img.self.title : ""; img.width = img.self.width ? img.self.width : ""; img.height = img.self.height ? img.self.height : ""; img.asp = img.width / img.width; } elements = $(formImageHtml); elements = self.makeForm(elements, img); dialog = elements.appendTo("body"); dialog.dialog({ modal: true, resizable: false, open: function (ev, ui) { $("#wysiwyg_submit", dialog).click(function (e) { self.processInsert(dialog.container, Wysiwyg, img); $(dialog).dialog("close"); return false; }); $("#wysiwyg_reset", dialog).click(function (e) { $(dialog).dialog("close"); return false; }); $('fieldset', dialog).click(function (e) { e.stopPropagation(); }); $("select, input[type=text]", dialog).uniform(); $('.width', dialog).wl_Number({ step: 10, onChange: function (value) { $('.height', dialog).val(Math.ceil(value / (img.asp || 1))); } }); $('.height', dialog).wl_Number({ step: 10, onChange: function (value) { $('.width', dialog).val(Math.floor(value * (img.asp || 1))); } }); $('input[name="src"]', dialog).wl_URL(); }, close: function (ev, ui) { dialog.dialog("destroy"); dialog.remove(); } }); $(Wysiwyg.editorDoc).trigger("editorRefresh.wysiwyg"); }, processInsert: function (context, Wysiwyg, img) { var image, url = $('input[name="src"]', context).val(), title = $('input[name="imgtitle"]', context).val(), description = $('input[name="description"]', context).val(), width = $('input[name="width"]', context).val(), height = $('input[name="height"]', context).val(), styleFloat = $('select[name="float"]', context).val(), style = [], found, baseUrl; if (Wysiwyg.options.controlImage.forceRelativeUrls) { baseUrl = window.location.protocol + "//" + window.location.hostname; if (0 === url.indexOf(baseUrl)) { url = url.substr(baseUrl.length); } } if (img.self) { // to preserve all img attributes $(img.self).attr("src", url).attr("title", title).attr("alt", description).css("float", styleFloat); if (width.toString().match(/^[0-9]+(px|%)?$/)) { $(img.self).css("width", width); } else { $(img.self).css("width", ""); } if (height.toString().match(/^[0-9]+(px|%)?$/)) { $(img.self).css("height", height); } else { $(img.self).css("height", ""); } Wysiwyg.saveContent(); } else { found = width.toString().match(/^[0-9]+(px|%)?$/); if (found) { if (found[1]) { style.push("width: " + width + ";"); } else { style.push("width: " + width + "px;"); } } found = height.toString().match(/^[0-9]+(px|%)?$/); if (found) { if (found[1]) { style.push("height: " + height + ";"); } else { style.push("height: " + height + "px;"); } } if (styleFloat.length > 0) { style.push("float: " + styleFloat + ";"); } if (style.length > 0) { style = ' style="' + style.join(" ") + '"'; } image = "<img src='" + url + "' title='" + title + "' alt='" + description + "'" + style + "/>"; Wysiwyg.insertHtml(image); } }, makeForm: function (form, img) { form.find("input[name=src]").val(img.src); form.find("input[name=imgtitle]").val(img.title); form.find("input[name=description]").val(img.alt); form.find('input[name="width"]').val(img.width); form.find('input[name="height"]').val(img.height); form.find('img').attr("src", img.src); img.asp = img.width / img.height; form.find("input[name=src]").bind("change", function () { var image = new Image(); var text = $('#wysiwyg_submit', form).find('span').text(); form.find('img').removeAttr("src"); $('#wysiwyg_submit', form).prop('disabled', true).find('span').text('wait...'); image.onload = function () { form.find('img').attr("src", image.src); img.asp = image.width / image.height; form.find('input[name="width"]').val(image.width); form.find('input[name="height"]').val(image.height); $('#wysiwyg_submit', form).find('span').text(text); $('#wysiwyg_submit', form).prop('disabled', false); }; image.src = this.value; }); return form; } }; $.wysiwyg.insertImage = function (object, url, attributes) { return object.each(function () { var Wysiwyg = $(this).data("wysiwyg"), image, attribute; if (!Wysiwyg) { return this; } if (!url || url.length === 0) { return this; } if ($.browser.msie) { Wysiwyg.ui.focus(); } if (attributes) { Wysiwyg.editorDoc.execCommand("insertImage", false, "#jwysiwyg#"); image = Wysiwyg.getElementByAttributeValue("img", "src", "#jwysiwyg#"); if (image) { image.src = url; for (attribute in attributes) { if (attributes.hasOwnProperty(attribute)) { image.setAttribute(attribute, attributes[attribute]); } } } } else { Wysiwyg.editorDoc.execCommand("insertImage", false, url); } Wysiwyg.saveContent(); $(Wysiwyg.editorDoc).trigger("editorRefresh.wysiwyg"); return this; }); }; })(jQuery); /** * Controls: Table plugin * * Depends on jWYSIWYG */ (function ($) { if (undefined === $.wysiwyg) { throw "wysiwyg.table.js depends on $.wysiwyg"; } if (!$.wysiwyg.controls) { $.wysiwyg.controls = {}; } var insertTable = function (colCount, rowCount, filler) { if (isNaN(rowCount) || isNaN(colCount) || rowCount === null || colCount === null) { return; } var i, j, html = ['<table border="1" style="width: 100%;"><tbody>']; colCount = parseInt(colCount, 10); rowCount = parseInt(rowCount, 10); if (filler === null) { filler = "&nbsp;"; } filler = "<td>" + filler + "</td>"; for (i = rowCount; i > 0; i -= 1) { html.push("<tr>"); for (j = colCount; j > 0; j -= 1) { html.push(filler); } html.push("</tr>"); } html.push("</tbody></table>"); return this.insertHtml(html.join("")); }; /* * Wysiwyg namespace: public properties and methods */ $.wysiwyg.controls.table = function (Wysiwyg) { var dialog, colCount, rowCount, formTableHtml, formTextLegend = "Insert table", formTextCols = "Count of columns", formTextRows = "Count of rows", formTextSubmit = "Insert table", formTextReset = "Cancel"; if ($.wysiwyg.i18n) { formTextLegend = $.wysiwyg.i18n.t(formTextLegend, "dialogs.table"); formTextCols = $.wysiwyg.i18n.t(formTextCols, "dialogs.table"); formTextRows = $.wysiwyg.i18n.t(formTextRows, "dialogs.table"); formTextSubmit = $.wysiwyg.i18n.t(formTextSubmit, "dialogs.table"); formTextReset = $.wysiwyg.i18n.t(formTextReset, "dialogs"); } formTableHtml = '<form class="wysiwyg" title="' + formTextLegend + '">' + formTextCols + ': <input type="text" name="colCount" value="3" class="integer" ><br>' + formTextRows + ': <input type="text" name="rowCount" value="3" class="integer" ><hr>' + '<button class="button" id="wysiwyg_submit">' + formTextSubmit + '</button> ' + '<button class="button" id="wysiwyg_reset">' + formTextReset + '</button></form>'; if (!Wysiwyg.insertTable) { Wysiwyg.insertTable = insertTable; } dialog = $(formTableHtml).appendTo("body"); dialog.dialog({ modal: true, resizable: false, open: function (event, ui) { $("#wysiwyg_submit", dialog).click(function (e) { e.preventDefault(); rowCount = $('input[name="rowCount"]', dialog).val(); colCount = $('input[name="colCount"]', dialog).val(); Wysiwyg.insertTable(colCount, rowCount, Wysiwyg.defaults.tableFiller); $(dialog).dialog("close"); }); $("#wysiwyg_reset", dialog).click(function (e) { e.preventDefault(); $(dialog).dialog("close"); }); $("select, input[type=text]", dialog).uniform(); $('.integer', dialog).wl_Number(); }, close: function (event, ui) { dialog.dialog("destroy"); dialog.remove(); } }); $(Wysiwyg.editorDoc).trigger("editorRefresh.wysiwyg"); }; $.wysiwyg.insertTable = function (object, colCount, rowCount, filler) { return object.each(function () { var Wysiwyg = $(this).data("wysiwyg"); if (!Wysiwyg.insertTable) { Wysiwyg.insertTable = insertTable; } if (!Wysiwyg) { return this; } Wysiwyg.insertTable(colCount, rowCount, filler); $(Wysiwyg.editorDoc).trigger("editorRefresh.wysiwyg"); return this; }); }; })(jQuery); /** * Controls: Link plugin * * Depends on jWYSIWYG * * By: Esteban Beltran (academo) <sergies@gmail.com> */ (function ($) { if (undefined === $.wysiwyg) { throw "wysiwyg.link.js depends on $.wysiwyg"; } if (!$.wysiwyg.controls) { $.wysiwyg.controls = {}; } /* * Wysiwyg namespace: public properties and methods */ $.wysiwyg.controls.link = { init: function (Wysiwyg) { var self = this, elements, dialog, url, a, selection, formLinkHtml, formTextLegend, formTextUrl, formTextTitle, formTextTarget, formTextSubmit, formTextReset, baseUrl; formTextLegend = "Insert Link"; formTextUrl = "Link URL"; formTextTitle = "Link Title"; formTextTarget = "Link Target"; formTextSubmit = "Insert Link"; formTextReset = "Cancel"; if ($.wysiwyg.i18n) { formTextLegend = $.wysiwyg.i18n.t(formTextLegend, "dialogs.link"); formTextUrl = $.wysiwyg.i18n.t(formTextUrl, "dialogs.link"); formTextTitle = $.wysiwyg.i18n.t(formTextTitle, "dialogs.link"); formTextTarget = $.wysiwyg.i18n.t(formTextTarget, "dialogs.link"); formTextSubmit = $.wysiwyg.i18n.t(formTextSubmit, "dialogs.link"); formTextReset = $.wysiwyg.i18n.t(formTextReset, "dialogs"); } formLinkHtml = '<form class="wysiwyg" title="' + formTextLegend + '">' + formTextUrl + ': <input type="text" name="linkhref" value="">' + formTextTitle + ': <input type="text" name="linktitle" value="">' + formTextTarget + ': <input type="text" name="linktarget" value=""><hr>' + '<button class="button" id="wysiwyg_submit">' + formTextSubmit + '</button> ' + '<button class="button" id="wysiwyg_reset">' + formTextReset + '</button></form>'; a = { self: Wysiwyg.dom.getElement("a"), // link to element node href: "http://", title: "", target: "" }; if (a.self) { a.href = a.self.href ? a.self.href : a.href; a.title = a.self.title ? a.self.title : ""; a.target = a.self.target ? a.self.target : ""; } elements = $(formLinkHtml); elements.find("input[name=linkhref]").val(a.href); elements.find("input[name=linktitle]").val(a.title); elements.find("input[name=linktarget]").val(a.target); if ($.browser.msie) { dialog = elements.appendTo(Wysiwyg.editorDoc.body); } else { dialog = elements.appendTo("body"); } dialog.dialog({ modal: true, resizable: false, open: function (ev, ui) { $("#wysiwyg_submit", dialog).click(function (e) { e.preventDefault(); var url = $('input[name="linkhref"]', dialog).val(), title = $('input[name="linktitle"]', dialog).val(), target = $('input[name="linktarget"]', dialog).val(), baseUrl; if (Wysiwyg.options.controlLink.forceRelativeUrls) { baseUrl = window.location.protocol + "//" + window.location.hostname; if (0 === url.indexOf(baseUrl)) { url = url.substr(baseUrl.length); } } if (a.self) { if ("string" === typeof (url)) { if (url.length > 0) { // to preserve all link attributes $(a.self).attr("href", url).attr("title", title).attr("target", target); } else { $(a.self).replaceWith(a.self.innerHTML); } } } else { if ($.browser.msie) { Wysiwyg.ui.returnRange(); } //Do new link element selection = Wysiwyg.getRangeText(); img = Wysiwyg.dom.getElement("img"); if ((selection && selection.length > 0) || img) { if ($.browser.msie) { Wysiwyg.ui.focus(); } if ("string" === typeof (url)) { if (url.length > 0) { Wysiwyg.editorDoc.execCommand("createLink", false, url); } else { Wysiwyg.editorDoc.execCommand("unlink", false, null); } } a.self = Wysiwyg.dom.getElement("a"); $(a.self).attr("href", url).attr("title", title); /** * @url https://github.com/akzhan/jwysiwyg/issues/16 */ $(a.self).attr("target", target); } else if (Wysiwyg.options.messages.nonSelection) { $.dialog(Wysiwyg.options.messages.nonSelection); } } Wysiwyg.saveContent(); $(dialog).dialog("close"); }); $("#wysiwyg_reset", dialog).click(function (e) { e.preventDefault(); $(dialog).dialog("close"); }); $("select, input", dialog).uniform(); $('input[name="linkhref"]', dialog).wl_URL(); }, close: function (ev, ui) { dialog.dialog("destroy"); dialog.remove(); } }); $(Wysiwyg.editorDoc).trigger("editorRefresh.wysiwyg"); } }; $.wysiwyg.createLink = function (object, url) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"), selection; if (!oWysiwyg) { return this; } if (!url || url.length === 0) { return this; } selection = oWysiwyg.getRangeText(); if (selection && selection.length > 0) { if ($.browser.msie) { oWysiwyg.ui.focus(); } oWysiwyg.editorDoc.execCommand("unlink", false, null); oWysiwyg.editorDoc.execCommand("createLink", false, url); } else if (oWysiwyg.options.messages.nonSelection) { window.alert(oWysiwyg.options.messages.nonSelection); } }); }; })(jQuery); /** * Controls: Element CSS Wrapper plugin * * Depends on jWYSIWYG * * By Yotam Bar-On (https://github.com/tudmotu) */ (function ($) { if (undefined === $.wysiwyg) { throw "wysiwyg.cssWrap.js depends on $.wysiwyg"; } /* For core enhancements #143 $.wysiwyg.ui.addControl("cssWrap", { visible : false, groupIndex: 6, tooltip: "CSS Wrapper", exec: function () { $.wysiwyg.controls.cssWrap.init(this); } } */ if (!$.wysiwyg.controls) { $.wysiwyg.controls = {}; } /* * Wysiwyg namespace: public properties and methods */ $.wysiwyg.controls.cssWrap = { init: function (Wysiwyg) { var self = this, formWrapHtml, key, translation, dialogReplacements = { legend: "Wrap Element", wrapperType: "Wrapper Type", ID: "ID", "class": "Class", wrap: "Wrap", unwrap: "Unwrap", cancel: "Cancel" }; formWrapHtml = '<form class="wysiwyg" title="{legend}"><fieldset>' + '{wrapperType}: <select name="type"><option value="span">Span</option><option value="div">Div</option></select><br>' + '{ID}: <input name="id" type="text"><br>' + '{class}: <input name="class" type="text" ><hr>' + '<button class="cssWrap-unwrap" style="display:none;">{unwrap}</button> ' + '<button class="cssWrap-submit">{wrap}</button> ' + '<button class="cssWrap-cancel">{cancel}</button></fieldset></form>'; for (key in dialogReplacements) { if ($.wysiwyg.i18n) { translation = $.wysiwyg.i18n.t(dialogReplacements[key]); if (translation === dialogReplacements[key]) { // if not translated search in dialogs translation = $.wysiwyg.i18n.t(dialogReplacements[key], "dialogs"); } dialogReplacements[key] = translation; } formWrapHtml = formWrapHtml.replace("{" + key + "}", dialogReplacements[key]); } if (!$(".wysiwyg-dialog-wrapper").length) { $(formWrapHtml).appendTo("body"); $("form.wysiwyg").dialog({ modal: true, resizable: false, open: function (ev, ui) { $this = $(this); var range = Wysiwyg.getInternalRange(), common; // We make sure that there is some selection: if (range) { if ($.browser.msie) { Wysiwyg.ui.focus(); } common = $(range.commonAncestorContainer); } else { alert("You must select some elements before you can wrap them."); $this.dialog("close"); return 0; } var $nodeName = range.commonAncestorContainer.nodeName.toLowerCase(); // If the selection is already a .wysiwygCssWrapper, then we want to change it and not double-wrap it. if (common.parent(".wysiwygCssWrapper").length) { alert(common.parent(".wysiwygCssWrapper").get(0).nodeName.toLowerCase()); $this.find("select[name=type]").val(common.parent(".wysiwygCssWrapper").get(0).nodeName.toLowerCase()); $this.find("select[name=type]").attr("disabled", "disabled"); $this.find("input[name=id]").val(common.parent(".wysiwygCssWrapper").attr("id")); $this.find("input[name=class]").val(common.parent(".wysiwygCssWrapper").attr("class").replace('wysiwygCssWrapper ', '')); // Add the "unwrap" button: $("form.wysiwyg").find(".cssWrap-unwrap").show(); $("form.wysiwyg").find(".cssWrap-unwrap").click(function (e) { e.preventDefault(); if ($nodeName !== "body") { common.unwrap(); } $this.dialog("close"); return 1; }); } // Submit button. $("form.wysiwyg").find(".cssWrap-submit").click(function (e) { e.preventDefault(); var $wrapper = $("form.wysiwyg").find("select[name=type]").val(); var $id = $("form.wysiwyg").find("input[name=id]").val(); var $class = $("form.wysiwyg").find("input[name=class]").val(); if ($nodeName !== "body") { // If the selection is already a .wysiwygCssWrapper, then we want to change it and not double-wrap it. if (common.parent(".wysiwygCssWrapper").length) { common.parent(".wysiwygCssWrapper").attr("id", $class); common.parent(".wysiwygCssWrapper").attr("class", $class); } else { common.wrap('<' + $wrapper + ' id="' + $id + '" class="' + "wysiwygCssWrapper " + $class + '"/>'); } } else { // Currently no implemntation for if $nodeName == 'body'. } $this.dialog("close"); }); // Cancel button. $("form.wysiwyg").find(".cssWrap-cancel").click(function (e) { e.preventDefault(); $this.dialog("close"); return 1; }); $("form.wysiwyg").find("select, input[type=text]").uniform(); }, close: function () { $(this).dialog("destroy"); $(this).remove(); } }); Wysiwyg.saveContent(); } $(Wysiwyg.editorDoc).trigger("editorRefresh.wysiwyg"); return 1; } } })(jQuery); /** * Controls: Colorpicker plugin * * Depends on jWYSIWYG, wl_Color Plugin */ (function ($) { "use strict"; if (undefined === $.wysiwyg) { throw "wysiwyg.colorpicker.js depends on $.wysiwyg"; } if (!$.wysiwyg.controls) { $.wysiwyg.controls = {}; } /* * Wysiwyg namespace: public properties and methods */ $.wysiwyg.controls.colorpicker = { modalOpen: false, init: function (Wysiwyg) { if ($.wysiwyg.controls.colorpicker.modalOpen === true) { return false; } else { $.wysiwyg.controls.colorpicker.modalOpen = true; } var self = this, elements, dialog, colorpickerHtml, dialogReplacements, key, translation; dialogReplacements = { legend: "Colorpicker", color: "Color", submit: "Apply", cancel: "Cancel" }; colorpickerHtml = '<form class="wysiwyg" title="{legend}">' + '{color}: <input type="text" class="color" id="wysiwyg_colorpicker" name="wysiwyg_colorpicker" value=""><hr>' + '<button id="wysiwyg_colorpicker-submit">{submit}</button> ' + '<button id="wysiwyg_colorpicker-cancel">{cancel}</button></form>'; for (key in dialogReplacements) { if ($.wysiwyg.i18n) { translation = $.wysiwyg.i18n.t(dialogReplacements[key], "dialogs.colorpicker"); if (translation === dialogReplacements[key]) { // if not translated search in dialogs translation = $.wysiwyg.i18n.t(dialogReplacements[key], "dialogs"); } dialogReplacements[key] = translation; } colorpickerHtml = colorpickerHtml.replace("{" + key + "}", dialogReplacements[key]); } elements = $(colorpickerHtml); dialog = elements.appendTo("body"); dialog.dialog({ modal: true, resizable: false, open: function (event, ui) { if ($.browser.msie) { Wysiwyg.ui.returnRange(); } var selection = Wysiwyg.getRangeText(), content = Wysiwyg.getContent(), color = '', regexp = /#([a-fA-F0-9]{3,6})/; if (content.match(regexp)) { regexp.exec(content); color = RegExp.$1; } else { regexp = /rgb\((\d+), (\d+), (\d+)\)/; if (content.match(regexp)) { regexp.exec(content); var r = RegExp.$1, g = RegExp.$2, b = RegExp.$3; color = parseInt(r).toString(16) + parseInt(g).toString(16) + parseInt(b).toString(16); } } $('#wysiwyg_colorpicker').val('#' + color).wl_Color(); $("#wysiwyg_colorpicker-submit").click(function (e) { e.preventDefault(); var color = $('#wysiwyg_colorpicker').val(); if ($.browser.msie) { Wysiwyg.ui.returnRange(); Wysiwyg.ui.focus(); } if (color) Wysiwyg.editorDoc.execCommand('ForeColor', false, color); Wysiwyg.saveContent(); $(dialog).dialog("close"); return false; }); $("#wysiwyg_colorpicker-cancel").click(function (e) { e.preventDefault(); if ($.browser.msie) { Wysiwyg.ui.returnRange(); } $(dialog).dialog("close"); return false; }); }, close: function (event, ui) { $.wysiwyg.controls.colorpicker.modalOpen = false; dialog.dialog("destroy"); dialog.remove(); } }); } }; })(jQuery); });
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Multiselect v 1.3 by revaxarts.com /* description: Makes a Multiselector out of a select input /* dependency: jQuery UI /*----------------------------------------------------------------------*/ $.fn.wl_Multiselect = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Multiselect.methods[method]) { return $.fn.wl_Multiselect.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Multiselect')) { var opts = $.extend({}, $this.data('wl_Multiselect'), method); } else { var opts = $.extend({}, $.fn.wl_Multiselect.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Multiselect')) { $this.data('wl_Multiselect', {}); //Hide the native input $this.hide(); //insert the required HTML $('<div class="comboselectbox"><div class="combowrap"><ul class="comboselect"></ul></div><div class="comboselectbuttons"><a class="add btn"></a><a class="addall btn"></a><a class="removeall btn"></a><a class="remove btn"></a></div><div class="combowrap"><ul class="comboselect"></ul></div></div>').insertAfter($this); } else { } var $box = $this.next('.comboselectbox'), $add = $box.find('a.add'), $remove = $box.find('a.remove'), $addall = $box.find('a.addall'), $removeall = $box.find('a.removeall'), $lists = $box.find('.comboselect'), $i = $([]); var name = $this.attr('name'), j = 0, selected = searchresult = []; opts.pool = $lists.eq(0), opts.selection = $lists.eq(1); //add searchfield and its actions if(opts.searchfield){ $searchfield = $('<input>') .bind('keyup.wl_Multiselect', function(){ var term = new RegExp($(this).val(), 'i'); console.log(opts.pool.find('li')); $.each(opts.pool.find('li').not('.used'), function(i, el){ var _el = $(el), _val = _el.data('value')+_el.data('name'); if(term.test(_val)){ _el.removeClass('hidden'); }else{ _el.addClass('hidden'); } }); }).prependTo($box.addClass('searchable').find('.combowrap').eq(0)); } //append a '[]' if isn't set (required for multiple values if (!/\[\]$/.test(name)) $this.attr('name', name + '[]'); //set the height of the box $box.height(opts.height); //if items ar sett append them to the native input if (opts.items.length) { if (opts.selected.length && !$.isArray(opts.selected)) opts.selected = [opts.selected]; $.each(opts.items, function (i, data) { var name, value, selected = ''; if (typeof data == 'object') { name = data.name; value = data.value; } else { name = value = data; } if (opts.selected.length && $.inArray(value, opts.selected) != -1) selected = ' selected'; $i = $i.add($('<option value="' + value + '"' + selected + '>' + name + '</option>')); }); $i.appendTo($this); } //refresh the positions if a change is triggered $this.bind('change.wl_Multiselect', function () { refreshPositions(); }); //clear them opts.items = []; opts.selected = []; //and iterate thru all native options $.each($this.find('option'), function (i, e) { var _this = $(this), name = _this.text(), value = _this.val(); var item = $('<li><a>' + name + '</a></li>').append('<a class="add"></a>').data({ 'pos': i, 'value': value, 'name': name, 'native': _this }).appendTo(opts.pool); opts.items[value] = item; //if it's selected we need it in the selection list if (_this.is(':selected')) { opts.selected.push(value); item.clone(true).data({ 'pos': j++ }).attr('data-value', value).append('<a class="remove"></a>').appendTo(opts.selection).find('.add').remove(); item.data('native').prop('selected', true); item.addClass('used'); if (!opts.showUsed) item.hide(); } }); //Bind click events to the buttons in the middle $add.bind('click.wl_Multiselect', function () { var selection = $.map(opts.pool.find('li.selected'), function (el) { return $(el).data('value'); }); if(opts.searchfield) $searchfield.focus(); $this.wl_Multiselect('select', selection); }); $remove.bind('click.wl_Multiselect', function () { var selection = $.map(opts.selection.find('li.selected'), function (el) { return $(el).data('value'); }); $this.wl_Multiselect('unselect', selection); }); $addall.bind('click.wl_Multiselect', function () { var selection = $.map(opts.pool.find('li').not('.hidden'), function (el) { return $(el).data('value'); }); if(opts.searchfield) $searchfield.val('').trigger('keyup').focus(); $this.wl_Multiselect('select', selection); }); $removeall.bind('click.wl_Multiselect', function () { var selection = $.map(opts.selection.find('li'), function (el) { return $(el).data('value'); }); $this.wl_Multiselect('unselect', selection); }); //Bind events to the elements opts.pool.delegate('li', 'click.wl_Multiselect', { 'list': opts.pool }, clickHandler).delegate('li', 'dblclick.wl_Multiselect', function () { $this.wl_Multiselect('select', $(this).data('value')); }).delegate('a.add', 'click.wl_Multiselect', function () { $this.wl_Multiselect('select', $(this).parent().data('value')); }).disableSelection(); opts.selection.delegate('li', 'click.wl_Multiselect', { 'list': opts.selection }, clickHandler).delegate('a.remove', 'click.wl_Multiselect', function () { $this.wl_Multiselect('unselect', $(this).parent().data('value')); }); //make the selection list sortable opts.selection.sortable({ containment: opts.selection, distance: 20, handle: 'a:first', forcePlaceholderSize: true, forceHelperSize: true, update: function () { refreshPositions(); opts.onSort.call($this[0], $this.data('wl_Multiselect').selected); }, items: 'li' }); //function to refresh positions. simple add a position to the element and sort the native select list function refreshPositions() { var li = opts.pool.find('li').not('.used'), selected = []; $.each(li, function (i) { $(this).data('pos', i); }); li = opts.selection.find('li'); $.each(li, function (i) { var _this = $(this); _this.data('pos', i); opts.items[_this.data('value')].data('native').appendTo($this); selected.push(_this.data('value')); }); $this.data('wl_Multiselect').selected = selected; } //the click handle simulates a native click behaviour on the elements function clickHandler(event) { var _this = $(this), selected = event.data.list.find('li.selected'); //stop when the clicked element is used if (_this.hasClass('used')) return false; //remove the selected class if it's a normal click if (!event.shiftKey && !event.ctrlKey) selected.removeClass('selected'); //shift clicks selects from selected to previous selected element if (event.shiftKey) { var first, second, items = event.data.list.find('li').not('.used'); if (_this.data('pos') > event.data.list.data('last')) { first = event.data.list.data('last'); second = _this.data('pos'); } else { first = _this.data('pos'); second = event.data.list.data('last'); } for (var i = first; i <= second; i++) { items.eq(i).addClass('selected'); } event.data.list.data('last', second); //a normal click (or with ctrl key) select the current one } else { event.data.list.data('last', _this.data('pos')); _this.toggleClass('selected'); } return false; } if (opts) $.extend($this.data('wl_Multiselect'), opts); }); }; $.fn.wl_Multiselect.defaults = { height: 200, items: [], selected: [], showUsed: false, searchfield: true, onAdd: function (values) {}, onRemove: function (values) {}, onSelect: function (values) {}, onUnselect: function (values) {}, onSort: function (values) {} }; $.fn.wl_Multiselect.version = '1.3'; $.fn.wl_Multiselect.methods = { add: function (items, select) { var $this = $(this), opts = $this.data('wl_Multiselect'), i = opts.itemsum || 0, _items = {}; //make an object from the input if (typeof items != 'object') { _items[items] = items; } else if ($.isArray(items)) { for (var i = 0; i < items.length; i++) { _items[items[i]] = items[i]; } } else { _items = items; } //iterate thru all _items $.each(_items, function (value, name) { //make native items var _native = $('<option value="' + value + '">' + name + '</option>').appendTo($this); //and elements var item = $('<li><a>' + name + '</a></li>').append('<a class="add"></a>').data({ 'pos': i++, 'native': _native, 'name': name, 'value': value }).appendTo(opts.pool); //store info in the object $this.data('wl_Multiselect').items[value] = item; if (select) $this.wl_Multiselect('select', value); }); //trigger the callback function opts.onAdd.call($this[0], $.map(_items, function (k, v) { return k; })); }, remove: function (values) { var $this = $(this), opts = $this.data('wl_Multiselect'); if (values && !$.isArray(values)) { values = [values]; } //unselect all values before $this.wl_Multiselect('unselect', values); if(values){ //remove all elements + native options $.each(values, function (i, value) { var item = opts.items[value]; item.data('native').remove(); item.remove(); delete opts.items[value]; $this.data('wl_Multiselect').items = opts.items; }); } //trigger a change $this.trigger('change.wl_Multiselect'); //trigger the callback function opts.onRemove.call($this[0], values); }, select: function (values) { var $this = $(this), opts = $this.data('wl_Multiselect'); if (values && !$.isArray(values)) { values = [values]; } if(values){ //add elements to the selection list and select the native option $.each(values, function (i, value) { var item = opts.items[value]; if (item.hasClass('used')) return; item.removeClass('selected').clone(true).attr('data-value', value).append('<a class="remove"></a>').appendTo(opts.selection).find('.add').remove(); item.data('native').prop('selected', true); item.addClass('used'); if (!opts.showUsed) item.addClass('hidden'); }); } //trigger a change $this.trigger('change.wl_Multiselect'); //trigger the callback function opts.onSelect.call($this[0], values); }, unselect: function (values) { var $this = $(this), opts = $this.data('wl_Multiselect'); if (values && !$.isArray(values)) { values = [values]; } var li = opts.selection.find('li'); if(values){ //remove elements from the selection list and select the native option $.each(values, function (i, value) { var item = opts.items[value]; if (!item.hasClass('used')) return; item.data('native').prop('selected', false); li.filter('[data-value="' + value + '"]').remove(); item.removeClass('used'); if (!opts.showUsed) item.removeClass('hidden'); }); } //trigger a change $this.trigger('change.wl_Multiselect'); //trigger the callback function opts.onUnselect.call($this[0], values); }, clear: function () { var $this = $(this), opts = $this.data('wl_Multiselect'); //unselect all seleted $this.wl_Multiselect('unselect', opts.selected); //trigger a change $this.trigger('change.wl_Multiselect'); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Multiselect.defaults[key] !== undefined) { $this.data('wl_Multiselect')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Time v 1.1 by revaxarts.com /* description: makes a timefield out of an input field /* dependency: jQuery Datepicker, mousewheel plugin, $.leadingZero /*----------------------------------------------------------------------*/ $.fn.wl_Time = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Time.methods[method]) { return $.fn.wl_Time.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Time')) { var opts = $.extend({}, $this.data('wl_Time'), method); } else { var opts = $.extend({}, $.fn.wl_Time.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Time')) { $this.data('wl_Time', {}); $this.bind({ 'mousewheel.wl_Time': function (event, delta) { var opts = $this.data('wl_Time') || opts; if (opts.mousewheel) { event.preventDefault(); //delta must be 1 or -1 (different on macs and with shiftkey pressed) delta = (delta < 0) ? -1 : 1; //scroll thru hours if shift key is pressed if (event.shiftKey) delta *= 60 / opts.step; $.fn.wl_Time.methods.change.call($this[0], delta); } }, 'change.wl_Time': function () { var opts = $this.data('wl_Time') || opts; //correct input value $.fn.wl_Time.methods.correct.call($this[0]); //print it $.fn.wl_Time.methods.printTime.call($this[0]); //callback opts.onChange.call($this[0], opts.time); } //for 12h format ad a little span after the input and set length to 5 (hh:mm) }).after('<span class="timeformat"/>').attr('maxlength', 5); //is connected to a datepicker if (opts.connect !== null) { var _date = $('#' + opts.connect), _oldcallback = opts.onDateChange; //set a callback if the time reaches another date _callback = function (offset) { var current = new Date(_date.datepicker('getDate')).getTime(); if (current) _date.datepicker('setDate', new Date(current + (864e5 * offset))); _oldcallback.call($this[0], offset); }; opts.onDateChange = _callback; } //value is set and has to get translated (self-explanatory) if (opts.value) { var now = new Date().getTime(), date; switch (opts.value) { case 'now': date = new Date(now); break; default: //if a valid number add them as days to the date field if (!isNaN(opts.value)) date = new Date(now + (60000 * (opts.value % 60))); } //set the time (hh:mm) opts.time = $.leadingZero(date.getHours()) + ':' + $.leadingZero(date.getMinutes()); //write it into the input $this.val(opts.time); } } else { } if (opts) $.extend($this.data('wl_Time'), opts); //save value if already set if($this.val().match(/\d\d:\d\d/)){ $this.data('wl_Time').time = $this.val(); //correct input value $.fn.wl_Time.methods.printTime.call($this[0]); } }); }; $.fn.wl_Time.defaults = { step: 5, timeformat: 24, roundtime: true, time: null, value: null, mousewheel: true, onDateChange: function (offset) {}, onHourChange: function (offset) {}, onChange: function (value) {} }; $.fn.wl_Time.version = '1.1'; $.fn.wl_Time.methods = { change: function (delta) { var $this = $(this), opts = $this.data('wl_Time'), _current = new Date('2010/01/01 ' + ($this.data('wl_Time').time || '00:00')), _new = new Date(_current.getTime() + (delta * $this.data('wl_Time').step * 60000)), _hours = _new.getHours(), _minutes = _new.getMinutes(); //round the time on a mousewheel if (opts.roundtime) { _minutes -= (_minutes % $this.data('wl_Time').step); } //save time $this.data('wl_Time').time = $.leadingZero(_hours) + ':' + $.leadingZero(_minutes); //and print it $.fn.wl_Time.methods.printTime.call(this); //callbacks opts.onChange.call(this, $this.data('wl_Time').time); if (Math.abs(_current.getMinutes() - _minutes) == (60 - opts.step)) { opts.onHourChange.call(this, (_hours - _current.getHours())); } if (Math.abs(_current.getHours() - _hours) == (23)) { opts.onDateChange.call(this, (_hours) ? -1 : 1); } }, printTime: function () { var $this = $(this), opts = $this.data('wl_Time'), time = opts.time; if (time) { time = time.split(':'); //calculate the 12h format if (opts.timeformat == 12) { $this.val($.leadingZero(((time[0] % 12 == 0) ? 12 : time[0] % 12)) + ':' + $.leadingZero(time[1])).next().html((time[0] / 12 >= 1) ? 'pm' : 'am'); //or set the 24h format } else { $this.val($.leadingZero(time[0]) + ':' + $.leadingZero(time[1])); } } }, correct: function () { var $this = $(this), val = $this.val(), time; //no value => stop if (val == '') return; //it is not hh:mm format if (!/^\d+:\d+$/.test(val)) { //convert the input (read the docs for more details) if (val.length == 1) { val = "0" + val + ":00"; } else if (val.length == 2) { val = val + ":00"; } else if (val.length == 3) { val = val.substr(0, 2) + ":" + val.substr(2, 3) + "0"; } else if (val.length == 4) { val = val.substr(0, 2) + ":" + val.substr(2, 4); } } time = val.split(':'); //value is wrong or out of range if (!/\d\d:\d\d$/.test(val) && val != "" || time[0] > 23 || time[1] > 59) { $this.val('00:00').focus().select(); $this.data('wl_Time').time = '00:00'; $.fn.wl_Time.methods.printTime.call(this); //value is a time } else { //save it $this.data('wl_Time').time = val; //print it $.fn.wl_Time.methods.printTime.call(this); } }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Time.defaults[key] !== undefined || $.fn.wl_Time.defaults[key] == null) { $this.data('wl_Time')[key] = value; $this.trigger('change.wl_Time'); } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
$(document).ready(function () { var $body = $('body'), $content = $('#content'), $form = $content.find('#loginform'); //IE doen't like that fadein if (!$.browser.msie) $body.fadeTo(0, 0.0).delay(500).fadeTo(1000, 1); $("input").uniform(); $("input[name='UserName']").focus(); $form.wl_Form({ status: false, onBeforeSubmit: function (data) { $form.wl_Form('set', 'sent', false); if (data.UserName && data.Password) { return true; } else { $.wl_Alert('Please provide something!', 'info', '#content'); return false; } }, onSuccess: function (data, textStatus, jqXHR) { if (typeof data == 'string') data = JSON.parse(data); if (data.Success) { window.location.href = data.RedirectUrl; } else { $.wl_Alert(data.Message, 'info', '#content'); } } }); });
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Autocomplete v 1.0 by revaxarts.com /* description: extends the jQuery Autocomplete Function /* dependency: jQUery UI Autocomplete, parseData function /*----------------------------------------------------------------------*/ $.fn.wl_Autocomplete = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Autocomplete.methods[method]) { return $.fn.wl_Autocomplete.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Autocomplete')) { var opts = $.extend({}, $this.data('wl_Autocomplete'), method); } else { var opts = $.extend({}, $.fn.wl_Autocomplete.defaults, method, $this.data()); } } else { try { return $this.autocomplete(method, args[1], args[2]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_Autocomplete')) { $this.data('wl_Autocomplete', {}); //if source is a function use the returning value of that function if ($.isFunction(window[opts.source])) { opts.source = window[opts.source].call(this); } //if it is an string it must be an array to parse (typeof '[1,2,3]' === 'string') if (typeof opts.source === 'string') { opts.source = $.parseData(opts.source, true); } //call the jQueryUI autocomplete plugin $this.autocomplete(opts); } else { } if (opts) $.extend($this.data('wl_Autocomplete'), opts); }); }; $.fn.wl_Autocomplete.defaults = { //check http://jqueryui.com/demos/autocomplete/ for all options }; $.fn.wl_Autocomplete.version = '1.0'; $.fn.wl_Autocomplete.methods = { set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Autocomplete.defaults[key] !== undefined || $.fn.wl_Autocomplete.defaults[key] == null) { $this.data('wl_Autocomplete')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Calendar v 1.0 by revaxarts.com /* description: makes a Calendar /* dependency: fullcalendar plugin (calendar.js) /*----------------------------------------------------------------------*/ $.fn.wl_Calendar = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Calendar.methods[method]) { return $.fn.wl_Calendar.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Calendar')) { var opts = $.extend({}, $this.data('wl_Calendar'), method); } else { var opts = $.extend({}, $.fn.wl_Calendar.defaults, method, $this.data()); } } else { try { return $this.fullCalendar(method, args[1], args[2], args[3], args[4]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_Calendar')) { $this.data('wl_Calendar', {}); //we need to use the jquery UI Theme opts.theme = true; //some shorties for the header, you can add more easily switch (opts.header) { case 'small': opts.header = { left: 'title', right: 'prev,next' }; break; case 'small-today': opts.header = { left: 'title', right: 'prev,today,next' }; break; default: } //call the fullCalendar plugin $this.fullCalendar(opts); } else { } if (opts) $.extend($this.data('wl_Calendar'), opts); }); }; $.fn.wl_Calendar.defaults = {}; $.fn.wl_Calendar.version = '1.0'; $.fn.wl_Calendar.methods = { set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Calendar.defaults[key] !== undefined || $.fn.wl_Calendar.defaults[key] == null) { $this.data('wl_Calendar')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Dialog v 1.1 by revaxarts.com /* description: handles alert boxes, prompt boxes and confirm boxes and /* message boxes /* contains 4 plugins /* dependency: jquery UI Dialog /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Confirm Dialog /* like the native confirm method /*----------------------------------------------------------------------*/ $.confirm = function (text, callback, cancelcallback) { var options = $.extend(true, {}, $.alert.defaults, $.confirm.defaults); //nativ behaviour if (options.nativ) { if (result = confirm(unescape(text))) { if ($.isFunction(callback)) callback.call(this); } else { if ($.isFunction(cancelcallback)) cancelcallback.call(this); } return; } //the callbackfunction var cb = function () { if ($.isFunction(callback)) callback.call(this); $(this).dialog('close'); $('#wl_dialog').remove(); }, //the callbackfunction on cancel ccb = function () { if ($.isFunction(cancelcallback)) cancelcallback.call(this); $(this).dialog('close'); $('#wl_dialog').remove(); }; //set some options options = $.extend({}, { buttons: [{ text: options.text.ok, click: cb }, { text: options.text.cancel, click: ccb }] }, options); //use the dialog return $.alert(unescape(text), options); }; $.confirm.defaults = { text: { header: 'Please confirm', ok: 'Yes', cancel: 'No' } }; /*----------------------------------------------------------------------*/ /* Prompt Dialog /* like the native prompt method /*----------------------------------------------------------------------*/ $.prompt = function (text, value, callback, cancelcallback) { var options = $.extend(true, {}, $.alert.defaults, $.prompt.defaults); //nativ behaviour if (options.nativ) { var val = prompt(unescape($.trim(text)), unescape(value)); if ($.isFunction(callback) && val !== null) { callback.call(this, val); } else { if ($.isFunction(cancelcallback)) cancelcallback.call(this); } return; } //the callbackfunction var cb = function (value) { if ($.isFunction(callback)) callback.call(this, value); $(this).dialog('close'); $('#wl_dialog').remove(); }, //the callbackfunction on cancel ccb = function () { if ($.isFunction(cancelcallback)) cancelcallback.call(this); $(this).dialog('close'); $('#wl_dialog').remove(); }; //set some options options = $.extend({}, { buttons: [{ text: options.text.ok, click: function () { cb.call(this, $('#wl_promptinputfield').val()); } }, { text: options.text.cancel, click: ccb }], open: function () { $('#wl_promptinputfield').focus().select(); $('#wl_promptinputfield').uniform(); $('#wl_promptinputform').bind('submit', function (event) { event.preventDefault(); cb.call(this, $('#wl_promptinputfield').val()); $(this).parent().dialog('close'); $('#wl_dialog').remove(); }); } }, options); //use the dialog return $.alert('<p>' + unescape(text) + '</p><form id="wl_promptinputform"><input id="wl_promptinputfield" name="wl_promptinputfield" value="' + unescape(value) + '"></form>', options); }; $.prompt.defaults = { text: { header: 'Please prompt', ok: 'OK', cancel: 'Cancel' } }; /*----------------------------------------------------------------------*/ /* Alert Dialog /* like the native alert method /*----------------------------------------------------------------------*/ $.alert = function (content, options) { //if no options it is a normal dialog if (!options) { var options = $.extend(true, {}, { buttons: [{ text: $.alert.defaults.text.ok, click: function () { $(this).dialog('close'); $('#wl_dialog').remove(); } }] }, $.alert.defaults); } //nativ behaviour if (options.nativ) { alert(content); return; } //create a container var container = $('<div/>', { id: 'wl_dialog' }).appendTo('body'); //set a header if (options.text.header) { container.attr('title', options.text.header); } //fill the container container.html(content.replace(/\n/g, '<br>')); //display the dialog container.dialog(options); return{ close:function(callback){ container.dialog('close'); container.remove(); if($.isFunction(callback)) callback.call(this); }, setHeader:function(text){ this.set('title',text); }, setBody:function(html){ container.html(html); }, set:function(option, value){ container.dialog("option", option, value); } } }; $.alert.defaults = { nativ: false, resizable: false, modal: true, text: { header: 'Notification', ok: 'OK' } }; /*----------------------------------------------------------------------*/ /* Message Function /*----------------------------------------------------------------------*/ $.msg = function (content, options) { //get the options var options = $.extend({}, $.msg.defaults, options); var container = $('#wl_msg'),msgbox; //the container doen't exists => create it if (!container.length) { container = $('<div/>', { id: 'wl_msg' }).appendTo('body').data('msgcount', 0); var topoffset = parseInt(container.css('top'), 10); //bind some events to it container.bind('mouseenter', function () { container.data('pause', true); }).bind('mouseleave', function () { container.data('pause', false); }); container.delegate('.msg-close', 'click', function () { container.data('pause', false); close($(this).parent()); }); container.delegate('.msg-box-close', 'click', function () { container.fadeOutSlide(options.fadeTime); }); //bind the scroll event $(window).unbind('scroll.wl_msg').bind('scroll.wl_msg', function () { var pos = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; if (pos > topoffset) { (window.navigator.standalone === undefined) ? container.css({ position: 'fixed', top: 10 }) : container.css({ top: pos + 10 }); } else { (window.navigator.standalone === undefined) ? container.removeAttr('style') : container.css({ top: topoffset }); } }).trigger('scroll.wl_msg'); } //stop if no content is set if(!content)return false; //count of displayed messages var count = container.data('msgcount'); function getHTML(content, headline) { return '<div class="msg-box"><h3>' + (headline || '') + '</h3><a class="msg-close">close</a><div class="msg-content">' + content.replace('\n', '<br>') + '</div></div>'; } function create() { msgbox = $(getHTML(content, options.header)), closeall = $('.msg-box-close'); //we have some messages allready if (count) { //No close all button if (!closeall.length) { msgbox.appendTo(container); $('<div class="msg-box-close">close all</div>').appendTo(container).fadeInSlide(options.fadeTime); //Close all button } else { msgbox.insertBefore(closeall); } //first message } else { msgbox.appendTo(container); } //fade it in nicely msgbox.fadeInSlide(options.fadeTime); //add the count of the messages to the container container.data('msgcount', ++count); //outclose it only if it's not sticky if (!options.sticky) { close(msgbox, options.live); } } function close(item, delay, callback) { if ($.isFunction(delay)){ callback = delay; delay = 0; }else if(!delay){ delay = 0; } setTimeout(function () { //if the mouse isn't over the container if (!container.data('pause')) { item.fadeOutSlide(options.fadeTime, function () { var count = $('.msg-box').length; if (count < 2 && $('.msg-box-close').length) { $('.msg-box-close').fadeOutSlide(options.fadeTime); } container.data('msgcount', count); if($.isFunction(callback)) callback.call(item); }) //try again... } else { close(item, delay); } }, delay); } //create the messsage create(); return { close:function(callback){ close(msgbox,callback); }, setHeader:function(text){ msgbox.find('h3').eq(0).text(text); }, setBody:function(html){ msgbox.find('.msg-content').eq(0).html(html); }, closeAll:function(callback){ container.fadeOutSlide(options.fadeTime, function(){ if($.isFunction(callback)) callback.call(this); }); } } }; $.msg.defaults = { header: null, live: 5000, topoffset: 90, fadeTime: 500, sticky: false }; //initial call to prevent IE to jump to the top $(document).ready(function() {$.msg(false);});
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Color v 1.0 by revaxarts.com /* description: Makes a colorpicker on an input field /* dependency: miniColors Plugin /*----------------------------------------------------------------------*/ $.fn.wl_Color = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Color.methods[method]) { return $.fn.wl_Color.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Color')) { var opts = $.extend({}, $this.data('wl_Color'), method); } else { var opts = $.extend({}, $.fn.wl_Color.defaults, method, $this.data()); } } else { try { return $this.miniColors(method, args[1]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_Color')) { $this.data('wl_Color', {}); //bind the mouswheel event $this.bind('mousewheel.wl_Color', function (event, delta) { if (opts.mousewheel) { event.preventDefault(); //delta must be 1 or -1 (different on macs and with shiftkey pressed) var delta = (delta < 0) ? -1 : 1, hsb = $this.data('hsb'); //saturation with shift key if(event.shiftKey){ hsb.s -= delta*2; hsb.s = Math.round(Math.max(0,Math.min(100,hsb.s))); //hue with alt key }else if(event.altKey && event.shiftKey){ hsb.h += delta*5; hsb.h = Math.round(hsb.h); //brightness without additional key }else{ hsb.b += delta*2; hsb.b = Math.round(Math.max(0,Math.min(100,hsb.b))); } $this.miniColors('value',hsb); $this.trigger('change.wl_Color'); } }); //call the miniColors plugin with extra options $this.miniColors($.extend({}, { change: function (hex, rgb) { $(this).trigger('change.wl_Color'); } }), opts).trigger('keyup.miniColors'); //bind a change event to the evet field for the callback $this.bind('change.wl_Color', function () { var val = $(this).val(); if (val && !/^#/.test(val)) val = '#'+val; $(this).val(val); opts.onChange.call($this[0], $(this).data('hsb'), val); }) //hex values have 7 chars with # .attr('maxlength',7); //prepend a '#' if not set var val = $this.val(); if (val && !/^#/.test($this.val())) { $this.val('#' + val.substr(0,6)); } } else { } if (opts) $.extend($this.data('wl_Color'), opts); }); }; $.fn.wl_Color.defaults = { mousewheel: true, onChange: function (hsb, rgb) {} }; $.fn.wl_Color.version = '1.0'; $.fn.wl_Color.methods = { destroy: function () { var $this = $(this); //destroy them $this.removeData('wl_Color'); $this.miniColors('destroy'); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Color.defaults[key] !== undefined) { $this.data('wl_Color')[key] = value; } else if (key == 'value') { $this.val(value).trigger('keyup.miniColors'); } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
/*----------------------------------------------------------------------*/ /* wl_Password v 1.0.1 by revaxarts.com /* description: handles password fields /* dependency: none /*----------------------------------------------------------------------*/ $.fn.wl_Password = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($this.data('wl_Password') && $this.data('wl_Password').confirmfield) { return; } if ($.fn.wl_Password.methods[method]) { return $.fn.wl_Password.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Password')) { var opts = $.extend({}, $this.data('wl_Password'), method); } else { var opts = $.extend({}, $.fn.wl_Password.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Password')) { $this.data('wl_Password', {}); //The strnghtmeter var $strength = $('<div/>', { 'class': 'passwordstrength' }).appendTo($this.parent()).hide(); //if confirm field if (opts.confirm) { //clone the password field and append it after the field or after the strengthmeter. Hide it opts.connect = this.id + '_confirm'; var $confirm = $($this.addClass('password').clone()).attr({ 'id': opts.connect, 'name': opts.connect }).appendTo($this.parent()).removeAttr('required').hide(); $confirm.data('wl_Password', { confirmfield: true }); } $this.bind({ //focus triggers a keyup 'focus.wl_Password': function () { $this.trigger('keyup.wl_Password'); }, //blur sets the strengthmeter 'blur.wl_Password': function () { var opts = $this.data('wl_Password') || opts; if ($this.val()) { if (opts.confirm && !$confirm.val()) $strength.text(opts.text.confirm); } else { $strength.hide(); if (opts.confirm) $confirm.hide(); } }, 'keyup.wl_Password': function () { var opts = $this.data('wl_Password') || opts; //if value is set if ($this.val()) { //show optional confirm field if (opts.confirm) $confirm.show(); //get the strength of the current value var _strength = getStrength($this.val(), opts.minLength); //show optional strengthmeter if (opts.showStrength) { $strength.show(); $strength.attr('class', 'passwordstrength').addClass('s_' + _strength).text(opts.words[_strength]); } //add strength to the DOM element $this.data('wl_Password').strength = _strength; //hide siblings if no value is set } else { if (opts.showStrength) $strength.hide(); if (opts.confirm) $confirm.val('').hide(); } } }); //bind only when confirmation and strengthmeter is active if (opts.confirm && opts.showStrength) { $confirm.bind('keyup.wl_Password', function () { var opts = $this.data('wl_Password') || opts; if (!$confirm.val()) { //confirm text $strength.text(opts.text.confirm); } else if ($confirm.val() != $this.val()) { //password doesn't match $strength.text(opts.text.nomatch); } else { //password match => show strength $strength.text(opts.words[$this.data('wl_Password').strength]); } }); } //calculates the strenght of a password //must return a value between 0 and 5 //value is the password function getStrength(value, minLength) { var score = 0; if (value.length < minLength) { return score } else { score = Math.min(15, (score + (value.length) * 2)); } if (value.match(/[a-z]/)) score += 1; if (value.match(/[A-Z]/)) score += 5; if (value.match(/\d+/)) score += 5; if (value.match(/(.*[0-9].*[0-9].*[0-9])/)) score += 7; if (value.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)) score += 5; if (value.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) score += 7; if (value.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) score += 2; if (value.match(/([a-zA-Z])/) && value.match(/([0-9])/)) score += 3; if (value.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/)) score += 3; return Math.min(5, Math.ceil(score / 10)); } } else { } if (opts) $.extend($this.data('wl_Password'), opts); }); }; $.fn.wl_Password.defaults = { confirm: true, showStrength: true, words: ['too short', 'bad', 'medium', 'good', 'very good', 'excellent'], minLength: 3, text: { confirm: 'please confirm', nomatch: 'password doesn\'t match' } }; $.fn.wl_Password.version = '1.0.1'; $.fn.wl_Password.methods = { set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Password.defaults[key] !== undefined || $.fn.wl_Password.defaults[key] == null) { $this.data('wl_Password')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
JavaScript
var Wami = window.Wami || {}; // Upon a creation of a new Wami.GUI(options), we assume that a WAMI recorder // has been initialized. Wami.GUI = function(options) { var RECORD_BUTTON = 1; var PLAY_BUTTON = 2; setOptions(options); setupDOM(); var recordButton, playButton; var recordInterval, playInterval; function createDiv(id, style) { var div = document.createElement("div"); if (id) { div.setAttribute('id', id); } if (style) { div.style.cssText = style; } return div; } function setOptions(options) { if (!options.buttonUrl) { options.buttonUrl = "buttons.png"; } if (typeof options.listen == 'undefined' || options.listen) { listen(); } } function setupDOM() { var guidiv = createDiv(null, "position: absolute; width: 214px; height: 137px;"); document.getElementById(options.id).appendChild(guidiv); var rid = Wami.createID(); var recordDiv = createDiv(rid, "position: absolute; left: 40px; top: 25px"); guidiv.appendChild(recordDiv); recordButton = new Button(rid, RECORD_BUTTON, options.buttonUrl); recordButton.onstart = startRecording; recordButton.onstop = stopRecording; recordButton.setEnabled(true); if (!options.singleButton) { var pid = Wami.createID(); var playDiv = createDiv(pid, "position: absolute; right: 40px; top: 25px"); guidiv.appendChild(playDiv); playButton = new Button(pid, PLAY_BUTTON, options.buttonUrl); playButton.onstart = startPlaying; playButton.onstop = stopPlaying; } } /** * These methods are called on clicks from the GUI. */ function startRecording() { if (!options.recordUrl) { alert("No record Url specified!"); } recordButton.setActivity(0); playButton.setEnabled(false); Wami.startRecording(options.recordUrl, Wami.nameCallback(onRecordStart), Wami .nameCallback(onRecordFinish), Wami .nameCallback(onError)); } function stopRecording() { Wami.stopRecording(); clearInterval(recordInterval); recordButton.setEnabled(true); } function startPlaying() { if (!options.playUrl) { alert('No play URL specified!'); } playButton.setActivity(0); recordButton.setEnabled(false); Wami.startPlaying(options.playUrl, Wami.nameCallback(onPlayStart), Wami .nameCallback(onPlayFinish), Wami.nameCallback(onError)); } function stopPlaying() { Wami.stopPlaying(); } this.setPlayUrl = function(url) { options.playUrl = url; } this.setRecordUrl = function(url) { options.recordUrl = url; } this.setPlayEnabled = function(val) { playButton.setEnabled(val); } this.setRecordEnabled = function(val) { recordButton.setEnabled(val); } /** * Callbacks from the flash indicating certain events */ function onError(e) { alert(e); } function onRecordStart() { recordInterval = setInterval(function() { if (recordButton.isActive()) { var level = Wami.getRecordingLevel(); recordButton.setActivity(level); } }, 200); if (options.onRecordStart) { options.onRecordStart(); } } function onRecordFinish() { playButton.setEnabled(true); if (options.onRecordFinish) { options.onRecordFinish(); } } function onPlayStart() { playInterval = setInterval(function() { if (playButton.isActive()) { var level = Wami.getPlayingLevel(); playButton.setActivity(level); } }, 200); if (options.onPlayStart) { options.onPlayStart(); } } function onPlayFinish() { clearInterval(playInterval); recordButton.setEnabled(true); playButton.setEnabled(true); if (options.onPlayFinish) { options.onPlayFinish(); } } function listen() { Wami.startListening(); // Continually listening when the window is in focus allows us to // buffer a little audio before the users clicks, since sometimes // people talk too soon. Without "listening", the audio would record // exactly when startRecording() is called. window.onfocus = function() { Wami.startListening(); }; // Note that the use of onfocus and onblur should probably be replaced // with a more robust solution (e.g. jQuery's $(window).focus(...) window.onblur = function() { Wami.stopListening(); }; } function Button(buttonid, type, url) { var self = this; self.active = false; self.type = type; init(); // Get the background button image position // Index: 1) normal 2) pressed 3) mouse-over function background(index) { if (index == 1) return "-56px 0px"; if (index == 2) return "0px 0px"; if (index == 3) return "-112px 0"; alert("Background not found: " + index); } // Get the type of meter and its state // Index: 1) enabled 2) meter 3) disabled function meter(index, offset) { var top = 5; if (offset) top += offset; if (self.type == RECORD_BUTTON) { if (index == 1) return "-169px " + top + "px"; if (index == 2) return "-189px " + top + "px"; if (index == 3) return "-249px " + top + "px"; } else { if (index == 1) return "-269px " + top + "px"; if (index == 2) return "-298px " + top + "px"; if (index == 3) return "-327px " + top + "px"; } alert("Meter not found: " + self.type + " " + index); } function silhouetteWidth() { if (self.type == RECORD_BUTTON) { return "20px"; } else { return "29px"; } } function mouseHandler(e) { var rightclick; if (!e) var e = window.event; if (e.which) rightclick = (e.which == 3); else if (e.button) rightclick = (e.button == 2); if (!rightclick) { if (self.active && self.onstop) { self.active = false; self.onstop(); } else if (!self.active && self.onstart) { self.active = true; self.onstart(); } } } function init() { var div = document.createElement("div"); var elem = document.getElementById(buttonid); if (elem) { elem.appendChild(div); } else { alert('Could not find element on page named ' + buttonid); } self.guidiv = document.createElement("div"); self.guidiv.style.width = '56px'; self.guidiv.style.height = '63px'; self.guidiv.style.cursor = 'pointer'; self.guidiv.style.background = "url(" + url + ") no-repeat"; self.guidiv.style.backgroundPosition = background(1); div.appendChild(self.guidiv); // margin auto doesn't work in IE quirks mode // http://stackoverflow.com/questions/816343/why-will-this-div-img-not-center-in-ie8 // text-align is a hack to force it to work even if you forget the // doctype. self.guidiv.style.textAlign = 'center'; self.meterDiv = document.createElement("div"); self.meterDiv.style.width = silhouetteWidth(); self.meterDiv.style.height = '63px'; self.meterDiv.style.margin = 'auto'; self.meterDiv.style.cursor = 'pointer'; self.meterDiv.style.position = 'relative'; self.meterDiv.style.background = "url(" + url + ") no-repeat"; self.meterDiv.style.backgroundPosition = meter(2); self.guidiv.appendChild(self.meterDiv); self.coverDiv = document.createElement("div"); self.coverDiv.style.width = silhouetteWidth(); self.coverDiv.style.height = '63px'; self.coverDiv.style.margin = 'auto'; self.coverDiv.style.cursor = 'pointer'; self.coverDiv.style.position = 'relative'; self.coverDiv.style.background = "url(" + url + ") no-repeat"; self.coverDiv.style.backgroundPosition = meter(1); self.meterDiv.appendChild(self.coverDiv); self.active = false; self.guidiv.onmousedown = mouseHandler; } self.isActive = function() { return self.active; } self.setActivity = function(level) { self.guidiv.onmouseout = function() { }; self.guidiv.onmouseover = function() { }; self.guidiv.style.backgroundPosition = background(2); self.coverDiv.style.backgroundPosition = meter(1, 5); self.meterDiv.style.backgroundPosition = meter(2, 5); var totalHeight = 31; var maxHeight = 9; // When volume goes up, the black image loses height, // creating the perception of the colored one increasing. var height = (maxHeight + totalHeight - Math.floor(level / 100 * totalHeight)); self.coverDiv.style.height = height + "px"; } self.setEnabled = function(enable) { var guidiv = self.guidiv; self.active = false; if (enable) { self.coverDiv.style.backgroundPosition = meter(1); self.meterDiv.style.backgroundPosition = meter(1); guidiv.style.backgroundPosition = background(1); guidiv.onmousedown = mouseHandler; guidiv.onmouseover = function() { guidiv.style.backgroundPosition = background(3); }; guidiv.onmouseout = function() { guidiv.style.backgroundPosition = background(1); }; } else { self.coverDiv.style.backgroundPosition = meter(3); self.meterDiv.style.backgroundPosition = meter(3); guidiv.style.backgroundPosition = background(1); guidiv.onmousedown = null; guidiv.onmouseout = function() { }; guidiv.onmouseover = function() { }; } } } }
JavaScript
var Wami = window.Wami || {}; // Returns a (very likely) unique string with of random letters and numbers Wami.createID = function() { return "wid" + ("" + 1e10).replace(/[018]/g, function(a) { return (a ^ Math.random() * 16 >> a / 4).toString(16) }); } // Creates a named callback in WAMI and returns the name as a string. Wami.nameCallback = function(cb, cleanup) { Wami._callbacks = Wami._callbacks || {}; var id = Wami.createID(); Wami._callbacks[id] = function() { if (cleanup) { Wami._callbacks[id] = null; } cb.apply(null, arguments); }; var named = "Wami._callbacks['" + id + "']"; return named; } // This method ensures that a WAMI recorder is operational, and that // the following API is available in the Wami namespace. All functions // must be named (i.e. cannot be anonymous). // // Wami.startPlaying(url, startfn = null, finishedfn = null, failedfn = null); // Wami.stopPlaying() // // Wami.startRecording(url, startfn = null, finishedfn = null, failedfn = null); // Wami.stopRecording() // // Wami.getRecordingLevel() // Returns a number between 0 and 100 // Wami.getPlayingLevel() // Returns a number between 0 and 100 // // Wami.hide() // Wami.show() // // Manipulate the WAMI recorder's settings. In Flash // we need to check if the microphone permission has been granted. // We might also set/return sample rate here, etc. // // Wami.getSettings(); // Wami.setSettings(options); // // Optional way to set up browser so that it's constantly listening // This is to prepend audio in case the user starts talking before // they click-to-talk. // // Wami.startListening() // Wami.setup = function(options) { if (Wami.startRecording) { // Wami's already defined. if (options.onReady) { options.onReady(); } return; } // Assumes that swfobject.js is included if Wami.swfobject isn't // already defined. Wami.swfobject = Wami.swfobject || swfobject; if (!Wami.swfobject) { alert("Unable to find swfobject to help embed the SWF."); } var _options; setOptions(options); embedWamiSWF(_options.id, Wami.nameCallback(delegateWamiAPI)); function supportsTransparency() { // Detecting the OS is a big no-no in Javascript programming, but // I can't think of a better way to know if wmode is supported or // not... since NOT supporting it (like Flash on Ubuntu) is a bug. return (navigator.platform.indexOf("Linux") == -1); } function setOptions(options) { // Start with default options _options = { swfUrl : "Wami.swf", onReady : function() { Wami.hide(); }, onSecurity : checkSecurity, onError : function(error) { alert(error); } }; if (typeof options == 'undefined') { alert('Need at least an element ID to place the Flash object.'); } if (typeof options == 'string') { _options.id = options; } else { _options.id = options.id; } if (options.swfUrl) { _options.swfUrl = options.swfUrl; } if (options.onReady) { _options.onReady = options.onReady; } if (options.onLoaded) { _options.onLoaded = options.onLoaded; } if (options.onSecurity) { _options.onSecurity = options.onSecurity; } if (options.onError) { _options.onError = options.onError; } // Create a DIV for the SWF under _options.id var container = document.createElement('div'); container.style.position = 'absolute'; _options.cid = Wami.createID(); container.setAttribute('id', _options.cid); var swfdiv = document.createElement('div'); var id = Wami.createID(); swfdiv.setAttribute('id', id); container.appendChild(swfdiv); document.getElementById(_options.id).appendChild(container); _options.id = id; } function checkSecurity() { var settings = Wami.getSettings(); if (settings.microphone.granted) { _options.onReady(); } else { // Show any Flash settings panel you want: // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/SecurityPanel.html Wami.showSecurity("privacy", "Wami.show", Wami .nameCallback(_options.onSecurity), Wami .nameCallback(_options.onError)); } } // Embed the WAMI SWF and call the named callback function when loaded. function embedWamiSWF(id, initfn) { var flashVars = { visible : false, loadedCallback : initfn } var params = { allowScriptAccess : "always" } if (supportsTransparency()) { params.wmode = "transparent"; } if (typeof console !== 'undefined') { flashVars.console = true; } var version = '10.0.0'; document.getElementById(id).innerHTML = "WAMI requires Flash " + version + " or greater<br />https://get.adobe.com/flashplayer/"; // This is the minimum size due to the microphone security panel Wami.swfobject.embedSWF(_options.swfUrl, id, 214, 137, version, null, flashVars, params); // Without this line, Firefox has a dotted outline of the flash Wami.swfobject.createCSS("#" + id, "outline:none"); } // To check if the microphone settings were 'remembered', we // must actually embed an entirely new Wami client and check // whether its microphone is granted. If it is, it was remembered. function checkRemembered(finishedfn) { var id = Wami.createID(); var div = document.createElement('div'); div.style.top = '-999px'; div.style.left = '-999px'; div.setAttribute('id', id); var body = document.getElementsByTagName('body').item(0); body.appendChild(div); var fn = Wami.nameCallback(function() { var swf = document.getElementById(id); Wami._remembered = swf.getSettings().microphone.granted; Wami.swfobject.removeSWF(id); eval(finishedfn + "()"); }); embedWamiSWF(id, fn); } // Attach all the audio methods to the Wami namespace in the callback. function delegateWamiAPI() { var recorder = document.getElementById(_options.id); function delegate(name) { Wami[name] = function() { return recorder[name].apply(recorder, arguments); } } delegate('startPlaying'); delegate('stopPlaying'); delegate('startRecording'); delegate('stopRecording'); delegate('startListening'); delegate('stopListening'); delegate('getRecordingLevel'); delegate('getPlayingLevel'); delegate('setSettings'); // Append extra information about whether mic settings are sticky Wami.getSettings = function() { var settings = recorder.getSettings(); settings.microphone.remembered = Wami._remembered; return settings; } Wami.showSecurity = function(panel, startfn, finishedfn, failfn) { // Flash must be on top for this. var container = document.getElementById(_options.cid); var augmentedfn = Wami.nameCallback(function() { checkRemembered(finishedfn); container.style.cssText = "position: absolute;"; }); container.style.cssText = "position: absolute; z-index: 99999"; recorder.showSecurity(panel, startfn, augmentedfn, failfn); } Wami.show = function() { if (!supportsTransparency()) { recorder.style.visibility = "visible"; } } Wami.hide = function() { // Hiding flash in all the browsers is tricky. Please read: // https://code.google.com/p/wami-recorder/wiki/HidingFlash if (!supportsTransparency()) { recorder.style.visibility = "hidden"; } } // If we already have permissions, they were previously 'remembered' Wami._remembered = recorder.getSettings().microphone.granted; if (_options.onLoaded) { _options.onLoaded(); } if (!_options.noSecurityCheck) { checkSecurity(); } } }
JavaScript
/** * @license Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time to build CKEditor again. * * If you would like to build CKEditor online again * (for example to upgrade), visit one the following links: * * (1) http://ckeditor.com/builder * Visit online builder to build CKEditor from scratch. * * (2) http://ckeditor.com/builder/0ebaeed5189874e28f9af28caed38f94 * Visit online builder to build CKEditor, starting with the same setup as before. * * (3) http://ckeditor.com/builder/download/0ebaeed5189874e28f9af28caed38f94 * Straight download link to the latest version of CKEditor (Optimized) with the same setup as before. * * NOTE: * This file is not used by CKEditor, you may remove it. * Changing this file will not change your CKEditor configuration. */ var CKBUILDER_CONFIG = { skin: 'moonocolor', preset: 'standard', ignore: [ 'dev', '.gitignore', '.gitattributes', 'README.md', '.mailmap' ], plugins : { 'basicstyles' : 1, 'blockquote' : 1, 'clipboard' : 1, 'contextmenu' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'filebrowser' : 1, 'floatingspace' : 1, 'format' : 1, 'horizontalrule' : 1, 'htmlwriter' : 1, 'image' : 1, 'indentlist' : 1, 'link' : 1, 'list' : 1, 'magicline' : 1, 'maximize' : 1, 'pastefromword' : 1, 'pastetext' : 1, 'removeformat' : 1, 'resize' : 1, 'scayt' : 1, 'showborders' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tabletools' : 1, 'toolbar' : 1, 'undo' : 1, 'wsc' : 1, 'wysiwygarea' : 1 }, languages : { 'en' : 1 } };
JavaScript
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. // For complete reference see: // http://docs.ckeditor.com/#!/api/CKEDITOR.config // The toolbar groups arrangement, optimized for two toolbar rows. config.toolbarGroups = [ { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] }, { name: 'links' }, { name: 'insert' }, { name: 'forms' }, { name: 'tools' }, { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'others' }, '/', { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] }, { name: 'styles' }, { name: 'colors' }, { name: 'about' } ]; // Remove some buttons provided by the standard plugins, which are // not needed in the Standard(s) toolbar. config.removeButtons = 'Underline,Subscript,Superscript'; // Set the most common block elements. config.format_tags = 'p;h1;h2;h3;pre'; // Simplify the dialog windows. config.removeDialogTabs = 'image:advanced;link:advanced'; };
JavaScript
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */
JavaScript
/** * Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ // This file contains style definitions that can be used by CKEditor plugins. // // The most common use for it is the "stylescombo" plugin, which shows a combo // in the editor toolbar, containing all styles. Other plugins instead, like // the div plugin, use a subset of the styles on their feature. // // If you don't have plugins that depend on this file, you can simply ignore it. // Otherwise it is strongly recommended to customize this file to match your // website requirements and design properly. CKEDITOR.stylesSet.add( 'default', [ /* Block Styles */ // These styles are already available in the "Format" combo ("format" plugin), // so they are not needed here by default. You may enable them to avoid // placing the "Format" combo in the toolbar, maintaining the same features. /* { name: 'Paragraph', element: 'p' }, { name: 'Heading 1', element: 'h1' }, { name: 'Heading 2', element: 'h2' }, { name: 'Heading 3', element: 'h3' }, { name: 'Heading 4', element: 'h4' }, { name: 'Heading 5', element: 'h5' }, { name: 'Heading 6', element: 'h6' }, { name: 'Preformatted Text',element: 'pre' }, { name: 'Address', element: 'address' }, */ { name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } }, { name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } }, { name: 'Special Container', element: 'div', styles: { padding: '5px 10px', background: '#eee', border: '1px solid #ccc' } }, /* Inline Styles */ // These are core styles available as toolbar buttons. You may opt enabling // some of them in the Styles combo, removing them from the toolbar. // (This requires the "stylescombo" plugin) /* { name: 'Strong', element: 'strong', overrides: 'b' }, { name: 'Emphasis', element: 'em' , overrides: 'i' }, { name: 'Underline', element: 'u' }, { name: 'Strikethrough', element: 'strike' }, { name: 'Subscript', element: 'sub' }, { name: 'Superscript', element: 'sup' }, */ { name: 'Marker', element: 'span', attributes: { 'class': 'marker' } }, { name: 'Big', element: 'big' }, { name: 'Small', element: 'small' }, { name: 'Typewriter', element: 'tt' }, { name: 'Computer Code', element: 'code' }, { name: 'Keyboard Phrase', element: 'kbd' }, { name: 'Sample Text', element: 'samp' }, { name: 'Variable', element: 'var' }, { name: 'Deleted Text', element: 'del' }, { name: 'Inserted Text', element: 'ins' }, { name: 'Cited Work', element: 'cite' }, { name: 'Inline Quotation', element: 'q' }, { name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } }, { name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } }, /* Object Styles */ { name: 'Styled image (left)', element: 'img', attributes: { 'class': 'left' } }, { name: 'Styled image (right)', element: 'img', attributes: { 'class': 'right' } }, { name: 'Compact table', element: 'table', attributes: { cellpadding: '5', cellspacing: '0', border: '1', bordercolor: '#ccc' }, styles: { 'border-collapse': 'collapse' } }, { name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } }, { name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } } ] );
JavaScript
/** * Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'myDialog', function( editor ) { return { title: 'My Dialog', minWidth: 400, minHeight: 200, contents: [ { id: 'tab1', label: 'First Tab', title: 'First Tab', elements: [ { id: 'input1', type: 'text', label: 'Text Field' }, { id: 'select1', type: 'select', label: 'Select Field', items: [ [ 'option1', 'value1' ], [ 'option2', 'value2' ] ] } ] }, { id: 'tab2', label: 'Second Tab', title: 'Second Tab', elements: [ { id: 'button1', type: 'button', label: 'Button Field' } ] } ] }; } );
JavaScript
/** * Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ // Tool scripts for the sample pages. // This file can be ignored and is not required to make use of CKEditor. ( function() { CKEDITOR.on( 'instanceReady', function( ev ) { // Check for sample compliance. var editor = ev.editor, meta = CKEDITOR.document.$.getElementsByName( 'ckeditor-sample-required-plugins' ), requires = meta.length ? CKEDITOR.dom.element.get( meta[ 0 ] ).getAttribute( 'content' ).split( ',' ) : [], missing = [], i; if ( requires.length ) { for ( i = 0; i < requires.length; i++ ) { if ( !editor.plugins[ requires[ i ] ] ) missing.push( '<code>' + requires[ i ] + '</code>' ); } if ( missing.length ) { var warn = CKEDITOR.dom.element.createFromHtml( '<div class="warning">' + '<span>To fully experience this demo, the ' + missing.join( ', ' ) + ' plugin' + ( missing.length > 1 ? 's are' : ' is' ) + ' required.</span>' + '</div>' ); warn.insertBefore( editor.container ); } } // Set icons. var doc = new CKEDITOR.dom.document( document ), icons = doc.find( '.button_icon' ); for ( i = 0; i < icons.count(); i++ ) { var icon = icons.getItem( i ), name = icon.getAttribute( 'data-icon' ), style = CKEDITOR.skin.getIconStyle( name, ( CKEDITOR.lang.dir == 'rtl' ) ); icon.addClass( 'cke_button_icon' ); icon.addClass( 'cke_button__' + name + '_icon' ); icon.setAttribute( 'style', style ); icon.setStyle( 'float', 'none' ); } } ); } )();
JavaScript
/*! * iCheck v0.9.1, http://git.io/uhUPMA * ================================= * Powerful Zepto plugin for checkboxes and radio buttons customization * * (c) 2013 Damir Foy, http://damirfoy.com * MIT Licensed */ (function($) { // Cached vars var _iCheck = 'iCheck', _iCheckHelper = _iCheck + '-helper', _checkbox = 'checkbox', _radio = 'radio', _checked = 'checked', _unchecked = 'un' + _checked, _disabled = 'disabled', _determinate = 'determinate', _indeterminate = 'in' + _determinate, _update = 'update', _type = 'type', _click = 'click', _touch = 'touchbegin.i touchend.i', _add = 'addClass', _remove = 'removeClass', _callback = 'trigger', _label = 'label', _cursor = 'cursor', _mobile = /ipad|iphone|ipod|android|blackberry|windows phone|opera mini/i.test(navigator.userAgent); // Plugin init $.fn[_iCheck] = function(options, fire) { // Walker var handle = 'input[type="' + _checkbox + '"], input[type="' + _radio + '"]', stack = $(), walker = function(object) { object.each(function() { var self = $(this); if (self.is(handle)) { stack = stack.add(self); } else { stack = stack.add(self.find(handle)); }; }); }; // Check if we should operate with some method if (/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(options)) { // Normalize method's name options = options.toLowerCase(); // Find checkboxes and radio buttons walker(this); return stack.each(function() { var self = $(this); if (options == 'destroy') { tidy(self, 'ifDestroyed'); } else { operate(self, true, options); }; // Fire method's callback if ($.isFunction(fire)) { fire(); }; }); // Customization } else if (typeof options == 'object' || !options) { // Check if any options were passed var settings = $.extend({ checkedClass: _checked, disabledClass: _disabled, indeterminateClass: _indeterminate, labelHover: true }, options), selector = settings.handle, hoverClass = settings.hoverClass || 'hover', focusClass = settings.focusClass || 'focus', activeClass = settings.activeClass || 'active', labelHover = !!settings.labelHover, labelHoverClass = settings.labelHoverClass || 'hover', // Setup clickable area area = ('' + settings.increaseArea).replace('%', '') | 0; // Selector limit if (selector == _checkbox || selector == _radio) { handle = 'input[type="' + selector + '"]'; }; // Clickable area limit if (area < -50) { area = -50; }; // Walk around the selector walker(this); return stack.each(function() { var self = $(this); // If already customized tidy(self); var node = this, id = node.id, // Layer styles offset = -area + '%', size = 100 + (area * 2) + '%', layer = { position: 'absolute', top: offset, left: offset, display: 'block', width: size, height: size, margin: 0, padding: 0, background: '#fff', border: 0, opacity: 0 }, // Choose how to hide input hide = _mobile ? { position: 'absolute', visibility: 'hidden' } : area ? layer : { position: 'absolute', opacity: 0 }, // Get proper class className = node[_type] == _checkbox ? settings.checkboxClass || 'i' + _checkbox : settings.radioClass || 'i' + _radio, // Find assigned labels label = $(_label + '[for="' + id + '"]').add(self.closest(_label)), // Wrap input parent = self.wrap('<div class="' + className + '"/>')[_callback]('ifCreated').parent().append(settings.insert), // Layer addition helper = $('<ins class="' + _iCheckHelper + '"/>').css(layer).appendTo(parent); // Finalize customization self.data(_iCheck, {o: settings, s: self.attr('style')}).css(hide); !!settings.inheritClass && parent[_add](node.className || ''); !!settings.inheritID && id && parent.attr('id', _iCheck + '-' + id); parent.css('position') == 'static' && parent.css('position', 'relative'); operate(self, true, _update); // Label events if (label.length) { label.on(_click + '.i mouseover.i mouseout.i ' + _touch, function(event) { var type = event[_type], item = $(this); // Do nothing if input is disabled if (!node[_disabled]) { // Click if (type == _click) { operate(self, false, true); // Hover state } else if (labelHover) { // mouseout|touchend if (/ut|nd/.test(type)) { parent[_remove](hoverClass); item[_remove](labelHoverClass); } else { parent[_add](hoverClass); item[_add](labelHoverClass); }; }; if (_mobile) { event.stopPropagation(); } else { return false; }; }; }); }; // Input events self.on(_click + '.i focus.i blur.i keyup.i keydown.i keypress.i', function(event) { var type = event[_type], key = event.keyCode; // Click if (type == _click) { return false; // Keydown } else if (type == 'keydown' && key == 32) { if (!(node[_type] == _radio && node[_checked])) { if (node[_checked]) { off(self, _checked); } else { on(self, _checked); }; }; return false; // Keyup } else if (type == 'keyup' && node[_type] == _radio) { !node[_checked] && on(self, _checked); // Focus/blur } else if (/us|ur/.test(type)) { parent[type == 'blur' ? _remove : _add](focusClass); }; }); // Helper events helper.on(_click + ' mousedown mouseup mouseover mouseout ' + _touch, function(event) { var type = event[_type], // mousedown|mouseup toggle = /wn|up/.test(type) ? activeClass : hoverClass; // Do nothing if input is disabled if (!node[_disabled]) { // Click if (type == _click) { operate(self, false, true); // Active and hover states } else { // State is on if (/wn|er|in/.test(type)) { // mousedown|mouseover|touchbegin parent[_add](toggle); // State is off } else { parent[_remove](toggle + ' ' + activeClass); }; // Label hover if (label.length && labelHover && toggle == hoverClass) { // mouseout|touchend label[/ut|nd/.test(type) ? _remove : _add](labelHoverClass); }; }; if (_mobile) { event.stopPropagation(); } else { return false; }; }; }); }); } else { return this; }; }; // Do something with inputs function operate(input, direct, method) { var node = input[0]; state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked, active = method == _update ? { checked: node[_checked], disabled: node[_disabled], indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false' } : node[state]; // Check, disable or indeterminate if (/^(ch|di|in)/.test(method) && !active) { on(input, state); // Uncheck, enable or determinate } else if (/^(un|en|de)/.test(method) && active) { off(input, state); // Update } else if (method == _update) { // Handle states for (var state in active) { if (active[state]) { on(input, state, true); } else { off(input, state, true); }; }; } else if (!direct || method == 'toggle') { // Helper or label was clicked if (!direct) { input[_callback]('ifClicked'); }; // Toggle checked state if (active) { if (node[_type] !== _radio) { off(input, state); }; } else { on(input, state); }; }; }; // Add checked, disabled or indeterminate state function on(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== true) { // Toggle assigned radio buttons if (!keep && state == _checked && node[_type] == _radio && node.name) { var form = input.closest('form'), inputs = 'input[name="' + node.name + '"]'; inputs = form.length ? form.find(inputs) : $(inputs); inputs.each(function() { if (this !== node && $(this).data(_iCheck)) { off($(this), state); }; }); }; // Indeterminate state if (indeterminate) { // Add indeterminate state node[state] = true; // Remove checked state if (node[_checked]) { off(input, _checked, 'force'); }; // Checked or disabled state } else { // Add checked or disabled state if (!keep) { node[state] = true; }; // Remove indeterminate state if (checked && node[_indeterminate]) { off(input, _indeterminate, false); }; }; // Trigger callbacks callbacks(input, checked, state, keep); }; // Add proper cursor if (node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'default'); }; // Add state class parent[_add](specific || option(input, state) || ''); // Remove regular state class parent[_remove](regular || option(input, callback) || ''); }; // Remove checked, disabled or indeterminate state function off(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== false) { // Toggle state if (indeterminate || !keep || keep == 'force') { node[state] = false; }; // Trigger callbacks callbacks(input, checked, callback, keep); }; // Add proper cursor if (!node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'pointer'); }; // Remove state class parent[_remove](specific || option(input, state) || ''); // Add regular state class parent[_add](regular || option(input, callback) || ''); }; // Remove all traces function tidy(input, callback) { if (input.data(_iCheck)) { // Remove everything except input input.parent().html(input.attr('style', input.data(_iCheck).s || '')); // Callback if (callback) { input[_callback](callback); }; // Unbind events input.off('.i').unwrap(); $(_label + '[for="' + input[0].id + '"]').add(input.closest(_label)).off('.i'); }; }; // Get some option function option(input, state, regular) { if (input.data(_iCheck)) { return input.data(_iCheck).o[state + (regular ? '' : 'Class')]; }; }; // Capitalize some string function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); }; // Executable handlers function callbacks(input, checked, callback, keep) { if (!keep) { if (checked) { input[_callback]('ifToggled'); }; input[_callback]('ifChanged')[_callback]('if' + capitalize(callback)); }; }; })(Zepto);
JavaScript
/*! * iCheck v0.9.1, http://git.io/uhUPMA * ================================= * Powerful jQuery plugin for checkboxes and radio buttons customization * * (c) 2013 Damir Foy, http://damirfoy.com * MIT Licensed */ (function($) { // Cached vars var _iCheck = 'iCheck', _iCheckHelper = _iCheck + '-helper', _checkbox = 'checkbox', _radio = 'radio', _checked = 'checked', _unchecked = 'un' + _checked, _disabled = 'disabled', _determinate = 'determinate', _indeterminate = 'in' + _determinate, _update = 'update', _type = 'type', _click = 'click', _touch = 'touchbegin.i touchend.i', _add = 'addClass', _remove = 'removeClass', _callback = 'trigger', _label = 'label', _cursor = 'cursor', _mobile = /ipad|iphone|ipod|android|blackberry|windows phone|opera mini/i.test(navigator.userAgent); // Plugin init $.fn[_iCheck] = function(options, fire) { // Walker var handle = ':' + _checkbox + ', :' + _radio, stack = $(), walker = function(object) { object.each(function() { var self = $(this); if (self.is(handle)) { stack = stack.add(self); } else { stack = stack.add(self.find(handle)); }; }); }; // Check if we should operate with some method if (/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(options)) { // Normalize method's name options = options.toLowerCase(); // Find checkboxes and radio buttons walker(this); return stack.each(function() { if (options == 'destroy') { tidy(this, 'ifDestroyed'); } else { operate($(this), true, options); }; // Fire method's callback if ($.isFunction(fire)) { fire(); }; }); // Customization } else if (typeof options == 'object' || !options) { // Check if any options were passed var settings = $.extend({ checkedClass: _checked, disabledClass: _disabled, indeterminateClass: _indeterminate, labelHover: true }, options), selector = settings.handle, hoverClass = settings.hoverClass || 'hover', focusClass = settings.focusClass || 'focus', activeClass = settings.activeClass || 'active', labelHover = !!settings.labelHover, labelHoverClass = settings.labelHoverClass || 'hover', // Setup clickable area area = ('' + settings.increaseArea).replace('%', '') | 0; // Selector limit if (selector == _checkbox || selector == _radio) { handle = ':' + selector; }; // Clickable area limit if (area < -50) { area = -50; }; // Walk around the selector walker(this); return stack.each(function() { // If already customized tidy(this); var self = $(this), node = this, id = node.id, // Layer styles offset = -area + '%', size = 100 + (area * 2) + '%', layer = { position: 'absolute', top: offset, left: offset, display: 'block', width: size, height: size, margin: 0, padding: 0, background: '#fff', border: 0, opacity: 0 }, // Choose how to hide input hide = _mobile ? { position: 'absolute', visibility: 'hidden' } : area ? layer : { position: 'absolute', opacity: 0 }, // Get proper class className = node[_type] == _checkbox ? settings.checkboxClass || 'i' + _checkbox : settings.radioClass || 'i' + _radio, // Find assigned labels label = $(_label + '[for="' + id + '"]').add(self.closest(_label)), // Wrap input parent = self.wrap('<div class="' + className + '"/>')[_callback]('ifCreated').parent().append(settings.insert), // Layer addition helper = $('<ins class="' + _iCheckHelper + '"/>').css(layer).appendTo(parent); // Finalize customization self.data(_iCheck, {o: settings, s: self.attr('style')}).css(hide); !!settings.inheritClass && parent[_add](node.className); !!settings.inheritID && id && parent.attr('id', _iCheck + '-' + id); parent.css('position') == 'static' && parent.css('position', 'relative'); operate(self, true, _update); // Label events if (label.length) { label.on(_click + '.i mouseenter.i mouseleave.i ' + _touch, function(event) { var type = event[_type], item = $(this); // Do nothing if input is disabled if (!node[_disabled]) { // Click if (type == _click) { operate(self, false, true); // Hover state } else if (labelHover) { // mouseleave|touchend if (/ve|nd/.test(type)) { parent[_remove](hoverClass); item[_remove](labelHoverClass); } else { parent[_add](hoverClass); item[_add](labelHoverClass); }; }; if (_mobile) { event.stopPropagation(); } else { return false; }; }; }); }; // Input events self.on(_click + '.i focus.i blur.i keyup.i keydown.i keypress.i', function(event) { var type = event[_type], key = event.keyCode; // Click if (type == _click) { return false; // Keydown } else if (type == 'keydown' && key == 32) { if (!(node[_type] == _radio && node[_checked])) { if (node[_checked]) { off(self, _checked); } else { on(self, _checked); }; }; return false; // Keyup } else if (type == 'keyup' && node[_type] == _radio) { !node[_checked] && on(self, _checked); // Focus/blur } else if (/us|ur/.test(type)) { parent[type == 'blur' ? _remove : _add](focusClass); }; }); // Helper events helper.on(_click + ' mousedown mouseup mouseover mouseout ' + _touch, function(event) { var type = event[_type], // mousedown|mouseup toggle = /wn|up/.test(type) ? activeClass : hoverClass; // Do nothing if input is disabled if (!node[_disabled]) { // Click if (type == _click) { operate(self, false, true); // Active and hover states } else { // State is on if (/wn|er|in/.test(type)) { // mousedown|mouseover|touchbegin parent[_add](toggle); // State is off } else { parent[_remove](toggle + ' ' + activeClass); }; // Label hover if (label.length && labelHover && toggle == hoverClass) { // mouseout|touchend label[/ut|nd/.test(type) ? _remove : _add](labelHoverClass); }; }; if (_mobile) { event.stopPropagation(); } else { return false; }; }; }); }); } else { return this; }; }; // Do something with inputs function operate(input, direct, method) { var node = input[0]; state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked, active = method == _update ? { checked: node[_checked], disabled: node[_disabled], indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false' } : node[state]; // Check, disable or indeterminate if (/^(ch|di|in)/.test(method) && !active) { on(input, state); // Uncheck, enable or determinate } else if (/^(un|en|de)/.test(method) && active) { off(input, state); // Update } else if (method == _update) { // Handle states for (var state in active) { if (active[state]) { on(input, state, true); } else { off(input, state, true); }; }; } else if (!direct || method == 'toggle') { // Helper or label was clicked if (!direct) { input[_callback]('ifClicked'); }; // Toggle checked state if (active) { if (node[_type] !== _radio) { off(input, state); }; } else { on(input, state); }; }; }; // Add checked, disabled or indeterminate state function on(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(node, callback + capitalize(node[_type])), specific = option(node, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== true) { // Toggle assigned radio buttons if (!keep && state == _checked && node[_type] == _radio && node.name) { var form = input.closest('form'), inputs = 'input[name="' + node.name + '"]'; inputs = form.length ? form.find(inputs) : $(inputs); inputs.each(function() { if (this !== node && $.data(this, _iCheck)) { off($(this), state); }; }); }; // Indeterminate state if (indeterminate) { // Add indeterminate state node[state] = true; // Remove checked state if (node[_checked]) { off(input, _checked, 'force'); }; // Checked or disabled state } else { // Add checked or disabled state if (!keep) { node[state] = true; }; // Remove indeterminate state if (checked && node[_indeterminate]) { off(input, _indeterminate, false); }; }; // Trigger callbacks callbacks(input, checked, state, keep); }; // Add proper cursor if (node[_disabled] && !!option(node, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'default'); }; // Add state class parent[_add](specific || option(node, state)); // Remove regular state class parent[_remove](regular || option(node, callback) || ''); }; // Remove checked, disabled or indeterminate state function off(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(node, callback + capitalize(node[_type])), specific = option(node, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== false) { // Toggle state if (indeterminate || !keep || keep == 'force') { node[state] = false; }; // Trigger callbacks callbacks(input, checked, callback, keep); }; // Add proper cursor if (!node[_disabled] && !!option(node, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'pointer'); }; // Remove state class parent[_remove](specific || option(node, state) || ''); // Add regular state class parent[_add](regular || option(node, callback)); }; // Remove all traces function tidy(node, callback) { if ($.data(node, _iCheck)) { var input = $(node); // Remove everything except input input.parent().html(input.attr('style', $.data(node, _iCheck).s || '')[_callback](callback || '')); // Unbind events input.off('.i').unwrap(); $(_label + '[for="' + node.id + '"]').add(input.closest(_label)).off('.i'); }; }; // Get some option function option(node, state, regular) { if ($.data(node, _iCheck)) { return $.data(node, _iCheck).o[state + (regular ? '' : 'Class')]; }; }; // Capitalize some string function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); }; // Executable handlers function callbacks(input, checked, callback, keep) { if (!keep) { if (checked) { input[_callback]('ifToggled'); }; input[_callback]('ifChanged')[_callback]('if' + capitalize(callback)); }; }; })(jQuery);
JavaScript
/* * Inline Form Validation Engine 2.6, jQuery plugin * * Copyright(c) 2010, Cedric Dugas * http://www.position-absolute.com * * 2.0 Rewrite by Olivier Refalo * http://www.crionics.com * * Form validation engine allowing custom regex rules to be added. * Licensed under the MIT License */ (function($) { "use strict"; var methods = { /** * Kind of the constructor, called before any action * @param {Map} user options */ init: function(options) { var form = this; if (!form.data('jqv') || form.data('jqv') == null ) { options = methods._saveOptions(form, options); // bind all formError elements to close on click $(document).on("click", ".formError", function() { $(this).fadeOut(150, function() { // remove prompt once invisible $("#"+$(this).attr("data-elm")).focus(); $(this).parent('.formErrorOuter').remove(); $(this).remove(); }); }); } return this; }, /** * Attachs jQuery.validationEngine to form.submit and field.blur events * Takes an optional params: a list of options * ie. jQuery("#formID1").validationEngine('attach', {promptPosition : "centerRight"}); */ attach: function(userOptions) { if(!$(this).is("form")) { alert("Sorry, jqv.attach() only applies to a form"); return this; } var form = this; var options; if(userOptions) options = methods._saveOptions(form, userOptions); else options = form.data('jqv'); options.validateAttribute = (form.find("[data-validation-engine*=validate]").length) ? "data-validation-engine" : "class"; if (options.binded) { // bind fields form.find("["+options.validateAttribute+"*=validate]").not("[type=checkbox]").not("[type=radio]").not(".datepicker").bind(options.validationEventTrigger, methods._onFieldEvent); form.find("["+options.validateAttribute+"*=validate][type=checkbox],["+options.validateAttribute+"*=validate][type=radio]").bind("click", methods._onFieldEvent); form.find("["+options.validateAttribute+"*=validate][class*=datepicker]").bind(options.validationEventTrigger,{"delay": 300}, methods._onFieldEvent); } if (options.autoPositionUpdate) { $(window).bind("resize", { "noAnimation": true, "formElem": form }, methods.updatePromptsPosition); } // bind form.submit form.bind("submit", methods._onSubmitEvent); return this; }, /** * Unregisters any bindings that may point to jQuery.validaitonEngine */ detach: function() { if(!$(this).is("form")) { alert("Sorry, jqv.detach() only applies to a form"); return this; } var form = this; var options = form.data('jqv'); // unbind fields form.find("["+options.validateAttribute+"*=validate]").not("[type=checkbox]").unbind(options.validationEventTrigger, methods._onFieldEvent); form.find("["+options.validateAttribute+"*=validate][type=checkbox],[class*=validate][type=radio]").unbind("click", methods._onFieldEvent); // unbind form.submit form.unbind("submit", methods.onAjaxFormComplete); // unbind live fields (kill) form.find("["+options.validateAttribute+"*=validate]").not("[type=checkbox]").off(options.validationEventTrigger, methods._onFieldEvent); form.find("["+options.validateAttribute+"*=validate][type=checkbox]").off("click", methods._onFieldEvent); // unbind form.submit form.off("submit", methods.onAjaxFormComplete); form.removeData('jqv'); if (options.autoPositionUpdate) $(window).unbind("resize", methods.updatePromptsPosition); return this; }, /** * Validates either a form or a list of fields, shows prompts accordingly. * Note: There is no ajax form validation with this method, only field ajax validation are evaluated * * @return true if the form validates, false if it fails */ validate: function() { var element = $(this); var valid = null; if(element.is("form") && !element.hasClass('validating')) { element.addClass('validating'); var options = element.data('jqv'); valid = methods._validateFields(this); // If the form doesn't validate, clear the 'validating' class before the user has a chance to submit again setTimeout(function(){ element.removeClass('validating'); }, 100); if (valid && options.onFormSuccess) { options.onFormSuccess(); } else if (!valid && options.onFormFailure) { options.onFormFailure(); } } else if (element.is('form')) { element.removeClass('validating'); } else { // field validation var form = element.closest('form'); var options = form.data('jqv'); valid = methods._validateField(element, options); if (valid && options.onFieldSuccess) options.onFieldSuccess(); else if (options.onFieldFailure && options.InvalidFields.length > 0) { options.onFieldFailure(); } } return valid; }, /** * Redraw prompts position, useful when you change the DOM state when validating */ updatePromptsPosition: function(event) { if (event && this == window) { var form = event.data.formElem; var noAnimation = event.data.noAnimation; } else var form = $(this.closest('form')); var options = form.data('jqv'); // No option, take default one form.find('['+options.validateAttribute+'*=validate]').not(":disabled").each(function(){ var field = $(this); if (options.prettySelect && field.is(":hidden")) field = form.find("#" + options.usePrefix + field.attr('id') + options.useSuffix); var prompt = methods._getPrompt(field); var promptText = $(prompt).find(".formErrorContent").html(); if(prompt) methods._updatePrompt(field, $(prompt), promptText, undefined, false, options, noAnimation); }); return this; }, /** * Displays a prompt on a element. * Note that the element needs an id! * * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {String} possible values topLeft, topRight, bottomLeft, centerRight, bottomRight */ showPrompt: function(promptText, type, promptPosition, showArrow) { var form = this.closest('form'); var options = form.data('jqv'); // No option, take default one if(!options) options = methods._saveOptions(this, options); if(promptPosition) options.promptPosition=promptPosition; options.showArrow = showArrow==true; methods._showPrompt(this, promptText, type, false, options); return this; }, /** * Closes form error prompts, CAN be invidual */ hide: function() { var form = $(this).closest('form'); var options = form.data('jqv'); var fadeDuration = (options && options.fadeDuration) ? options.fadeDuration : 0.3; var closingtag; if($(this).is("form")) { closingtag = "parentForm"+methods._getClassName($(this).attr("id")); } else { closingtag = methods._getClassName($(this).attr("id")) +"formError"; } $('.'+closingtag).fadeTo(fadeDuration, 0.3, function() { $(this).parent('.formErrorOuter').remove(); $(this).remove(); }); return this; }, /** * Closes all error prompts on the page */ hideAll: function() { var form = this; var options = form.data('jqv'); var duration = options ? options.fadeDuration:0.3; $('.formError').fadeTo(duration, 0.3, function() { $(this).parent('.formErrorOuter').remove(); $(this).remove(); }); return this; }, /** * Typically called when user exists a field using tab or a mouse click, triggers a field * validation */ _onFieldEvent: function(event) { var field = $(this); var form = field.closest('form'); var options = form.data('jqv'); options.eventTrigger = "field"; // validate the current field window.setTimeout(function() { methods._validateField(field, options); if (options.InvalidFields.length == 0 && options.onFieldSuccess) { options.onFieldSuccess(); } else if (options.InvalidFields.length > 0 && options.onFieldFailure) { options.onFieldFailure(); } }, (event.data) ? event.data.delay : 0); }, /** * Called when the form is submited, shows prompts accordingly * * @param {jqObject} * form * @return false if form submission needs to be cancelled */ _onSubmitEvent: function() { var form = $(this); var options = form.data('jqv'); options.eventTrigger = "submit"; // validate each field // (- skip field ajax validation, not necessary IF we will perform an ajax form validation) var r=methods._validateFields(form); if (r && options.ajaxFormValidation) { methods._validateFormWithAjax(form, options); // cancel form auto-submission - process with async call onAjaxFormComplete return false; } if(options.onValidationComplete) { // !! ensures that an undefined return is interpreted as return false but allows a onValidationComplete() to possibly return true and have form continue processing return !!options.onValidationComplete(form, r); } return r; }, /** * Return true if the ajax field validations passed so far * @param {Object} options * @return true, is all ajax validation passed so far (remember ajax is async) */ _checkAjaxStatus: function(options) { var status = true; $.each(options.ajaxValidCache, function(key, value) { if (!value) { status = false; // break the each return false; } }); return status; }, /** * Return true if the ajax field is validated * @param {String} fieldid * @param {Object} options * @return true, if validation passed, false if false or doesn't exist */ _checkAjaxFieldStatus: function(fieldid, options) { return options.ajaxValidCache[fieldid] == true; }, /** * Validates form fields, shows prompts accordingly * * @param {jqObject} * form * @param {skipAjaxFieldValidation} * boolean - when set to true, ajax field validation is skipped, typically used when the submit button is clicked * * @return true if form is valid, false if not, undefined if ajax form validation is done */ _validateFields: function(form) { var options = form.data('jqv'); // this variable is set to true if an error is found var errorFound = false; // Trigger hook, start validation form.trigger("jqv.form.validating"); // first, evaluate status of non ajax fields var first_err=null; form.find('['+options.validateAttribute+'*=validate]').not(":disabled").each( function() { var field = $(this); var names = []; if ($.inArray(field.attr('name'), names) < 0) { errorFound |= methods._validateField(field, options); if (errorFound && first_err==null) if (field.is(":hidden") && options.prettySelect) first_err = field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix); else first_err=field; if (options.doNotShowAllErrosOnSubmit) return false; names.push(field.attr('name')); //if option set, stop checking validation rules after one error is found if(options.showOneMessage == true && errorFound){ return false; } } }); // second, check to see if all ajax calls completed ok // errorFound |= !methods._checkAjaxStatus(options); // third, check status and scroll the container accordingly form.trigger("jqv.form.result", [errorFound]); if (errorFound) { if (options.scroll) { var destination=first_err.offset().top; var fixleft = first_err.offset().left; //prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10) var positionType=options.promptPosition; if (typeof(positionType)=='string' && positionType.indexOf(":")!=-1) positionType=positionType.substring(0,positionType.indexOf(":")); if (positionType!="bottomRight" && positionType!="bottomLeft") { var prompt_err= methods._getPrompt(first_err); if (prompt_err) { destination=prompt_err.offset().top; } } // get the position of the first error, there should be at least one, no need to check this //var destination = form.find(".formError:not('.greenPopup'):first").offset().top; if (options.isOverflown) { var overflowDIV = $(options.overflownDIV); if(!overflowDIV.length) return false; var scrollContainerScroll = overflowDIV.scrollTop(); var scrollContainerPos = -parseInt(overflowDIV.offset().top); destination += scrollContainerScroll + scrollContainerPos - 5; var scrollContainer = $(options.overflownDIV + ":not(:animated)"); scrollContainer.animate({scrollTop: destination}, 1100, function(){ if(options.focusFirstField) first_err.focus(); }); } else { $("body,html").stop().animate({ scrollTop: destination, scrollLeft: fixleft }, 1100, function(){ if(options.focusFirstField) first_err.focus(); }); } } else if(options.focusFirstField) first_err.focus(); return false; } return true; }, /** * This method is called to perform an ajax form validation. * During this process all the (field, value) pairs are sent to the server which returns a list of invalid fields or true * * @param {jqObject} form * @param {Map} options */ _validateFormWithAjax: function(form, options) { var data = form.serialize(); var type = (options.ajaxmethod) ? options.ajaxmethod : "GET"; var url = (options.ajaxFormValidationURL) ? options.ajaxFormValidationURL : form.attr("action"); var dataType = (options.dataType) ? options.dataType : "json"; $.ajax({ type: type, url: url, cache: false, dataType: dataType, data: data, form: form, methods: methods, options: options, beforeSend: function() { return options.onBeforeAjaxFormValidation(form, options); }, error: function(data, transport) { methods._ajaxError(data, transport); }, success: function(json) { if ((dataType == "json") && (json !== true)) { // getting to this case doesn't necessary means that the form is invalid // the server may return green or closing prompt actions // this flag helps figuring it out var errorInForm=false; for (var i = 0; i < json.length; i++) { var value = json[i]; var errorFieldId = value[0]; var errorField = $($("#" + errorFieldId)[0]); // make sure we found the element if (errorField.length == 1) { // promptText or selector var msg = value[2]; // if the field is valid if (value[1] == true) { if (msg == "" || !msg){ // if for some reason, status==true and error="", just close the prompt methods._closePrompt(errorField); } else { // the field is valid, but we are displaying a green prompt if (options.allrules[msg]) { var txt = options.allrules[msg].alertTextOk; if (txt) msg = txt; } methods._showPrompt(errorField, msg, "pass", false, options, true); } } else { // the field is invalid, show the red error prompt errorInForm|=true; if (options.allrules[msg]) { var txt = options.allrules[msg].alertText; if (txt) msg = txt; } methods._showPrompt(errorField, msg, "", false, options, true); } } } options.onAjaxFormComplete(!errorInForm, form, json, options); } else options.onAjaxFormComplete(true, form, json, options); } }); }, /** * Validates field, shows prompts accordingly * * @param {jqObject} * field * @param {Array[String]} * field's validation rules * @param {Map} * user options * @return false if field is valid (It is inversed for *fields*, it return false on validate and true on errors.) */ _validateField: function(field, options, skipAjaxValidation) { if (!field.attr("id")) { field.attr("id", "form-validation-field-" + $.validationEngine.fieldIdCounter); ++$.validationEngine.fieldIdCounter; } if (field.is(":hidden") && !options.prettySelect || field.parent().is(":hidden")) return false; var rulesParsing = field.attr(options.validateAttribute); var getRules = /validate\[(.*)\]/.exec(rulesParsing); if (!getRules) return false; var str = getRules[1]; var rules = str.split(/\[|,|\]/); // true if we ran the ajax validation, tells the logic to stop messing with prompts var isAjaxValidator = false; var fieldName = field.attr("name"); var promptText = ""; var promptType = ""; var required = false; var limitErrors = false; options.isError = false; options.showArrow = true; // If the programmer wants to limit the amount of error messages per field, if (options.maxErrorsPerField > 0) { limitErrors = true; } var form = $(field.closest("form")); // Fix for adding spaces in the rules for (var i in rules) { rules[i] = rules[i].replace(" ", ""); // Remove any parsing errors if (rules[i] === '') { delete rules[i]; } } for (var i = 0, field_errors = 0; i < rules.length; i++) { // If we are limiting errors, and have hit the max, break if (limitErrors && field_errors >= options.maxErrorsPerField) { // If we haven't hit a required yet, check to see if there is one in the validation rules for this // field and that it's index is greater or equal to our current index if (!required) { var have_required = $.inArray('required', rules); required = (have_required != -1 && have_required >= i); } break; } var errorMsg = undefined; switch (rules[i]) { case "required": required = true; errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._required); break; case "custom": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._custom); break; case "groupRequired": // Check is its the first of group, if not, reload validation with first field // AND continue normal validation on present field var classGroup = "["+options.validateAttribute+"*=" +rules[i + 1] +"]"; var firstOfGroup = form.find(classGroup).eq(0); if(firstOfGroup[0] != field[0]){ methods._validateField(firstOfGroup, options, skipAjaxValidation); options.showArrow = true; continue; } errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._groupRequired); if(errorMsg) required = true; options.showArrow = false; break; case "ajax": // AJAX defaults to returning it's loading message errorMsg = methods._ajax(field, rules, i, options); if (errorMsg) { promptType = "load"; } break; case "minSize": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minSize); break; case "maxSize": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxSize); break; case "min": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._min); break; case "max": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._max); break; case "past": errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._past); break; case "future": errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._future); break; case "dateRange": var classGroup = "["+options.validateAttribute+"*=" + rules[i + 1] + "]"; options.firstOfGroup = form.find(classGroup).eq(0); options.secondOfGroup = form.find(classGroup).eq(1); //if one entry out of the pair has value then proceed to run through validation if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) { errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._dateRange); } if (errorMsg) required = true; options.showArrow = false; break; case "dateTimeRange": var classGroup = "["+options.validateAttribute+"*=" + rules[i + 1] + "]"; options.firstOfGroup = form.find(classGroup).eq(0); options.secondOfGroup = form.find(classGroup).eq(1); //if one entry out of the pair has value then proceed to run through validation if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) { errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._dateTimeRange); } if (errorMsg) required = true; options.showArrow = false; break; case "maxCheckbox": field = $(form.find("input[name='" + fieldName + "']")); errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxCheckbox); break; case "minCheckbox": field = $(form.find("input[name='" + fieldName + "']")); errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minCheckbox); break; case "equals": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._equals); break; case "funcCall": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._funcCall); break; case "creditCard": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._creditCard); break; case "condRequired": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._condRequired); if (errorMsg !== undefined) { required = true; } break; default: } var end_validation = false; // If we were passed back an message object, check what the status was to determine what to do if (typeof errorMsg == "object") { switch (errorMsg.status) { case "_break": end_validation = true; break; // If we have an error message, set errorMsg to the error message case "_error": errorMsg = errorMsg.message; break; // If we want to throw an error, but not show a prompt, return early with true case "_error_no_prompt": return true; break; // Anything else we continue on default: break; } } // If it has been specified that validation should end now, break if (end_validation) { break; } // If we have a string, that means that we have an error, so add it to the error message. if (typeof errorMsg == 'string') { promptText += errorMsg + "<br/>"; options.isError = true; field_errors++; } } // If the rules required is not added, an empty field is not validated if(!required && field.val().length < 1) options.isError = false; // Hack for radio/checkbox group button, the validation go into the // first radio/checkbox of the group var fieldType = field.prop("type"); if ((fieldType == "radio" || fieldType == "checkbox") && form.find("input[name='" + fieldName + "']").size() > 1) { field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:first")); options.showArrow = false; } if(field.is(":hidden") && options.prettySelect) { field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix); } if (options.isError){ methods._showPrompt(field, promptText, promptType, false, options); }else{ if (!isAjaxValidator) methods._closePrompt(field); } if (!isAjaxValidator) { field.trigger("jqv.field.result", [field, options.isError, promptText]); } /* Record error */ var errindex = $.inArray(field[0], options.InvalidFields); if (errindex == -1) { if (options.isError) options.InvalidFields.push(field[0]); } else if (!options.isError) { options.InvalidFields.splice(errindex, 1); } methods._handleStatusCssClasses(field, options); return options.isError; }, /** * Handling css classes of fields indicating result of validation * * @param {jqObject} * field * @param {Array[String]} * field's validation rules * @private */ _handleStatusCssClasses: function(field, options) { /* remove all classes */ if(options.addSuccessCssClassToField) field.removeClass(options.addSuccessCssClassToField); if(options.addFailureCssClassToField) field.removeClass(options.addFailureCssClassToField); /* Add classes */ if (options.addSuccessCssClassToField && !options.isError) field.addClass(options.addSuccessCssClassToField); if (options.addFailureCssClassToField && options.isError) field.addClass(options.addFailureCssClassToField); }, /******************** * _getErrorMessage * * @param form * @param field * @param rule * @param rules * @param i * @param options * @param originalValidationMethod * @return {*} * @private */ _getErrorMessage:function (form, field, rule, rules, i, options, originalValidationMethod) { // If we are using the custon validation type, build the index for the rule. // Otherwise if we are doing a function call, make the call and return the object // that is passed back. var beforeChangeRule = rule; if (rule == "custom") { var custom_validation_type_index = jQuery.inArray(rule, rules)+ 1; var custom_validation_type = rules[custom_validation_type_index]; rule = "custom[" + custom_validation_type + "]"; } var element_classes = (field.attr("data-validation-engine")) ? field.attr("data-validation-engine") : field.attr("class"); var element_classes_array = element_classes.split(" "); // Call the original validation method. If we are dealing with dates or checkboxes, also pass the form var errorMsg; if (rule == "future" || rule == "past" || rule == "maxCheckbox" || rule == "minCheckbox") { errorMsg = originalValidationMethod(form, field, rules, i, options); } else { errorMsg = originalValidationMethod(field, rules, i, options); } // If the original validation method returned an error and we have a custom error message, // return the custom message instead. Otherwise return the original error message. if (errorMsg != undefined) { var custom_message = methods._getCustomErrorMessage($(field), element_classes_array, beforeChangeRule, options); if (custom_message) errorMsg = custom_message; } return errorMsg; }, _getCustomErrorMessage:function (field, classes, rule, options) { var custom_message = false; var validityProp = methods._validityProp[rule]; // If there is a validityProp for this rule, check to see if the field has an attribute for it if (validityProp != undefined) { custom_message = field.attr("data-errormessage-"+validityProp); // If there was an error message for it, return the message if (custom_message != undefined) return custom_message; } custom_message = field.attr("data-errormessage"); // If there is an inline custom error message, return it if (custom_message != undefined) return custom_message; var id = '#' + field.attr("id"); // If we have custom messages for the element's id, get the message for the rule from the id. // Otherwise, if we have custom messages for the element's classes, use the first class message we find instead. if (typeof options.custom_error_messages[id] != "undefined" && typeof options.custom_error_messages[id][rule] != "undefined" ) { custom_message = options.custom_error_messages[id][rule]['message']; } else if (classes.length > 0) { for (var i = 0; i < classes.length && classes.length > 0; i++) { var element_class = "." + classes[i]; if (typeof options.custom_error_messages[element_class] != "undefined" && typeof options.custom_error_messages[element_class][rule] != "undefined") { custom_message = options.custom_error_messages[element_class][rule]['message']; break; } } } if (!custom_message && typeof options.custom_error_messages[rule] != "undefined" && typeof options.custom_error_messages[rule]['message'] != "undefined"){ custom_message = options.custom_error_messages[rule]['message']; } return custom_message; }, _validityProp: { "required": "value-missing", "custom": "custom-error", "groupRequired": "value-missing", "ajax": "custom-error", "minSize": "range-underflow", "maxSize": "range-overflow", "min": "range-underflow", "max": "range-overflow", "past": "type-mismatch", "future": "type-mismatch", "dateRange": "type-mismatch", "dateTimeRange": "type-mismatch", "maxCheckbox": "range-overflow", "minCheckbox": "range-underflow", "equals": "pattern-mismatch", "funcCall": "custom-error", "creditCard": "pattern-mismatch", "condRequired": "value-missing" }, /** * Required validation * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _required: function(field, rules, i, options) { switch (field.prop("type")) { case "text": case "password": case "textarea": case "file": case "select-one": case "select-multiple": default: if (! $.trim(field.val()) || field.val() == field.attr("data-validation-placeholder") || field.val() == field.attr("placeholder")) return options.allrules[rules[i]].alertText; break; case "radio": case "checkbox": var form = field.closest("form"); var name = field.attr("name"); if (form.find("input[name='" + name + "']:checked").size() == 0) { if (form.find("input[name='" + name + "']:visible").size() == 1) return options.allrules[rules[i]].alertTextCheckboxe; else return options.allrules[rules[i]].alertTextCheckboxMultiple; } break; } }, /** * Validate that 1 from the group field is required * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _groupRequired: function(field, rules, i, options) { var classGroup = "["+options.validateAttribute+"*=" +rules[i + 1] +"]"; var isValid = false; // Check all fields from the group field.closest("form").find(classGroup).each(function(){ if(!methods._required($(this), rules, i, options)){ isValid = true; return false; } }); if(!isValid) { return options.allrules[rules[i]].alertText; } }, /** * Validate rules * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _custom: function(field, rules, i, options) { var customRule = rules[i + 1]; var rule = options.allrules[customRule]; var fn; if(!rule) { alert("jqv:custom rule not found - "+customRule); return; } if(rule["regex"]) { var ex=rule.regex; if(!ex) { alert("jqv:custom regex not found - "+customRule); return; } var pattern = new RegExp(ex); if (!pattern.test(field.val())) return options.allrules[customRule].alertText; } else if(rule["func"]) { fn = rule["func"]; if (typeof(fn) !== "function") { alert("jqv:custom parameter 'function' is no function - "+customRule); return; } if (!fn(field, rules, i, options)) return options.allrules[customRule].alertText; } else { alert("jqv:custom type not allowed "+customRule); return; } }, /** * Validate custom function outside of the engine scope * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _funcCall: function(field, rules, i, options) { var functionName = rules[i + 1]; var fn; if(functionName.indexOf('.') >-1) { var namespaces = functionName.split('.'); var scope = window; while(namespaces.length) { scope = scope[namespaces.shift()]; } fn = scope; } else fn = window[functionName] || options.customFunctions[functionName]; if (typeof(fn) == 'function') return fn(field, rules, i, options); }, /** * Field match * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _equals: function(field, rules, i, options) { var equalsField = rules[i + 1]; if (field.val() != $("#" + equalsField).val()) return options.allrules.equals.alertText; }, /** * Check the maximum size (in characters) * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _maxSize: function(field, rules, i, options) { var max = rules[i + 1]; var len = field.val().length; if (len > max) { var rule = options.allrules.maxSize; return rule.alertText + max + rule.alertText2; } }, /** * Check the minimum size (in characters) * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _minSize: function(field, rules, i, options) { var min = rules[i + 1]; var len = field.val().length; if (len < min) { var rule = options.allrules.minSize; return rule.alertText + min + rule.alertText2; } }, /** * Check number minimum value * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _min: function(field, rules, i, options) { var min = parseFloat(rules[i + 1]); var len = parseFloat(field.val()); if (len < min) { var rule = options.allrules.min; if (rule.alertText2) return rule.alertText + min + rule.alertText2; return rule.alertText + min; } }, /** * Check number maximum value * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _max: function(field, rules, i, options) { var max = parseFloat(rules[i + 1]); var len = parseFloat(field.val()); if (len >max ) { var rule = options.allrules.max; if (rule.alertText2) return rule.alertText + max + rule.alertText2; //orefalo: to review, also do the translations return rule.alertText + max; } }, /** * Checks date is in the past * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _past: function(form, field, rules, i, options) { var p=rules[i + 1]; var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']")); var pdate; if (p.toLowerCase() == "now") { pdate = new Date(); } else if (undefined != fieldAlt.val()) { if (fieldAlt.is(":disabled")) return; pdate = methods._parseDate(fieldAlt.val()); } else { pdate = methods._parseDate(p); } var vdate = methods._parseDate(field.val()); if (vdate > pdate ) { var rule = options.allrules.past; if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2; return rule.alertText + methods._dateToString(pdate); } }, /** * Checks date is in the future * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _future: function(form, field, rules, i, options) { var p=rules[i + 1]; var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']")); var pdate; if (p.toLowerCase() == "now") { pdate = new Date(); } else if (undefined != fieldAlt.val()) { if (fieldAlt.is(":disabled")) return; pdate = methods._parseDate(fieldAlt.val()); } else { pdate = methods._parseDate(p); } var vdate = methods._parseDate(field.val()); if (vdate < pdate ) { var rule = options.allrules.future; if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2; return rule.alertText + methods._dateToString(pdate); } }, /** * Checks if valid date * * @param {string} date string * @return a bool based on determination of valid date */ _isDate: function (value) { var dateRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/); return dateRegEx.test(value); }, /** * Checks if valid date time * * @param {string} date string * @return a bool based on determination of valid date time */ _isDateTime: function (value){ var dateTimeRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/); return dateTimeRegEx.test(value); }, //Checks if the start date is before the end date //returns true if end is later than start _dateCompare: function (start, end) { return (new Date(start.toString()) < new Date(end.toString())); }, /** * Checks date range * * @param {jqObject} first field name * @param {jqObject} second field name * @return an error string if validation failed */ _dateRange: function (field, rules, i, options) { //are not both populated if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are not both dates if (!methods._isDate(options.firstOfGroup[0].value) || !methods._isDate(options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are both dates but range is off if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } }, /** * Checks date time range * * @param {jqObject} first field name * @param {jqObject} second field name * @return an error string if validation failed */ _dateTimeRange: function (field, rules, i, options) { //are not both populated if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are not both dates if (!methods._isDateTime(options.firstOfGroup[0].value) || !methods._isDateTime(options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are both dates but range is off if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } }, /** * Max number of checkbox selected * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _maxCheckbox: function(form, field, rules, i, options) { var nbCheck = rules[i + 1]; var groupname = field.attr("name"); var groupSize = form.find("input[name='" + groupname + "']:checked").size(); if (groupSize > nbCheck) { options.showArrow = false; if (options.allrules.maxCheckbox.alertText2) return options.allrules.maxCheckbox.alertText + " " + nbCheck + " " + options.allrules.maxCheckbox.alertText2; return options.allrules.maxCheckbox.alertText; } }, /** * Min number of checkbox selected * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _minCheckbox: function(form, field, rules, i, options) { var nbCheck = rules[i + 1]; var groupname = field.attr("name"); var groupSize = form.find("input[name='" + groupname + "']:checked").size(); if (groupSize < nbCheck) { options.showArrow = false; return options.allrules.minCheckbox.alertText + " " + nbCheck + " " + options.allrules.minCheckbox.alertText2; } }, /** * Checks that it is a valid credit card number according to the * Luhn checksum algorithm. * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _creditCard: function(field, rules, i, options) { //spaces and dashes may be valid characters, but must be stripped to calculate the checksum. var valid = false, cardNumber = field.val().replace(/ +/g, '').replace(/-+/g, ''); var numDigits = cardNumber.length; if (numDigits >= 14 && numDigits <= 16 && parseInt(cardNumber) > 0) { var sum = 0, i = numDigits - 1, pos = 1, digit, luhn = new String(); do { digit = parseInt(cardNumber.charAt(i)); luhn += (pos++ % 2 == 0) ? digit * 2 : digit; } while (--i >= 0) for (i = 0; i < luhn.length; i++) { sum += parseInt(luhn.charAt(i)); } valid = sum % 10 == 0; } if (!valid) return options.allrules.creditCard.alertText; }, /** * Ajax field validation * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return nothing! the ajax validator handles the prompts itself */ _ajax: function(field, rules, i, options) { var errorSelector = rules[i + 1]; var rule = options.allrules[errorSelector]; var extraData = rule.extraData; var extraDataDynamic = rule.extraDataDynamic; var data = { "fieldId" : field.attr("id"), "fieldValue" : field.val() }; if (typeof extraData === "object") { $.extend(data, extraData); } else if (typeof extraData === "string") { var tempData = extraData.split("&"); for(var i = 0; i < tempData.length; i++) { var values = tempData[i].split("="); if (values[0] && values[0]) { data[values[0]] = values[1]; } } } if (extraDataDynamic) { var tmpData = []; var domIds = String(extraDataDynamic).split(","); for (var i = 0; i < domIds.length; i++) { var id = domIds[i]; if ($(id).length) { var inputValue = field.closest("form").find(id).val(); var keyValue = id.replace('#', '') + '=' + escape(inputValue); data[id.replace('#', '')] = inputValue; } } } // If a field change event triggered this we want to clear the cache for this ID if (options.eventTrigger == "field") { delete(options.ajaxValidCache[field.attr("id")]); } // If there is an error or if the the field is already validated, do not re-execute AJAX if (!options.isError && !methods._checkAjaxFieldStatus(field.attr("id"), options)) { $.ajax({ type: options.ajaxFormValidationMethod, url: rule.url, cache: false, dataType: "json", data: data, field: field, rule: rule, methods: methods, options: options, beforeSend: function() {}, error: function(data, transport) { methods._ajaxError(data, transport); }, success: function(json) { // asynchronously called on success, data is the json answer from the server var errorFieldId = json[0]; //var errorField = $($("#" + errorFieldId)[0]); var errorField = $("#"+ errorFieldId +"']").eq(0); // make sure we found the element if (errorField.length == 1) { var status = json[1]; // read the optional msg from the server var msg = json[2]; if (!status) { // Houston we got a problem - display an red prompt options.ajaxValidCache[errorFieldId] = false; options.isError = true; // resolve the msg prompt if(msg) { if (options.allrules[msg]) { var txt = options.allrules[msg].alertText; if (txt) { msg = txt; } } } else msg = rule.alertText; methods._showPrompt(errorField, msg, "", true, options); } else { options.ajaxValidCache[errorFieldId] = true; // resolves the msg prompt if(msg) { if (options.allrules[msg]) { var txt = options.allrules[msg].alertTextOk; if (txt) { msg = txt; } } } else msg = rule.alertTextOk; // see if we should display a green prompt if (msg) methods._showPrompt(errorField, msg, "pass", true, options); else methods._closePrompt(errorField); // If a submit form triggered this, we want to re-submit the form if (options.eventTrigger == "submit") field.closest("form").submit(); } } errorField.trigger("jqv.field.result", [errorField, options.isError, msg]); } }); return rule.alertTextLoad; } }, /** * Common method to handle ajax errors * * @param {Object} data * @param {Object} transport */ _ajaxError: function(data, transport) { if(data.status == 0 && transport == null) alert("The page is not served from a server! ajax call failed"); else if(typeof console != "undefined") console.log("Ajax error: " + data.status + " " + transport); }, /** * date -> string * * @param {Object} date */ _dateToString: function(date) { return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(); }, /** * Parses an ISO date * @param {String} d */ _parseDate: function(d) { var dateParts = d.split("-"); if(dateParts==d) dateParts = d.split("/"); return new Date(dateParts[0], (dateParts[1] - 1) ,dateParts[2]); }, /** * Builds or updates a prompt with the given information * * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _showPrompt: function(field, promptText, type, ajaxed, options, ajaxform) { var prompt = methods._getPrompt(field); // The ajax submit errors are not see has an error in the form, // When the form errors are returned, the engine see 2 bubbles, but those are ebing closed by the engine at the same time // Because no error was found befor submitting if(ajaxform) prompt = false; if (prompt) methods._updatePrompt(field, prompt, promptText, type, ajaxed, options); else methods._buildPrompt(field, promptText, type, ajaxed, options); }, /** * Builds and shades a prompt for the given field. * * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _buildPrompt: function(field, promptText, type, ajaxed, options) { // create the prompt var prompt = $('<div>'); prompt.addClass(methods._getClassName(field.attr("id")) + "formError"); // add a class name to identify the parent form of the prompt prompt.addClass("parentForm"+methods._getClassName(field.parents('form').attr("id"))); prompt.addClass("formError"); prompt.addClass("erc").attr("data-elm",field.attr("id")); switch (type) { case "pass": prompt.addClass("greenPopup"); break; case "load": prompt.addClass("blackPopup"); break; default: /* it has error */ //alert("unknown popup type:"+type); } if (ajaxed) prompt.addClass("ajaxed"); // create the prompt content var promptContent = $('<div>').addClass("formErrorContent").html(promptText).appendTo(prompt); // create the css arrow pointing at the field // note that there is no triangle on max-checkbox and radio if (options.showArrow) { var arrow = $('<div>').addClass("formErrorArrow"); //prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10) var positionType=field.data("promptPosition") || options.promptPosition; if (typeof(positionType)=='string') { var pos=positionType.indexOf(":"); if(pos!=-1) positionType=positionType.substring(0,pos); } if(options.isPopup) switch (positionType) { case "bottomLeft": case "bottomRight": prompt.find(".formErrorContent").before(arrow); arrow.addClass("formErrorArrowBottom").html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>'); break; case "topLeft": case "topRight": arrow.html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>'); prompt.append(arrow); break; } } // Modify z-indexes for jquery ui if (field.closest('.ui-dialog').length) prompt.addClass('formErrorInsideDialog'); // add prompt after or before if(field.attr("data-putto")){ if($(field.attr("data-putto").length>0)) prompt.appendTo($(field.attr("data-putto"))); else field.after(prompt); }else{ field.after(prompt); } field.addClass("erb"); if(options.isPopup){ prompt.css({ "opacity": 0, 'position':'absolute' }); var pos = methods._calculatePosition(field, prompt, options); prompt.css({ "top": pos.callerTopPosition, "left": pos.callerleftPosition, "marginTop": pos.marginTopSize, "opacity": 0 }).data("callerField", field); }else{ prompt.css({ "opacity": 0 }); } if (options.autoHidePrompt) { setTimeout(function(){ prompt.animate({ "opacity": 0 },function(){ prompt.closest('.formErrorOuter').remove(); prompt.remove(); field.removeClass("erb"); }); }, options.autoHideDelay); } return prompt.animate({ "opacity": 0.87 }); }, /** * Updates the prompt text field - the field for which the prompt * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _updatePrompt: function(field, prompt, promptText, type, ajaxed, options, noAnimation) { if (prompt) { if (typeof type !== "undefined") { if (type == "pass") prompt.addClass("greenPopup"); else prompt.removeClass("greenPopup"); if (type == "load") prompt.addClass("blackPopup"); else prompt.removeClass("blackPopup"); } if (ajaxed) prompt.addClass("ajaxed"); else prompt.removeClass("ajaxed"); prompt.find(".formErrorContent").html(promptText); var pos = methods._calculatePosition(field, prompt, options); if(options.isPopup){ var css = { "top": pos.callerTopPosition, "left": pos.callerleftPosition, "marginTop": pos.marginTopSize }; if (noAnimation) prompt.css(css); else prompt.animate(css); } } }, /** * Closes the prompt associated with the given field * * @param {jqObject} * field */ _closePrompt: function(field) { var prompt = methods._getPrompt(field); if (prompt) prompt.fadeTo("fast", 0, function() { prompt.parent('.formErrorOuter').remove(); prompt.remove(); field.removeClass("erb"); }); }, closePrompt: function(field) { return methods._closePrompt(field); }, /** * Returns the error prompt matching the field if any * * @param {jqObject} * field * @return undefined or the error prompt (jqObject) */ _getPrompt: function(field) { var formId = $(field).closest('form').attr('id'); var className = methods._getClassName(field.attr("id")) + "formError"; var match = $("." + methods._escapeExpression(className) + '.parentForm' + formId)[0]; if (match) return $(match); }, /** * Returns the escapade classname * * @param {selector} * className */ _escapeExpression: function (selector) { return selector.replace(/([#;&,\.\+\*\~':"\!\^$\[\]\(\)=>\|])/g, "\\$1"); }, /** * returns true if we are in a RTLed document * * @param {jqObject} field */ isRTL: function(field) { var $document = $(document); var $body = $('body'); var rtl = (field && field.hasClass('rtl')) || (field && (field.attr('dir') || '').toLowerCase()==='rtl') || $document.hasClass('rtl') || ($document.attr('dir') || '').toLowerCase()==='rtl' || $body.hasClass('rtl') || ($body.attr('dir') || '').toLowerCase()==='rtl'; return Boolean(rtl); }, /** * Calculates prompt position * * @param {jqObject} * field * @param {jqObject} * the prompt * @param {Map} * options * @return positions */ _calculatePosition: function (field, promptElmt, options) { var promptTopPosition, promptleftPosition, marginTopSize; var fieldWidth = field.width(); var fieldLeft = field.position().left; var fieldTop = field.position().top; var fieldHeight = field.height(); var promptHeight = promptElmt.height(); // is the form contained in an overflown container? promptTopPosition = promptleftPosition = 0; // compensation for the arrow marginTopSize = -promptHeight; //prompt positioning adjustment support //now you can adjust prompt position //usage: positionType:Xshift,Yshift //for example: // bottomLeft:+20 means bottomLeft position shifted by 20 pixels right horizontally // topRight:20, -15 means topRight position shifted by 20 pixels to right and 15 pixels to top //You can use +pixels, - pixels. If no sign is provided than + is default. var positionType=field.data("promptPosition") || options.promptPosition; var shift1=""; var shift2=""; var shiftX=0; var shiftY=0; if (typeof(positionType)=='string') { //do we have any position adjustments ? if (positionType.indexOf(":")!=-1) { shift1=positionType.substring(positionType.indexOf(":")+1); positionType=positionType.substring(0,positionType.indexOf(":")); //if any advanced positioning will be needed (percents or something else) - parser should be added here //for now we use simple parseInt() //do we have second parameter? if (shift1.indexOf(",") !=-1) { shift2=shift1.substring(shift1.indexOf(",") +1); shift1=shift1.substring(0,shift1.indexOf(",")); shiftY=parseInt(shift2); if (isNaN(shiftY)) shiftY=0; }; shiftX=parseInt(shift1); if (isNaN(shift1)) shift1=0; }; }; switch (positionType) { default: case "topRight": promptleftPosition += fieldLeft + fieldWidth - 30; promptTopPosition += fieldTop; break; case "topLeft": promptTopPosition += fieldTop; promptleftPosition += fieldLeft; break; case "centerRight": promptTopPosition = fieldTop+4; marginTopSize = 0; promptleftPosition= fieldLeft + field.outerWidth(true)+5; break; case "centerLeft": promptleftPosition = fieldLeft - (promptElmt.width() + 2); promptTopPosition = fieldTop+4; marginTopSize = 0; break; case "bottomLeft": promptTopPosition = fieldTop + field.height() + 5; marginTopSize = 0; promptleftPosition = fieldLeft; break; case "bottomRight": promptleftPosition = fieldLeft + fieldWidth - 30; promptTopPosition = fieldTop + field.height() + 5; marginTopSize = 0; }; //apply adjusments if any promptleftPosition += shiftX; promptTopPosition += shiftY; return { "callerTopPosition": promptTopPosition + "px", "callerleftPosition": promptleftPosition + "px", "marginTopSize": marginTopSize + "px" }; }, /** * Saves the user options and variables in the form.data * * @param {jqObject} * form - the form where the user option should be saved * @param {Map} * options - the user options * @return the user options (extended from the defaults) */ _saveOptions: function(form, options) { // is there a language localisation ? if ($.validationEngineLanguage) var allRules = $.validationEngineLanguage.allRules; else $.error("jQuery.validationEngine rules are not loaded, plz add localization files to the page"); // --- Internals DO NOT TOUCH or OVERLOAD --- // validation rules and i18 $.validationEngine.defaults.allrules = allRules; var userOptions = $.extend(true,{},$.validationEngine.defaults,options); form.data('jqv', userOptions); return userOptions; }, /** * Removes forbidden characters from class name * @param {String} className */ _getClassName: function(className) { if(className) return className.replace(/:/g, "_").replace(/\./g, "_"); }, /** * Escape special character for jQuery selector * http://totaldev.com/content/escaping-characters-get-valid-jquery-id * @param {String} selector */ _jqSelector: function(str){ return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); }, /** * Conditionally required field * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _condRequired: function(field, rules, i, options) { var idx, dependingField; for(idx = (i + 1); idx < rules.length; idx++) { dependingField = jQuery("#" + rules[idx]).first(); /* Use _required for determining wether dependingField has a value. * There is logic there for handling all field types, and default value; so we won't replicate that here */ if (dependingField.length && methods._required(dependingField, ["required"], 0, options) == undefined) { /* We now know any of the depending fields has a value, * so we can validate this field as per normal required code */ return methods._required(field, ["required"], 0, options); } } } }; /** * Plugin entry point. * You may pass an action as a parameter or a list of options. * if none, the init and attach methods are being called. * Remember: if you pass options, the attached method is NOT called automatically * * @param {String} * method (optional) action */ $.fn.validationEngine = function(method) { var form = $(this); if(!form[0]) return form; // stop here if the form does not exist if (typeof(method) == 'string' && method.charAt(0) != '_' && methods[method]) { // make sure init is called once if(method != "showPrompt" && method != "hide" && method != "hideAll") methods.init.apply(form); return methods[method].apply(form, Array.prototype.slice.call(arguments, 1)); } else if (typeof method == 'object' || !method) { // default constructor with or without arguments methods.init.apply(form, arguments); return methods.attach.apply(form); } else { $.error('Method ' + method + ' does not exist in jQuery.validationEngine'); } }; // LEAK GLOBAL OPTIONS $.validationEngine= {fieldIdCounter: 0,defaults:{ // Name of the event triggering field validation validationEventTrigger: "blur", // Automatically scroll viewport to the first error scroll: true, // Focus on the first input focusFirstField:true, // Opening box position, possible locations are: topLeft, // topRight, bottomLeft, centerRight, bottomRight promptPosition: "topRight", bindMethod:"bind", // internal, automatically set to true when it parse a _ajax rule inlineAjax: false, // if set to true, the form data is sent asynchronously via ajax to the form.action url (get) ajaxFormValidation: false, // The url to send the submit ajax validation (default to action) ajaxFormValidationURL: false, // HTTP method used for ajax validation ajaxFormValidationMethod: 'get', // Ajax form validation callback method: boolean onComplete(form, status, errors, options) // retuns false if the form.submit event needs to be canceled. onAjaxFormComplete: $.noop, // called right before the ajax call, may return false to cancel onBeforeAjaxFormValidation: $.noop, // Stops form from submitting and execute function assiciated with it onValidationComplete: false, // Used when you have a form fields too close and the errors messages are on top of other disturbing viewing messages doNotShowAllErrosOnSubmit: false, // Object where you store custom messages to override the default error messages custom_error_messages:{}, // true if you want to vind the input fields binded: true, // set to true, when the prompt arrow needs to be displayed showArrow: true, // did one of the validation fail ? kept global to stop further ajax validations isError: false, // Limit how many displayed errors a field can have maxErrorsPerField: false, // Caches field validation status, typically only bad status are created. // the array is used during ajax form validation to detect issues early and prevent an expensive submit ajaxValidCache: {}, // Auto update prompt position after window resize autoPositionUpdate: false, InvalidFields: [], onFieldSuccess: false, onFieldFailure: false, onFormSuccess: false, onFormFailure: false, addSuccessCssClassToField: false, addFailureCssClassToField: false, // Auto-hide prompt autoHidePrompt: false, // Delay before auto-hide autoHideDelay: 10000, // Fade out duration while hiding the validations fadeDuration: 0.3, // Use Prettify select library prettySelect: false, // Custom ID uses prefix usePrefix: "", // Custom ID uses suffix useSuffix: "", // Only show one message per error prompt showOneMessage: false }}; $(function(){$.validationEngine.defaults.promptPosition = methods.isRTL()?'topLeft':"topRight"}); })(jQuery);
JavaScript
(function($){ $.fn.validationEngineLanguage = function(){ }; $.validationEngineLanguage = { newLang: function(){ $.validationEngineLanguage.allRules = { "required": { // Add your regex rules here, you can take telephone as an example "regex": "none", "alertText": "* This field is required", "alertTextCheckboxMultiple": "* Please select an option", "alertTextCheckboxe": "* This checkbox is required", "alertTextDateRange": "* Both date range fields are required" }, "requiredInFunction": { "func": function(field, rules, i, options){ return (field.val() === "test") ? true : false; }, "alertText": "* Field must equal test" }, "dateRange": { "regex": "none", "alertText": "* Invalid ", "alertText2": "Date Range" }, "dateTimeRange": { "regex": "none", "alertText": "* Invalid ", "alertText2": "Date Time Range" }, "minSize": { "regex": "none", "alertText": "* Minimum ", "alertText2": " characters allowed" }, "maxSize": { "regex": "none", "alertText": "* Maximum ", "alertText2": " characters allowed" }, "groupRequired": { "regex": "none", "alertText": "* You must fill one of the following fields" }, "min": { "regex": "none", "alertText": "* Minimum value is " }, "max": { "regex": "none", "alertText": "* Maximum value is " }, "past": { "regex": "none", "alertText": "* Date prior to " }, "future": { "regex": "none", "alertText": "* Date past " }, "maxCheckbox": { "regex": "none", "alertText": "* Maximum ", "alertText2": " options allowed" }, "minCheckbox": { "regex": "none", "alertText": "* Please select ", "alertText2": " options" }, "equals": { "regex": "none", "alertText": "* Fields do not match" }, "creditCard": { "regex": "none", "alertText": "* Invalid credit card number" }, "phone": { // credit: jquery.h5validate.js / orefalo "regex": /^([\+][0-9]{1,3}[\ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9\ \.\-\/]{3,20})((x|ext|extension)[\ ]?[0-9]{1,4})?$/, "alertText": "* Invalid phone number" }, "alias":{ "regex": /^[0-9a-z\-]+$/, "alertText": "* Invalid alias" }, "email": { // HTML5 compatible email regex ( http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html# e-mail-state-%28type=email%29 ) "regex": /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/, "alertText": "* Invalid email address" }, "integer": { "regex": /^[\-\+]?\d+$/, "alertText": "* Not a valid integer" }, "number": { // Number, including positive, negative, and floating decimal. credit: orefalo "regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/, "alertText": "* Invalid floating decimal number" }, "date": { // Check if date is valid by leap year "func": function (field) { var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/); var match = pattern.exec(field.val()); if (match === null) return false; var year = match[1]; var month = match[2]*1; var day = match[3]*1; var date = new Date(year, month - 1, day); // because months starts from 0. return (date.getFullYear() === year && date.getMonth() === (month - 1) && date.getDate() === day); }, "alertText": "* Invalid date, must be in YYYY-MM-DD format" }, "ipv4": { "regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/, "alertText": "* Invalid IP address" }, "url": { "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i, "alertText": "* Invalid URL" }, "onlyNumberSp": { "regex": /^[0-9\ ]+$/, "alertText": "* Numbers only" }, "onlyLetterSp": { "regex": /^[a-zA-Z\ \']+$/, "alertText": "* Letters only" }, "onlyLetterNumber": { "regex": /^[0-9a-zA-Z]+$/, "alertText": "* No special characters allowed" }, // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings "ajaxUserCall": { "url": "ajaxValidateFieldUser", // you may want to pass extra data on the ajax call "extraData": "name=eric", "alertText": "* This user is already taken", "alertTextLoad": "* Validating, please wait" }, "ajaxUserCallPhp": { "url": "phpajax/ajaxValidateFieldUser.php", // you may want to pass extra data on the ajax call "extraData": "name=eric", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* This username is available", "alertText": "* This user is already taken", "alertTextLoad": "* Validating, please wait" }, "ajaxNameCall": { // remote json service location "url": "ajaxValidateFieldName", // error "alertText": "* This name is already taken", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* This name is available", // speaks by itself "alertTextLoad": "* Validating, please wait" }, "ajaxNameCallPhp": { // remote json service location "url": "phpajax/ajaxValidateFieldName.php", // error "alertText": "* This name is already taken", // speaks by itself "alertTextLoad": "* Validating, please wait" }, "validate2fields": { "alertText": "* Please input HELLO" }, //tls warning:homegrown not fielded "dateFormat":{ "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/, "alertText": "* Invalid Date" }, //tls warning:homegrown not fielded "dateTimeFormat": { "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/, "alertText": "* Invalid Date or Date Format", "alertText2": "Expected Format: ", "alertText3": "mm/dd/yyyy hh:mm:ss AM|PM or ", "alertText4": "yyyy-mm-dd hh:mm:ss AM|PM" } }; } }; $.validationEngineLanguage.newLang(); })(jQuery);
JavaScript
(function($){ $.fn.validationEngineLanguage = function(){ }; $.validationEngineLanguage = { newLang: function(){ $.validationEngineLanguage.allRules = { "required": { // Add your regex rules here, you can take telephone as an example "regex": "none", "alertText": "* Trường này bắt buộc", "alertTextCheckboxMultiple": "* Vui lòng chọn một tùy chọn", "alertTextCheckboxe": "* Checkbox này bắt buộc", "alertTextDateRange": "* Cả hai trường ngày tháng đều bắt buộc" }, "requiredInFunction": { "func": function(field, rules, i, options){ return (field.val() == "test") ? true : false; }, "alertText": "* Giá trị của trường phải là test" }, "minNumber": { "func": function(field, rules, i, options){ console.log(rules.maxNumber); return (isNaN(field.val()) || parseInt(field.val())<rules[2]) ? false : true; }, "alertText": "* Giá trị không hợp lệ." }, "maxNumber": { "func": function(field, rules, i, options){ console.log(options.allrules); return (isNaN(field.val()) || parseInt(field.val())>rules[2]) ? false : true; }, "alertText": "* Giá trị không hợp lệ." }, "dateRange": { "regex": "none", "alertText": "* Không đúng ", "alertText2": "Khoảng ngày tháng" }, "dateTimeRange": { "regex": "none", "alertText": "* Không đúng ", "alertText2": "Khoảng thời gian" }, "minSize": { "regex": "none", "alertText": "* Tối thiểu là ", "alertText2": " ký tự" }, "maxSize": { "regex": "none", "alertText": "* Tối đa là ", "alertText2": " ký tự" }, "groupRequired": { "regex": "none", "alertText": "* Bạn phải điền một trong những trường sau" }, "min": { "regex": "none", "alertText": "* Giá trị nhỏ nhất là " }, "max": { "regex": "none", "alertText": "* Giá trị lớn nhất là " }, "past": { "regex": "none", "alertText": "* Ngày kéo dài tới " }, "future": { "regex": "none", "alertText": "* Ngày đã qua " }, "maxCheckbox": { "regex": "none", "alertText": "* Tối đa ", "alertText2": " số tùy chọn được cho phép" }, "minCheckbox": { "regex": "none", "alertText": "* Vui lòng chọn ", "alertText2": " các tùy chọn" }, "equals": { "regex": "none", "alertText": "* Giá trị các trường không giống nhau" }, "creditCard": { "regex": "none", "alertText": "* Số thẻ tín dụng sai" }, "phone": { // credit: jquery.h5validate.js / orefalo "regex": /^([\+][0-9]{1,3}[\ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9\ \.\-\/]{3,20})((x|ext|extension)[\ ]?[0-9]{1,4})?$/, "alertText": "* Số điện thoại sai" }, "email": { // HTML5 compatible email regex ( http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html# e-mail-state-%28type=email%29 ) "regex": /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/, "alertText": "* Địa chỉ thư điện tử sai" }, "integer": { "regex": /^[\-\+]?\d+$/, "alertText": "* Không đúng là số nguyên" }, "number": { // Number, including positive, negative, and floating decimal. credit: orefalo "regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/, "alertText": "* Không đúng là số" }, "date": { "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/, "alertText": "* Ngày sai, phải có định dạng YYYY-MM-DD" }, "ipv4": { "regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/, "alertText": "* Địa chỉ IP sai" }, "url": { "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i, "alertText": "* URL sai" }, "phone_":{ "regex": /^[0-9\ ,(,),.,\-,+]{7,20}$/, "alertText": "* Định dạng phone sai" }, "alias":{ "regex": /^[0-9a-z\-]+$/, "alertText": "* Định dạng alias sai" }, "onlyNumberSp": { "regex": /^[0-9\ ]+$/, "alertText": "* Chỉ điền số" }, "onlyLetterSp": { "regex": /^[a-zA-Z\ \']+$/, "alertText": "* Chỉ điền chữ" }, "onlyLetterNumber": { "regex": /^[0-9a-zA-Z]+$/, "alertText": "* Không được chứa ký tự đặc biệt" }, // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings "ajaxUserCall": { "url": "ajaxValidateFieldUser", // you may want to pass extra data on the ajax call "extraData": "name=eric", "alertText": "* Tên này được dùng", "alertTextLoad": "* Đang xác nhận, vui lòng chờ" }, "ajaxUserCallPhp": { "url": "phpajax/ajaxValidateFieldUser.php", // you may want to pass extra data on the ajax call "extraData": "name=eric", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* Tên người dùng này có thể dùng được", "alertText": "* Tên người dùng này đã được sử dụng", "alertTextLoad": "* Đang xác nhận, vui lòng chờ" }, "ajaxNameCall": { // remote json service location "url": "ajaxValidateFieldName", // error "alertText": "* Tên này được dùng", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* Tên này có thể dùng", // speaks by itself "alertTextLoad": "* Đang xác nhận, vui lòng chờ" }, "ajaxNameCallPhp": { // remote json service location "url": "phpajax/ajaxValidateFieldName.php", // error "alertText": "* Tên này được dùng", // speaks by itself "alertTextLoad": "* Đang xác nhận, vui lòng chờ" }, "validate2fields": { "alertText": "* Vui lòng nhập vào HELLO" }, //tls warning:homegrown not fielded "dateFormat":{ "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/, "alertText": "* Ngày sai" }, //tls warning:homegrown not fielded "dateTimeFormat": { "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/, "alertText": "* Ngày sai hoặc định dạng ngày sai", "alertText2": "Định dạng đúng là: ", "alertText3": "mm/dd/yyyy hh:mm:ss AM|PM hay ", "alertText4": "yyyy-mm-dd hh:mm:ss AM|PM" } }; } }; $.validationEngineLanguage.newLang(); })(jQuery);
JavaScript
;/***************************************************************** * Japanese language file for jquery.validationEngine.js (ver2.0) * * Transrator: tomotomo ( Tomoyuki SUGITA ) * http://tomotomoSnippet.blogspot.com/ * Licenced under the MIT Licence *******************************************************************/ (function($){ $.fn.validationEngineLanguage = function(){ }; $.validationEngineLanguage = { newLang: function(){ $.validationEngineLanguage.allRules = { "required": { // Add your regex rules here, you can take telephone as an example "regex": "none", "alertText": "* 必須項目です", "alertTextCheckboxMultiple": "* 選択してください", "alertTextCheckboxe": "* チェックボックスをチェックしてください" }, "requiredInFunction": { "func": function(field, rules, i, options){ return (field.val() == "test") ? true : false; }, "alertText": "* Field must equal test" }, "minSize": { "regex": "none", "alertText": "* ", "alertText2": "文字以上にしてください" }, "groupRequired": { "regex": "none", "alertText": "* You must fill one of the following fields" }, "maxSize": { "regex": "none", "alertText": "* ", "alertText2": "文字以下にしてください" }, "min": { "regex": "none", "alertText": "* ", "alertText2": " 以上の数値にしてください" }, "max": { "regex": "none", "alertText": "* ", "alertText2": " 以下の数値にしてください" }, "past": { "regex": "none", "alertText": "* ", "alertText2": " より過去の日付にしてください" }, "future": { "regex": "none", "alertText": "* ", "alertText2": " より最近の日付にしてください" }, "maxCheckbox": { "regex": "none", "alertText": "* チェックしすぎです" }, "minCheckbox": { "regex": "none", "alertText": "* ", "alertText2": "つ以上チェックしてください" }, "equals": { "regex": "none", "alertText": "* 入力された値が一致しません" }, "creditCard": { "regex": "none", "alertText": "* 無効なクレジットカード番号" }, "phone": { // credit: jquery.h5validate.js / orefalo "regex": /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/, "alertText": "* 電話番号が正しくありません" }, "email": { // Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/ "regex": /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "alertText": "* メールアドレスが正しくありません" }, "integer": { "regex": /^[\-\+]?\d+$/, "alertText": "* 整数を半角で入力してください" }, "number": { // Number, including positive, negative, and floating decimal. credit: orefalo "regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/, "alertText": "* 数値を半角で入力してください" }, "date": { "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/, "alertText": "* 日付は半角で YYYY-MM-DD の形式で入力してください" }, "ipv4": { "regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/, "alertText": "* IPアドレスが正しくありません" }, "url": { "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i, "alertText": "* URLが正しくありません" }, "onlyNumberSp": { "regex": /^[0-9\ ]+$/, "alertText": "* 半角数字で入力してください" }, "onlyLetterSp": { "regex": /^[a-zA-Z\ \']+$/, "alertText": "* 半角アルファベットで入力してください" }, "onlyLetterNumber": { "regex": /^[0-9a-zA-Z]+$/, "alertText": "* 半角英数で入力してください" }, // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings "ajaxUserCall": { "url": "ajaxValidateFieldUser", // you may want to pass extra data on the ajax call "extraData": "name=eric", "alertText": "* This user is already taken", "alertTextLoad": "* Validating, please wait" }, "ajaxNameCall": { // remote json service location "url": "ajaxValidateFieldName", // error "alertText": "* This name is already taken", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* This name is available", // speaks by itself "alertTextLoad": "* Validating, please wait" }, "validate2fields": { "alertText": "* 『HELLO』と入力してください" } }; } }; $.validationEngineLanguage.newLang(); })(jQuery);
JavaScript
(function($){ $.fn.validationEngineLanguage = function(){ }; $.validationEngineLanguage = { newLang: function(){ $.validationEngineLanguage.allRules = { "required": { "regex": "none", "alertText": "* Ce champ est requis", "alertTextCheckboxMultiple": "* Choisir une option", "alertTextCheckboxe": "* Cette option est requise" }, "requiredInFunction": { "func": function(field, rules, i, options){ return (field.val() == "test") ? true : false; }, "alertText": "* Field must equal test" }, "minSize": { "regex": "none", "alertText": "* Minimum ", "alertText2": " caractères requis" }, "groupRequired": { "regex": "none", "alertText": "* Vous devez remplir un des champs suivant" }, "maxSize": { "regex": "none", "alertText": "* Maximum ", "alertText2": " caractères requis" }, "min": { "regex": "none", "alertText": "* Valeur minimum requise " }, "max": { "regex": "none", "alertText": "* Valeur maximum requise " }, "past": { "regex": "none", "alertText": "* Date antérieure au " }, "future": { "regex": "none", "alertText": "* Date postérieure au " }, "maxCheckbox": { "regex": "none", "alertText": "* Nombre max de choix excédé" }, "minCheckbox": { "regex": "none", "alertText": "* Veuillez choisir ", "alertText2": " options" }, "equals": { "regex": "none", "alertText": "* Votre champ n'est pas identique" }, "creditCard": { "regex": "none", "alertText": "* Numéro de carte bancaire valide" }, "phone": { // credit: jquery.h5validate.js / orefalo "regex": /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/, "alertText": "* Numéro de téléphone invalide" }, "email": { // Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/ "regex": /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "alertText": "* Adresse email invalide" }, "integer": { "regex": /^[\-\+]?\d+$/, "alertText": "* Nombre entier invalide" }, "number": { // Number, including positive, negative, and floating decimal. credit: orefalo "regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/, "alertText": "* Nombre flottant invalide" }, "date": { "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/, "alertText": "* Date invalide, format YYYY-MM-DD requis" }, "ipv4": { "regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/, "alertText": "* Adresse IP invalide" }, "url": { "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i, "alertText": "* URL invalide" }, "onlyNumberSp": { "regex": /^[0-9\ ]+$/, "alertText": "* Seuls les chiffres sont acceptés" }, "onlyLetterSp": { "regex": /^[a-zA-Z\u00C0-\u00D6\u00D9-\u00F6\u00F9-\u00FD\ \']+$/, "alertText": "* Seules les lettres sont acceptées" }, "onlyLetterNumber": { "regex": /^[0-9a-zA-Z\u00C0-\u00D6\u00D9-\u00F6\u00F9-\u00FD]+$/, "alertText": "* Aucun caractère spécial n'est accepté" }, // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings "ajaxUserCall": { "url": "ajaxValidateFieldUser", "extraData": "name=eric", "alertTextLoad": "* Chargement, veuillez attendre", "alertText": "* Ce nom est déjà pris" }, "ajaxNameCall": { "url": "ajaxValidateFieldName", "alertText": "* Ce nom est déjà pris", "alertTextOk": "*Ce nom est disponible", "alertTextLoad": "* Chargement, veuillez attendre" }, "validate2fields": { "alertText": "Veuillez taper le mot HELLO" } }; } }; $.validationEngineLanguage.newLang(); })(jQuery);
JavaScript
/* Respond.js unit tests - based on qUnit */ window.onload = function(){ if( !window.opener ){ document.documentElement.className = "launcher"; document.getElementById("launcher").innerHTML = '<p>Tests must run in a popup window. <a href="suite.html" id="suitelink">Open test suite</a></p>'; document.getElementById( "suitelink" ).onclick = function(){ window.open( location.href + "?" + Math.random(), 'win', 'width=800,height=600,scrollbars=1,resizable=1' ); return false; }; } else { var testElem = document.getElementById("testelem"); //check if a particular style has applied properly function widthApplied( val ){ return testElem.offsetWidth === val; } function heightApplied( val ){ return testElem.offsetHeight === val; } // A short snippet for detecting versions of IE in JavaScript - author: @padolsey var ie = (function(){ var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0] ); return v > 4 ? v : undef; }()); window.moveTo(0,0); /* TESTS HERE */ asyncTest( 'Styles not nested in media queries apply as expected', function() { window.resizeTo(200,600); setTimeout(function(){ ok( widthApplied( 50 ), "testelem is 50px wide when window is 200px wide" ); start(); }, 900); }); asyncTest( 'styles within min-width media queries apply properly', function() { window.resizeTo(520,600); setTimeout(function(){ ok( widthApplied( 150 ), 'testelem is 150px wide when window is 500px wide' ); start(); }, 900); }); // This test is for a feature in IE7 and up if( ie >= 7 ){ asyncTest( "attribute selectors still work (where supported) after respond runs its course", function() { window.resizeTo(520,600); setTimeout(function(){ ok( heightApplied( 200 ), "testelem is 200px tall when window is 500px wide" ); start(); }, 900); }); } asyncTest( 'styles within max-width media queries apply properly', function() { window.resizeTo(300,600); setTimeout(function(){ ok( heightApplied( 150 ), 'testelem is 150px tall when window is under 480px wide' ); start(); }, 900); }); asyncTest( 'min and max-width media queries that use EM units apply properly', function() { window.resizeTo(560,600); setTimeout(function(){ ok( widthApplied( 12 ), 'testelem is 150px wide when window is 500px wide' ); start(); }, 900); }); asyncTest( "styles within a min-width media query with an \"only\" keyword apply properly", function() { window.resizeTo(650,600); setTimeout(function(){ ok( widthApplied( 250 ), "testelem is 250px wide when window is 650px wide" ); start(); }, 900); }); asyncTest( "styles within a media query with a one true query among other false queries apply properly", function() { window.resizeTo(800,600); setTimeout(function(){ ok( widthApplied( 350 ), "testelem is 350px wide when window is 750px wide" ); start(); }, 900); }); asyncTest( "Styles within a false media query do not apply", function() { window.resizeTo(800,600); setTimeout(function(){ ok( !widthApplied( 500 ), "testelem is not 500px wide when window is 800px wide" ); start(); }, 900); }); asyncTest( "stylesheets with a media query in a media attribute apply when they should", function() { window.resizeTo(1300,600); setTimeout(function(){ ok( widthApplied( 16 ), "testelem is 16px wide when window is 1300px wide" ); start(); }, 900); }); asyncTest( "stylesheets with an EM-based media query in a media attribute apply when they should", function() { window.resizeTo(1500,600); setTimeout(function(){ ok( widthApplied( 25 ), "testelem is 25px wide when window is > 1400px wide" ); start(); }, 900); }); } };
JavaScript
/** * QUnit v1.3.0pre - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2011 John Resig, Jörn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * or GPL (GPL-LICENSE.txt) licenses. */ (function(window) { var defined = { setTimeout: typeof window.setTimeout !== "undefined", sessionStorage: (function() { try { return !!sessionStorage.getItem; } catch(e) { return false; } })() }; var testId = 0, toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty; var Test = function(name, testName, expected, testEnvironmentArg, async, callback) { this.name = name; this.testName = testName; this.expected = expected; this.testEnvironmentArg = testEnvironmentArg; this.async = async; this.callback = callback; this.assertions = []; }; Test.prototype = { init: function() { var tests = id("qunit-tests"); if (tests) { var b = document.createElement("strong"); b.innerHTML = "Running " + this.name; var li = document.createElement("li"); li.appendChild( b ); li.className = "running"; li.id = this.id = "test-output" + testId++; tests.appendChild( li ); } }, setup: function() { if (this.module != config.previousModule) { if ( config.previousModule ) { runLoggingCallbacks('moduleDone', QUnit, { name: config.previousModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all } ); } config.previousModule = this.module; config.moduleStats = { all: 0, bad: 0 }; runLoggingCallbacks( 'moduleStart', QUnit, { name: this.module } ); } config.current = this; this.testEnvironment = extend({ setup: function() {}, teardown: function() {} }, this.moduleTestEnvironment); if (this.testEnvironmentArg) { extend(this.testEnvironment, this.testEnvironmentArg); } runLoggingCallbacks( 'testStart', QUnit, { name: this.testName, module: this.module }); // allow utility functions to access the current test environment // TODO why?? QUnit.current_testEnvironment = this.testEnvironment; try { if ( !config.pollution ) { saveGlobal(); } this.testEnvironment.setup.call(this.testEnvironment); } catch(e) { QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message ); } }, run: function() { config.current = this; if ( this.async ) { QUnit.stop(); } if ( config.notrycatch ) { this.callback.call(this.testEnvironment); return; } try { this.callback.call(this.testEnvironment); } catch(e) { fail("Test " + this.testName + " died, exception and test follows", e, this.callback); QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { QUnit.start(); } } }, teardown: function() { config.current = this; try { this.testEnvironment.teardown.call(this.testEnvironment); checkPollution(); } catch(e) { QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message ); } }, finish: function() { config.current = this; if ( this.expected != null && this.expected != this.assertions.length ) { QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" ); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += this.assertions.length; config.moduleStats.all += this.assertions.length; if ( tests ) { var ol = document.createElement("ol"); for ( var i = 0; i < this.assertions.length; i++ ) { var assertion = this.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed"); ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } // store result when possible if ( QUnit.config.reorder && defined.sessionStorage ) { if (bad) { sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad); } else { sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName); } } if (bad == 0) { ol.style.display = "none"; } var b = document.createElement("strong"); b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>"; var a = document.createElement("a"); a.innerHTML = "Rerun"; a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); addEvent(b, "click", function() { var next = b.nextSibling.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = e && e.target ? e.target : window.event.srcElement; if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { target = target.parentNode; } if ( window.location && target.nodeName.toLowerCase() === "strong" ) { window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); } }); var li = id(this.id); li.className = bad ? "fail" : "pass"; li.removeChild( li.firstChild ); li.appendChild( b ); li.appendChild( a ); li.appendChild( ol ); } else { for ( var i = 0; i < this.assertions.length; i++ ) { if ( !this.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } try { QUnit.reset(); } catch(e) { fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset); } runLoggingCallbacks( 'testDone', QUnit, { name: this.testName, module: this.module, failed: bad, passed: this.assertions.length - bad, total: this.assertions.length } ); }, queue: function() { var test = this; synchronize(function() { test.init(); }); function run() { // each of these can by async synchronize(function() { test.setup(); }); synchronize(function() { test.run(); }); synchronize(function() { test.teardown(); }); synchronize(function() { test.finish(); }); } // defer when previous test run passed, if storage is available var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName); if (bad) { run(); } else { synchronize(run, true); }; } }; var QUnit = { // call on start of module test to prepend name to all tests module: function(name, testEnvironment) { config.currentModule = name; config.currentModuleTestEnviroment = testEnvironment; }, asyncTest: function(testName, expected, callback) { if ( arguments.length === 2 ) { callback = expected; expected = null; } QUnit.test(testName, expected, callback, true); }, test: function(testName, expected, callback, async) { var name = '<span class="test-name">' + escapeInnerText(testName) + '</span>', testEnvironmentArg; if ( arguments.length === 2 ) { callback = expected; expected = null; } // is 2nd argument a testEnvironment? if ( expected && typeof expected === 'object') { testEnvironmentArg = expected; expected = null; } if ( config.currentModule ) { name = '<span class="module-name">' + config.currentModule + "</span>: " + name; } if ( !validTest(config.currentModule + ": " + testName) ) { return; } var test = new Test(name, testName, expected, testEnvironmentArg, async, callback); test.module = config.currentModule; test.moduleTestEnvironment = config.currentModuleTestEnviroment; test.queue(); }, /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ expect: function(asserts) { config.current.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function(a, msg) { a = !!a; var details = { result: a, message: msg }; msg = escapeInnerText(msg); runLoggingCallbacks( 'log', QUnit, details ); config.current.assertions.push({ result: a, message: msg }); }, /** * Checks that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * * Prefered to ok( actual == expected, message ) * * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); * * @param Object actual * @param Object expected * @param String message (optional) */ equal: function(actual, expected, message) { QUnit.push(expected == actual, actual, expected, message); }, notEqual: function(actual, expected, message) { QUnit.push(expected != actual, actual, expected, message); }, deepEqual: function(actual, expected, message) { QUnit.push(QUnit.equiv(actual, expected), actual, expected, message); }, notDeepEqual: function(actual, expected, message) { QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message); }, strictEqual: function(actual, expected, message) { QUnit.push(expected === actual, actual, expected, message); }, notStrictEqual: function(actual, expected, message) { QUnit.push(expected !== actual, actual, expected, message); }, raises: function(block, expected, message) { var actual, ok = false; if (typeof expected === 'string') { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } if (actual) { // we don't want to validate thrown error if (!expected) { ok = true; // expected is a regexp } else if (QUnit.objectType(expected) === "regexp") { ok = expected.test(actual); // expected is a constructor } else if (actual instanceof expected) { ok = true; // expected is a validation function which returns true is validation passed } else if (expected.call({}, actual) === true) { ok = true; } } QUnit.ok(ok, message); }, start: function(count) { config.semaphore -= count || 1; if (config.semaphore > 0) { // don't start until equal number of stop-calls return; } if (config.semaphore < 0) { // ignore if start is called more often then stop config.semaphore = 0; } // A slight delay, to avoid any current callbacks if ( defined.setTimeout ) { window.setTimeout(function() { if (config.semaphore > 0) { return; } if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(true); }, 13); } else { config.blocking = false; process(true); } }, stop: function(count) { config.semaphore += count || 1; config.blocking = true; if ( config.testTimeout && defined.setTimeout ) { clearTimeout(config.timeout); config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); config.semaphore = 1; QUnit.start(); }, config.testTimeout); } } }; //We want access to the constructor's prototype (function() { function F(){}; F.prototype = QUnit; QUnit = new F(); //Make F QUnit's constructor so that we can add to the prototype later QUnit.constructor = F; })(); // Backwards compatibility, deprecated QUnit.equals = QUnit.equal; QUnit.same = QUnit.deepEqual; // Maintain internal state var config = { // The queue of tests to run queue: [], // block until document ready blocking: true, // when enabled, show only failing tests // gets persisted through sessionStorage and can be changed in UI via checkbox hidepassed: false, // by default, run previously failed tests first // very useful in combination with "Hide passed tests" checked reorder: true, // by default, modify document.title when suite is done altertitle: true, urlConfig: ['noglobals', 'notrycatch'], //logging callback queues begin: [], done: [], log: [], testStart: [], testDone: [], moduleStart: [], moduleDone: [] }; // Load paramaters (function() { var location = window.location || { search: "", protocol: "file:" }, params = location.search.slice( 1 ).split( "&" ), length = params.length, urlParams = {}, current; if ( params[ 0 ] ) { for ( var i = 0; i < length; i++ ) { current = params[ i ].split( "=" ); current[ 0 ] = decodeURIComponent( current[ 0 ] ); // allow just a key to turn on a flag, e.g., test.html?noglobals current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; urlParams[ current[ 0 ] ] = current[ 1 ]; } } QUnit.urlParams = urlParams; config.filter = urlParams.filter; // Figure out if we're running the tests from a server or not QUnit.isLocal = !!(location.protocol === 'file:'); })(); // Expose the API as global variables, unless an 'exports' // object exists, in that case we assume we're in CommonJS if ( typeof exports === "undefined" || typeof require === "undefined" ) { extend(window, QUnit); window.QUnit = QUnit; } else { extend(exports, QUnit); exports.QUnit = QUnit; } // define these after exposing globals to keep them in these QUnit namespace only extend(QUnit, { config: config, // Initialize the configuration options init: function() { extend(config, { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date, updateRate: 1000, blocking: false, autostart: true, autorun: false, filter: "", queue: [], semaphore: 0 }); var tests = id( "qunit-tests" ), banner = id( "qunit-banner" ), result = id( "qunit-testresult" ); if ( tests ) { tests.innerHTML = ""; } if ( banner ) { banner.className = ""; } if ( result ) { result.parentNode.removeChild( result ); } if ( tests ) { result = document.createElement( "p" ); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests ); result.innerHTML = 'Running...<br/>&nbsp;'; } }, /** * Resets the test setup. Useful for tests that modify the DOM. * * If jQuery is available, uses jQuery's html(), otherwise just innerHTML. */ reset: function() { if ( window.jQuery ) { jQuery( "#qunit-fixture" ).html( config.fixture ); } else { var main = id( 'qunit-fixture' ); if ( main ) { main.innerHTML = config.fixture; } } }, /** * Trigger an event on an element. * * @example triggerEvent( document.body, "click" ); * * @param DOMElement elem * @param String type */ triggerEvent: function( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent("on"+type); } }, // Safe object type checking is: function( type, obj ) { return QUnit.objectType( obj ) == type; }, objectType: function( obj ) { if (typeof obj === "undefined") { return "undefined"; // consider: typeof null === object } if (obj === null) { return "null"; } var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || ''; switch (type) { case 'Number': if (isNaN(obj)) { return "nan"; } else { return "number"; } case 'String': case 'Boolean': case 'Array': case 'Date': case 'RegExp': case 'Function': return type.toLowerCase(); } if (typeof obj === "object") { return "object"; } return undefined; }, push: function(result, actual, expected, message) { var details = { result: result, message: message, actual: actual, expected: expected }; message = escapeInnerText(message) || (result ? "okay" : "failed"); message = '<span class="test-message">' + message + "</span>"; expected = escapeInnerText(QUnit.jsDump.parse(expected)); actual = escapeInnerText(QUnit.jsDump.parse(actual)); var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>'; if (actual != expected) { output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>'; output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>'; } if (!result) { var source = sourceFromStacktrace(); if (source) { details.source = source; output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>'; } } output += "</table>"; runLoggingCallbacks( 'log', QUnit, details ); config.current.assertions.push({ result: !!result, message: output }); }, url: function( params ) { params = extend( extend( {}, QUnit.urlParams ), params ); var querystring = "?", key; for ( key in params ) { if ( !hasOwn.call( params, key ) ) { continue; } querystring += encodeURIComponent( key ) + "=" + encodeURIComponent( params[ key ] ) + "&"; } return window.location.pathname + querystring.slice( 0, -1 ); }, extend: extend, id: id, addEvent: addEvent }); //QUnit.constructor is set to the empty F() above so that we can add to it's prototype later //Doing this allows us to tell if the following methods have been overwritten on the actual //QUnit object, which is a deprecated way of using the callbacks. extend(QUnit.constructor.prototype, { // Logging callbacks; all receive a single argument with the listed properties // run test/logs.html for any related changes begin: registerLoggingCallback('begin'), // done: { failed, passed, total, runtime } done: registerLoggingCallback('done'), // log: { result, actual, expected, message } log: registerLoggingCallback('log'), // testStart: { name } testStart: registerLoggingCallback('testStart'), // testDone: { name, failed, passed, total } testDone: registerLoggingCallback('testDone'), // moduleStart: { name } moduleStart: registerLoggingCallback('moduleStart'), // moduleDone: { name, failed, passed, total } moduleDone: registerLoggingCallback('moduleDone') }); if ( typeof document === "undefined" || document.readyState === "complete" ) { config.autorun = true; } QUnit.load = function() { runLoggingCallbacks( 'begin', QUnit, {} ); // Initialize the config, saving the execution queue var oldconfig = extend({}, config); QUnit.init(); extend(config, oldconfig); config.blocking = false; var urlConfigHtml = '', len = config.urlConfig.length; for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) { config[val] = QUnit.urlParams[val]; urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>'; } var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var banner = id("qunit-header"); if ( banner ) { banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml; addEvent( banner, "change", function( event ) { var params = {}; params[ event.target.name ] = event.target.checked ? true : undefined; window.location = QUnit.url( params ); }); } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; addEvent( filter, "click", function() { var ol = document.getElementById("qunit-tests"); if ( filter.checked ) { ol.className = ol.className + " hidepass"; } else { var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; ol.className = tmp.replace(/ hidepass /, " "); } if ( defined.sessionStorage ) { if (filter.checked) { sessionStorage.setItem("qunit-filter-passed-tests", "true"); } else { sessionStorage.removeItem("qunit-filter-passed-tests"); } } }); if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) { filter.checked = true; var ol = document.getElementById("qunit-tests"); ol.className = ol.className + " hidepass"; } toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "qunit-filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); } var main = id('qunit-fixture'); if ( main ) { config.fixture = main.innerHTML; } if (config.autostart) { QUnit.start(); } }; addEvent(window, "load", QUnit.load); // addEvent(window, "error") gives us a useless event object window.onerror = function( message, file, line ) { if ( QUnit.config.current ) { ok( false, message + ", " + file + ":" + line ); } else { test( "global failure", function() { ok( false, message + ", " + file + ":" + line ); }); } }; function done() { config.autorun = true; // Log the last module results if ( config.currentModule ) { runLoggingCallbacks( 'moduleDone', QUnit, { name: config.currentModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all } ); } var banner = id("qunit-banner"), tests = id("qunit-tests"), runtime = +new Date - config.started, passed = config.stats.all - config.stats.bad, html = [ 'Tests completed in ', runtime, ' milliseconds.<br/>', '<span class="passed">', passed, '</span> tests of <span class="total">', config.stats.all, '</span> passed, <span class="failed">', config.stats.bad, '</span> failed.' ].join(''); if ( banner ) { banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); } if ( tests ) { id( "qunit-testresult" ).innerHTML = html; } if ( config.altertitle && typeof document !== "undefined" && document.title ) { // show ✖ for good, ✔ for bad suite result in title // use escape sequences in case file gets loaded with non-utf-8-charset document.title = [ (config.stats.bad ? "\u2716" : "\u2714"), document.title.replace(/^[\u2714\u2716] /i, "") ].join(" "); } runLoggingCallbacks( 'done', QUnit, { failed: config.stats.bad, passed: passed, total: config.stats.all, runtime: runtime } ); } function validTest( name ) { var filter = config.filter, run = false; if ( !filter ) { return true; } var not = filter.charAt( 0 ) === "!"; if ( not ) { filter = filter.slice( 1 ); } if ( name.indexOf( filter ) !== -1 ) { return !not; } if ( not ) { run = true; } return run; } // so far supports only Firefox, Chrome and Opera (buggy) // could be extended in the future to use something like https://github.com/csnover/TraceKit function sourceFromStacktrace() { try { throw new Error(); } catch ( e ) { if (e.stacktrace) { // Opera return e.stacktrace.split("\n")[6]; } else if (e.stack) { // Firefox, Chrome return e.stack.split("\n")[4]; } else if (e.sourceURL) { // Safari, PhantomJS // TODO sourceURL points at the 'throw new Error' line above, useless //return e.sourceURL + ":" + e.line; } } } function escapeInnerText(s) { if (!s) { return ""; } s = s + ""; return s.replace(/[\&<>]/g, function(s) { switch(s) { case "&": return "&amp;"; case "<": return "&lt;"; case ">": return "&gt;"; default: return s; } }); } function synchronize( callback, last ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process(last); } } function process( last ) { var start = new Date().getTime(); config.depth = config.depth ? config.depth + 1 : 1; while ( config.queue.length && !config.blocking ) { if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { config.queue.shift()(); } else { window.setTimeout( function(){ process( last ); }, 13 ); break; } } config.depth--; if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { done(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { if ( !hasOwn.call( window, key ) ) { continue; } config.pollution.push( key ); } } } function checkPollution( name ) { var old = config.pollution; saveGlobal(); var newGlobals = diff( config.pollution, old ); if ( newGlobals.length > 0 ) { ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); } var deletedGlobals = diff( old, config.pollution ); if ( deletedGlobals.length > 0 ) { ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); } } // returns a new Array with the elements that are in a but not in b function diff( a, b ) { var result = a.slice(); for ( var i = 0; i < result.length; i++ ) { for ( var j = 0; j < b.length; j++ ) { if ( result[i] === b[j] ) { result.splice(i, 1); i--; break; } } } return result; } function fail(message, exception, callback) { if ( typeof console !== "undefined" && console.error && console.warn ) { console.error(message); console.error(exception); console.error(exception.stack); console.warn(callback.toString()); } else if ( window.opera && opera.postError ) { opera.postError(message, exception, callback.toString); } } function extend(a, b) { for ( var prop in b ) { if ( b[prop] === undefined ) { delete a[prop]; // Avoid "Member not found" error in IE8 caused by setting window.constructor } else if ( prop !== "constructor" || a !== window ) { a[prop] = b[prop]; } } return a; } function addEvent(elem, type, fn) { if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, fn ); } else { fn(); } } function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById( name ); } function registerLoggingCallback(key){ return function(callback){ config[key].push( callback ); }; } // Supports deprecated method of completely overwriting logging callbacks function runLoggingCallbacks(key, scope, args) { //debugger; var callbacks; if ( QUnit.hasOwnProperty(key) ) { QUnit[key].call(scope, args); } else { callbacks = config[key]; for( var i = 0; i < callbacks.length; i++ ) { callbacks[i].call( scope, args ); } } } // Test for equality any JavaScript type. // Author: Philippe Rathé <prathe@gmail.com> QUnit.equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions var parents = []; // stack to avoiding loops from circular referencing // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = QUnit.objectType(o); if (prop) { if (QUnit.objectType(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var getProto = Object.getPrototypeOf || function (obj) { return obj.__proto__; }; var callbacks = function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a // declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string" : useStrictEquality, "boolean" : useStrictEquality, "number" : useStrictEquality, "null" : useStrictEquality, "undefined" : useStrictEquality, "nan" : function(b) { return isNaN(b); }, "date" : function(b, a) { return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp" : function(b, a) { return QUnit.objectType(b) === "regexp" && a.source === b.source && // the regex itself a.global === b.global && // and its modifers // (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function" : function() { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array" : function(b, a) { var i, j, loop; var len; // b could be an object literal here if (!(QUnit.objectType(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } // track reference to avoid circular references parents.push(a); for (i = 0; i < len; i++) { loop = false; for (j = 0; j < parents.length; j++) { if (parents[j] === a[i]) { loop = true;// dont rewalk array } } if (!loop && !innerEquiv(a[i], b[i])) { parents.pop(); return false; } } parents.pop(); return true; }, "object" : function(b, a) { var i, j, loop; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of // strings // comparing constructors is more strict than using // instanceof if (a.constructor !== b.constructor) { // Allow objects with no prototype to be equivalent to // objects with Object as their constructor. if (!((getProto(a) === null && getProto(b) === Object.prototype) || (getProto(b) === null && getProto(a) === Object.prototype))) { return false; } } // stack constructor before traversing properties callers.push(a.constructor); // track reference to avoid circular references parents.push(a); for (i in a) { // be strict: don't ensures hasOwnProperty // and go deep loop = false; for (j = 0; j < parents.length; j++) { if (parents[j] === a[i]) loop = true; // don't go down the same path // twice } aProperties.push(i); // collect a's properties if (!loop && !innerEquiv(a[i], b[i])) { eq = false; break; } } callers.pop(); // unstack, we are done parents.pop(); for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties .sort()); } }; }(); innerEquiv = function() { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function(a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType(a) !== QUnit.objectType(b)) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [ b, a ]); } // apply transition with (1..n) arguments })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length - 1)); }; return innerEquiv; }(); /** * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | * http://flesler.blogspot.com Licensed under BSD * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 * * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */ QUnit.jsDump = (function() { function quote( str ) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; }; function literal( o ) { return o + ''; }; function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) arr = arr.join( ',' + s + inner ); if ( !arr ) return pre + post; return [ pre, inner + arr, base + post ].join(s); }; function array( arr, stack ) { var i = arr.length, ret = Array(i); this.up(); while ( i-- ) ret[i] = this.parse( arr[i] , undefined , stack); this.down(); return join( '[', ret, ']' ); }; var reName = /^function (\w+)/; var jsDump = { parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance stack = stack || [ ]; var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; var inStack = inArray(obj, stack); if (inStack != -1) { return 'recursion('+(inStack - stack.length)+')'; } //else if (type == 'function') { stack.push(obj); var res = parser.call( this, obj, stack ); stack.pop(); return res; } // else return (type == 'string') ? parser : this.parsers.error; }, typeOf:function( obj ) { var type; if ( obj === null ) { type = "null"; } else if (typeof obj === "undefined") { type = "undefined"; } else if (QUnit.is("RegExp", obj)) { type = "regexp"; } else if (QUnit.is("Date", obj)) { type = "date"; } else if (QUnit.is("Function", obj)) { type = "function"; } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") { type = "window"; } else if (obj.nodeType === 9) { type = "document"; } else if (obj.nodeType) { type = "node"; } else if ( // native arrays toString.call( obj ) === "[object Array]" || // NodeList objects ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) ) { type = "array"; } else { type = typeof obj; } return type; }, separator:function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' '; }, indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing if ( !this.multiline ) return ''; var chr = this.indentChar; if ( this.HTML ) chr = chr.replace(/\t/g,' ').replace(/ /g,'&nbsp;'); return Array( this._depth_ + (extra||0) ).join(chr); }, up:function( a ) { this._depth_ += a || 1; }, down:function( a ) { this._depth_ -= a || 1; }, setParser:function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote:quote, literal:literal, join:join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers:{ window: '[Window]', document: '[Document]', error:'[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null':'null', 'undefined':'undefined', 'function':function( fn ) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE if ( name ) ret += ' ' + name; ret += '('; ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, arguments: array, object:function( map, stack ) { var ret = [ ]; QUnit.jsDump.up(); for ( var key in map ) { var val = map[key]; ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack)); } QUnit.jsDump.down(); return join( '{', ret, '}' ); }, node:function( node ) { var open = QUnit.jsDump.HTML ? '&lt;' : '<', close = QUnit.jsDump.HTML ? '&gt;' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in QUnit.jsDump.DOMAttrs ) { var val = node[QUnit.jsDump.DOMAttrs[a]]; if ( val ) ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' ); } return ret + close + open + '/' + tag + close; }, functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function var l = fn.length; if ( !l ) return ''; var args = Array(l); while ( l-- ) args[l] = String.fromCharCode(97+l);//97 is 'a' return ' ' + args.join(', ') + ' '; }, key:quote, //object calls it internally, the key part of an item in a map functionCode:'[code]', //function calls it internally, it's the content of the function attribute:quote, //node calls it internally, it's an html attribute value string:quote, date:quote, regexp:literal, //regex number:literal, 'boolean':literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:false,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump; })(); // from Sizzle.js function getText( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += getText( elem.childNodes ); } } return ret; }; //from jquery.js function inArray( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; } /* * Javascript Diff Algorithm * By John Resig (http://ejohn.org/) * Modified by Chu Alan "sprite" * * Released under the MIT license. * * More Info: * http://ejohn.org/projects/javascript-diff-algorithm/ * * Usage: QUnit.diff(expected, actual) * * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" */ QUnit.diff = (function() { function diff(o, n) { var ns = {}; var os = {}; for (var i = 0; i < n.length; i++) { if (ns[n[i]] == null) ns[n[i]] = { rows: [], o: null }; ns[n[i]].rows.push(i); } for (var i = 0; i < o.length; i++) { if (os[o[i]] == null) os[o[i]] = { rows: [], n: null }; os[o[i]].rows.push(i); } for (var i in ns) { if ( !hasOwn.call( ns, i ) ) { continue; } if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) { n[ns[i].rows[0]] = { text: n[ns[i].rows[0]], row: os[i].rows[0] }; o[os[i].rows[0]] = { text: o[os[i].rows[0]], row: ns[i].rows[0] }; } } for (var i = 0; i < n.length - 1; i++) { if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && n[i + 1] == o[n[i].row + 1]) { n[i + 1] = { text: n[i + 1], row: n[i].row + 1 }; o[n[i].row + 1] = { text: o[n[i].row + 1], row: i + 1 }; } } for (var i = n.length - 1; i > 0; i--) { if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null && n[i - 1] == o[n[i].row - 1]) { n[i - 1] = { text: n[i - 1], row: n[i].row - 1 }; o[n[i].row - 1] = { text: o[n[i].row - 1], row: i - 1 }; } } return { o: o, n: n }; } return function(o, n) { o = o.replace(/\s+$/, ''); n = n.replace(/\s+$/, ''); var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/)); var str = ""; var oSpace = o.match(/\s+/g); if (oSpace == null) { oSpace = [" "]; } else { oSpace.push(" "); } var nSpace = n.match(/\s+/g); if (nSpace == null) { nSpace = [" "]; } else { nSpace.push(" "); } if (out.n.length == 0) { for (var i = 0; i < out.o.length; i++) { str += '<del>' + out.o[i] + oSpace[i] + "</del>"; } } else { if (out.n[0].text == null) { for (n = 0; n < out.o.length && out.o[n].text == null; n++) { str += '<del>' + out.o[n] + oSpace[n] + "</del>"; } } for (var i = 0; i < out.n.length; i++) { if (out.n[i].text == null) { str += '<ins>' + out.n[i] + nSpace[i] + "</ins>"; } else { var pre = ""; for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) { pre += '<del>' + out.o[n] + oSpace[n] + "</del>"; } str += " " + out.n[i].text + nSpace[i] + pre; } } } return str; }; })(); })(this);
JavaScript
/*! Respond.js: min/max-width media query polyfill. Remote proxy (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */ (function(win, doc, undefined){ var docElem = doc.documentElement, proxyURL = doc.getElementById("respond-proxy").href, redirectURL = (doc.getElementById("respond-redirect") || location).href, baseElem = doc.getElementsByTagName("base")[0], urls = [], refNode; function encode(url){ return win.encodeURIComponent(url); } function fakejax( url, callback ){ var iframe, AXO; // All hail Google http://j.mp/iKMI19 // Behold, an iframe proxy without annoying clicky noises. if ( "ActiveXObject" in win ) { AXO = new ActiveXObject( "htmlfile" ); AXO.open(); AXO.write( '<iframe id="x"></iframe>' ); AXO.close(); iframe = AXO.getElementById( "x" ); } else { iframe = doc.createElement( "iframe" ); iframe.style.cssText = "position:absolute;top:-99em"; docElem.insertBefore(iframe, docElem.firstElementChild || docElem.firstChild ); } iframe.src = checkBaseURL(proxyURL) + "?url=" + encode(redirectURL) + "&css=" + encode(checkBaseURL(url)); function checkFrameName() { var cssText; try { cssText = iframe.contentWindow.name; } catch (e) { } if (cssText) { // We've got what we need. Stop the iframe from loading further content. iframe.src = "about:blank"; iframe.parentNode.removeChild(iframe); iframe = null; // Per http://j.mp/kn9EPh, not taking any chances. Flushing the ActiveXObject if (AXO) { AXO = null; if (win.CollectGarbage) { win.CollectGarbage(); } } callback(cssText); } else{ win.setTimeout(checkFrameName, 100); } } win.setTimeout(checkFrameName, 500); } function checkBaseURL(href) { if (baseElem && href.indexOf(baseElem.href) === -1) { bref = (/\/$/).test(baseElem.href) ? baseElem.href : (baseElem.href + "/"); href = bref + href; } return href; } function checkRedirectURL() { // IE6 & IE7 don't build out absolute urls in <link /> attributes. // So respond.proxy.gif remains relative instead of http://example.com/respond.proxy.gif. // This trickery resolves that issue. if (~ !redirectURL.indexOf(location.host)) { var fakeLink = doc.createElement("div"); fakeLink.innerHTML = '<a href="' + redirectURL + '"></a>'; docElem.insertBefore(fakeLink, docElem.firstElementChild || docElem.firstChild ); // Grab the parsed URL from that dummy object redirectURL = fakeLink.firstChild.href; // Clean up fakeLink.parentNode.removeChild(fakeLink); fakeLink = null; } } function buildUrls(){ var links = doc.getElementsByTagName( "link" ); for( var i = 0, linkl = links.length; i < linkl; i++ ){ var thislink = links[i], href = links[i].href, extreg = (/^([a-zA-Z]+?:(\/\/)?(www\.)?)/).test( href ), ext = (baseElem && !extreg) || extreg; //make sure it's an external stylesheet if( thislink.rel.indexOf( "stylesheet" ) >= 0 && ext ){ (function( link ){ fakejax( href, function( css ){ link.styleSheet.rawCssText = css; respond.update(); } ); })( thislink ); } } } if( !respond.mediaQueriesSupported ){ checkRedirectURL(); buildUrls(); } })( window, document );
JavaScript
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ /*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */ window.matchMedia = window.matchMedia || (function( doc, undefined ) { "use strict"; var bool, docElem = doc.documentElement, refNode = docElem.firstElementChild || docElem.firstChild, // fakeBody required for <FF4 when executed in <head> fakeBody = doc.createElement( "body" ), div = doc.createElement( "div" ); div.id = "mq-test-1"; div.style.cssText = "position:absolute;top:-100em"; fakeBody.style.background = "none"; fakeBody.appendChild(div); return function(q){ div.innerHTML = "&shy;<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>"; docElem.insertBefore( fakeBody, refNode ); bool = div.offsetWidth === 42; docElem.removeChild( fakeBody ); return { matches: bool, media: q }; }; }( document )); /*! Respond.js v1.1.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */ (function( win ){ "use strict"; //exposed namespace var respond = {}; win.respond = respond; //define update even in native-mq-supporting browsers, to avoid errors respond.update = function(){}; //expose media query support flag for external use respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches; //if media queries are supported, exit here if( respond.mediaQueriesSupported ){ return; } //define vars var doc = win.document, docElem = doc.documentElement, mediastyles = [], rules = [], appendedEls = [], parsedSheets = {}, resizeThrottle = 30, head = doc.getElementsByTagName( "head" )[0] || docElem, base = doc.getElementsByTagName( "base" )[0], links = head.getElementsByTagName( "link" ), requestQueue = [], //loop stylesheets, send text content to translate ripCSS = function(){ for( var i = 0; i < links.length; i++ ){ var sheet = links[ i ], href = sheet.href, media = sheet.media, isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet"; //only links plz and prevent re-parsing if( !!href && isCSS && !parsedSheets[ href ] ){ // selectivizr exposes css through the rawCssText expando if (sheet.styleSheet && sheet.styleSheet.rawCssText) { translate( sheet.styleSheet.rawCssText, href, media ); parsedSheets[ href ] = true; } else { if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base) || href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){ requestQueue.push( { href: href, media: media } ); } } } } makeRequests(); }, //recurse through request queue, get css text makeRequests = function(){ if( requestQueue.length ){ var thisRequest = requestQueue.shift(); ajax( thisRequest.href, function( styles ){ translate( styles, thisRequest.href, thisRequest.media ); parsedSheets[ thisRequest.href ] = true; // by wrapping recursive function call in setTimeout // we prevent "Stack overflow" error in IE7 win.setTimeout(function(){ makeRequests(); },0); } ); } }, //find media blocks in css text, convert to style blocks translate = function( styles, href, media ){ var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ), ql = qs && qs.length || 0; //try to get CSS path href = href.substring( 0, href.lastIndexOf( "/" ) ); var repUrls = function( css ){ return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" ); }, useMedia = !ql && media; //if path exists, tack on trailing slash if( href.length ){ href += "/"; } //if no internal queries exist, but media attr does, use that //note: this currently lacks support for situations where a media attr is specified on a link AND //its associated stylesheet has internal CSS media queries. //In those cases, the media attribute will currently be ignored. if( useMedia ){ ql = 1; } for( var i = 0; i < ql; i++ ){ var fullq, thisq, eachq, eql; //media attr if( useMedia ){ fullq = media; rules.push( repUrls( styles ) ); } //parse for styles else{ fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1; rules.push( RegExp.$2 && repUrls( RegExp.$2 ) ); } eachq = fullq.split( "," ); eql = eachq.length; for( var j = 0; j < eql; j++ ){ thisq = eachq[ j ]; mediastyles.push( { media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all", rules : rules.length - 1, hasquery : thisq.indexOf("(") > -1, minw : thisq.match( /\(\s*min\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ), maxw : thisq.match( /\(\s*max\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ) } ); } } applyMedia(); }, lastCall, resizeDefer, // returns the value of 1em in pixels getEmValue = function() { var ret, div = doc.createElement('div'), body = doc.body, fakeUsed = false; div.style.cssText = "position:absolute;font-size:1em;width:1em"; if( !body ){ body = fakeUsed = doc.createElement( "body" ); body.style.background = "none"; } body.appendChild( div ); docElem.insertBefore( body, docElem.firstChild ); ret = div.offsetWidth; if( fakeUsed ){ docElem.removeChild( body ); } else { body.removeChild( div ); } //also update eminpx before returning ret = eminpx = parseFloat(ret); return ret; }, //cached container for 1em value, populated the first time it's needed eminpx, //enable/disable styles applyMedia = function( fromResize ){ var name = "clientWidth", docElemProp = docElem[ name ], currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp, styleBlocks = {}, lastLink = links[ links.length-1 ], now = (new Date()).getTime(); //throttle resize calls if( fromResize && lastCall && now - lastCall < resizeThrottle ){ win.clearTimeout( resizeDefer ); resizeDefer = win.setTimeout( applyMedia, resizeThrottle ); return; } else { lastCall = now; } for( var i in mediastyles ){ if( mediastyles.hasOwnProperty( i ) ){ var thisstyle = mediastyles[ i ], min = thisstyle.minw, max = thisstyle.maxw, minnull = min === null, maxnull = max === null, em = "em"; if( !!min ){ min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); } if( !!max ){ max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); } // if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){ if( !styleBlocks[ thisstyle.media ] ){ styleBlocks[ thisstyle.media ] = []; } styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] ); } } } //remove any existing respond style element(s) for( var j in appendedEls ){ if( appendedEls.hasOwnProperty( j ) ){ if( appendedEls[ j ] && appendedEls[ j ].parentNode === head ){ head.removeChild( appendedEls[ j ] ); } } } //inject active styles, grouped by media type for( var k in styleBlocks ){ if( styleBlocks.hasOwnProperty( k ) ){ var ss = doc.createElement( "style" ), css = styleBlocks[ k ].join( "\n" ); ss.type = "text/css"; ss.media = k; //originally, ss was appended to a documentFragment and sheets were appended in bulk. //this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one! head.insertBefore( ss, lastLink.nextSibling ); if ( ss.styleSheet ){ ss.styleSheet.cssText = css; } else { ss.appendChild( doc.createTextNode( css ) ); } //push to appendedEls to track for later removal appendedEls.push( ss ); } } }, //tweaked Ajax functions from Quirksmode ajax = function( url, callback ) { var req = xmlHttp(); if (!req){ return; } req.open( "GET", url, true ); req.onreadystatechange = function () { if ( req.readyState !== 4 || req.status !== 200 && req.status !== 304 ){ return; } callback( req.responseText ); }; if ( req.readyState === 4 ){ return; } req.send( null ); }, //define ajax obj xmlHttp = (function() { var xmlhttpmethod = false; try { xmlhttpmethod = new win.XMLHttpRequest(); } catch( e ){ xmlhttpmethod = new win.ActiveXObject( "Microsoft.XMLHTTP" ); } return function(){ return xmlhttpmethod; }; })(); //translate CSS ripCSS(); //expose update for re-running respond later on respond.update = ripCSS; //adjust on resize function callMedia(){ applyMedia( true ); } if( win.addEventListener ){ win.addEventListener( "resize", callMedia, false ); } else if( win.attachEvent ){ win.attachEvent( "onresize", callMedia ); } })(this);
JavaScript
/* * jQuery Plugin: Tokenizing Autocomplete Text Entry * Version 1.6.0 * * Copyright (c) 2009 James Smith (http://loopj.com) * Licensed jointly under the GPL and MIT licenses, * choose which one suits your project best! * */ (function ($) { // Default settings var DEFAULT_SETTINGS = { // Search settings method: "POST", contentType: "json", queryParam: "q", searchDelay: 300, minChars: 1, propertyToSearch: "name", jsonContainer: null, // Display settings hintText: "Type in a search term", noResultsText: "No results", searchingText: "Searching...", deleteText: "&times;", animateDropdown: true, // Tokenization settings tokenLimit: null, tokenDelimiter: ",", preventDuplicates: false, // Output settings tokenValue: "id", // Prepopulation settings prePopulate: null, processPrePopulate: false, // Manipulation settings idPrefix: "token-input-", // Formatters resultsFormatter: function(item){ return "<li>" + item[this.propertyToSearch]+ "</li>" }, tokenFormatter: function(item) { return "<li><p>" + item[this.propertyToSearch] + "</p></li>" }, // Callbacks onResult: null, onAdd: null, onDelete: null, onReady: null }; // Default classes to use when theming var DEFAULT_CLASSES = { tokenList: "token-input-list", token: "token-input-token", tokenDelete: "token-input-delete-token", selectedToken: "token-input-selected-token", highlightedToken: "token-input-highlighted-token", dropdown: "token-input-dropdown", dropdownItem: "token-input-dropdown-item", dropdownItem2: "token-input-dropdown-item2", selectedDropdownItem: "token-input-selected-dropdown-item", inputToken: "token-input-input-token" }; // Input box position "enum" var POSITION = { BEFORE: 0, AFTER: 1, END: 2 }; // Keys "enum" var KEY = { BACKSPACE: 8, TAB: 9, ENTER: 13, ESCAPE: 27, SPACE: 32, PAGE_UP: 33, PAGE_DOWN: 34, END: 35, HOME: 36, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, NUMPAD_ENTER: 108, COMMA: 188 }; // Additional public (exposed) methods var methods = { init: function(url_or_data_or_function, options) { var settings = $.extend({}, DEFAULT_SETTINGS, options || {}); return this.each(function () { $(this).data("tokenInputObject", new $.TokenList(this, url_or_data_or_function, settings)); }); }, clear: function() { this.data("tokenInputObject").clear(); return this; }, add: function(item) { this.data("tokenInputObject").add(item); return this; }, remove: function(item) { this.data("tokenInputObject").remove(item); return this; }, get: function() { return this.data("tokenInputObject").getTokens(); } } // Expose the .tokenInput function to jQuery as a plugin $.fn.tokenInput = function (method) { // Method calling and initialization logic if(methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else { return methods.init.apply(this, arguments); } }; // TokenList class for each input $.TokenList = function (input, url_or_data, settings) { // // Initialization // // Configure the data source if($.type(url_or_data) === "string" || $.type(url_or_data) === "function") { // Set the url to query against settings.url = url_or_data; // If the URL is a function, evaluate it here to do our initalization work var url = computeURL(); // Make a smart guess about cross-domain if it wasn't explicitly specified if(settings.crossDomain === undefined) { if(url.indexOf("://") === -1) { settings.crossDomain = false; } else { settings.crossDomain = (location.href.split(/\/+/g)[1] !== url.split(/\/+/g)[1]); } } } else if(typeof(url_or_data) === "object") { // Set the local data to search through settings.local_data = url_or_data; } // Build class names if(settings.classes) { // Use custom class names settings.classes = $.extend({}, DEFAULT_CLASSES, settings.classes); } else if(settings.theme) { // Use theme-suffixed default class names settings.classes = {}; $.each(DEFAULT_CLASSES, function(key, value) { settings.classes[key] = value + "-" + settings.theme; }); } else { settings.classes = DEFAULT_CLASSES; } // Save the tokens var saved_tokens = []; // Keep track of the number of tokens in the list var token_count = 0; // Basic cache to save on db hits var cache = new $.TokenList.Cache(); // Keep track of the timeout, old vals var timeout; var input_val; // Create a new text input an attach keyup events var input_box = $("<input type=\"text\" autocomplete=\"off\">") .css({ outline: "none" }) .attr("id", settings.idPrefix + input.id) .focus(function () { if (settings.tokenLimit === null || settings.tokenLimit !== token_count) { show_dropdown_hint(); } }) .blur(function () { hide_dropdown(); $(this).val(""); }) .bind("keyup keydown blur update", resize_input) .keydown(function (event) { var previous_token; var next_token; switch(event.keyCode) { case KEY.LEFT: case KEY.RIGHT: case KEY.UP: case KEY.DOWN: if(!$(this).val()) { previous_token = input_token.prev(); next_token = input_token.next(); if((previous_token.length && previous_token.get(0) === selected_token) || (next_token.length && next_token.get(0) === selected_token)) { // Check if there is a previous/next token and it is selected if(event.keyCode === KEY.LEFT || event.keyCode === KEY.UP) { deselect_token($(selected_token), POSITION.BEFORE); } else { deselect_token($(selected_token), POSITION.AFTER); } } else if((event.keyCode === KEY.LEFT || event.keyCode === KEY.UP) && previous_token.length) { // We are moving left, select the previous token if it exists select_token($(previous_token.get(0))); } else if((event.keyCode === KEY.RIGHT || event.keyCode === KEY.DOWN) && next_token.length) { // We are moving right, select the next token if it exists select_token($(next_token.get(0))); } } else { var dropdown_item = null; if(event.keyCode === KEY.DOWN || event.keyCode === KEY.RIGHT) { dropdown_item = $(selected_dropdown_item).next(); } else { dropdown_item = $(selected_dropdown_item).prev(); } if(dropdown_item.length) { select_dropdown_item(dropdown_item); } return false; } break; case KEY.BACKSPACE: previous_token = input_token.prev(); if(!$(this).val().length) { if(selected_token) { delete_token($(selected_token)); hidden_input.change(); } else if(previous_token.length) { select_token($(previous_token.get(0))); } return false; } else if($(this).val().length === 1) { hide_dropdown(); } else { // set a timeout just long enough to let this function finish. setTimeout(function(){do_search();}, 5); } break; case KEY.TAB: case KEY.ENTER: case KEY.NUMPAD_ENTER: case KEY.COMMA: if(selected_dropdown_item) { add_token($(selected_dropdown_item).data("tokeninput")); hidden_input.change(); return false; } break; case KEY.ESCAPE: hide_dropdown(); return true; default: if(String.fromCharCode(event.which)) { // set a timeout just long enough to let this function finish. setTimeout(function(){do_search();}, 5); } break; } }); // Keep a reference to the original input box var hidden_input = $(input) .hide() .val("") .focus(function () { input_box.focus(); }) .blur(function () { input_box.blur(); }); // Keep a reference to the selected token and dropdown item var selected_token = null; var selected_token_index = 0; var selected_dropdown_item = null; // The list to store the token items in var token_list = $("<ul />") .addClass(settings.classes.tokenList) .click(function (event) { var li = $(event.target).closest("li"); if(li && li.get(0) && $.data(li.get(0), "tokeninput")) { toggle_select_token(li); } else { // Deselect selected token if(selected_token) { deselect_token($(selected_token), POSITION.END); } // Focus input box input_box.focus(); } }) .mouseover(function (event) { var li = $(event.target).closest("li"); if(li && selected_token !== this) { li.addClass(settings.classes.highlightedToken); } }) .mouseout(function (event) { var li = $(event.target).closest("li"); if(li && selected_token !== this) { li.removeClass(settings.classes.highlightedToken); } }) .insertBefore(hidden_input); // The token holding the input box var input_token = $("<li />") .addClass(settings.classes.inputToken) .appendTo(token_list) .append(input_box); // The list to store the dropdown items in var dropdown = $("<div>") .addClass(settings.classes.dropdown) .appendTo("body") .hide(); // Magic element to help us resize the text input var input_resizer = $("<tester/>") .insertAfter(input_box) .css({ position: "absolute", top: -9999, left: -9999, width: "auto", fontSize: input_box.css("fontSize"), fontFamily: input_box.css("fontFamily"), fontWeight: input_box.css("fontWeight"), letterSpacing: input_box.css("letterSpacing"), whiteSpace: "nowrap" }); // Pre-populate list if items exist hidden_input.val(""); var li_data = settings.prePopulate || hidden_input.data("pre"); if(settings.processPrePopulate && $.isFunction(settings.onResult)) { li_data = settings.onResult.call(hidden_input, li_data); } if(li_data && li_data.length) { $.each(li_data, function (index, value) { insert_token(value); checkTokenLimit(); }); } // Initialization is done if($.isFunction(settings.onReady)) { settings.onReady.call(); } // // Public functions // this.clear = function() { token_list.children("li").each(function() { if ($(this).children("input").length === 0) { delete_token($(this)); } }); } this.add = function(item) { add_token(item); } this.remove = function(item) { token_list.children("li").each(function() { if ($(this).children("input").length === 0) { var currToken = $(this).data("tokeninput"); var match = true; for (var prop in item) { if (item[prop] !== currToken[prop]) { match = false; break; } } if (match) { delete_token($(this)); } } }); } this.getTokens = function() { return saved_tokens; } // // Private functions // function checkTokenLimit() { if(settings.tokenLimit !== null && token_count >= settings.tokenLimit) { input_box.hide(); hide_dropdown(); return; } } function resize_input() { if(input_val === (input_val = input_box.val())) {return;} // Enter new content into resizer and resize input accordingly var escaped = input_val.replace(/&/g, '&amp;').replace(/\s/g,' ').replace(/</g, '&lt;').replace(/>/g, '&gt;'); input_resizer.html(escaped); input_box.width(input_resizer.width() + 30); } function is_printable_character(keycode) { return ((keycode >= 48 && keycode <= 90) || // 0-1a-z (keycode >= 96 && keycode <= 111) || // numpad 0-9 + - / * . (keycode >= 186 && keycode <= 192) || // ; = , - . / ^ (keycode >= 219 && keycode <= 222)); // ( \ ) ' } // Inner function to a token to the list function insert_token(item) { var this_token = settings.tokenFormatter(item); this_token = $(this_token) .addClass(settings.classes.token) .insertBefore(input_token); // The 'delete token' button $("<span>" + settings.deleteText + "</span>") .addClass(settings.classes.tokenDelete) .appendTo(this_token) .click(function () { delete_token($(this).parent()); hidden_input.change(); return false; }); // Store data on the token var token_data = {"id": item.id}; token_data[settings.propertyToSearch] = item[settings.propertyToSearch]; $.data(this_token.get(0), "tokeninput", item); // Save this token for duplicate checking saved_tokens = saved_tokens.slice(0,selected_token_index).concat([token_data]).concat(saved_tokens.slice(selected_token_index)); selected_token_index++; // Update the hidden input update_hidden_input(saved_tokens, hidden_input); token_count += 1; // Check the token limit if(settings.tokenLimit !== null && token_count >= settings.tokenLimit) { input_box.hide(); hide_dropdown(); } return this_token; } // Add a token to the token list based on user input function add_token (item) { var callback = settings.onAdd; // See if the token already exists and select it if we don't want duplicates if(token_count > 0 && settings.preventDuplicates) { var found_existing_token = null; token_list.children().each(function () { var existing_token = $(this); var existing_data = $.data(existing_token.get(0), "tokeninput"); if(existing_data && existing_data.id === item.id) { found_existing_token = existing_token; return false; } }); if(found_existing_token) { select_token(found_existing_token); input_token.insertAfter(found_existing_token); input_box.focus(); return; } } // Insert the new tokens if(settings.tokenLimit == null || token_count < settings.tokenLimit) { insert_token(item); checkTokenLimit(); } // Clear input box input_box.val(""); // Don't show the help dropdown, they've got the idea hide_dropdown(); // Execute the onAdd callback if defined if($.isFunction(callback)) { callback.call(hidden_input,item); } } // Select a token in the token list function select_token (token) { token.addClass(settings.classes.selectedToken); selected_token = token.get(0); // Hide input box input_box.val(""); // Hide dropdown if it is visible (eg if we clicked to select token) hide_dropdown(); } // Deselect a token in the token list function deselect_token (token, position) { token.removeClass(settings.classes.selectedToken); selected_token = null; if(position === POSITION.BEFORE) { input_token.insertBefore(token); selected_token_index--; } else if(position === POSITION.AFTER) { input_token.insertAfter(token); selected_token_index++; } else { input_token.appendTo(token_list); selected_token_index = token_count; } // Show the input box and give it focus again input_box.focus(); } // Toggle selection of a token in the token list function toggle_select_token(token) { var previous_selected_token = selected_token; if(selected_token) { deselect_token($(selected_token), POSITION.END); } if(previous_selected_token === token.get(0)) { deselect_token(token, POSITION.END); } else { select_token(token); } } // Delete a token from the token list function delete_token (token) { // Remove the id from the saved list var token_data = $.data(token.get(0), "tokeninput"); var callback = settings.onDelete; var index = token.prevAll().length; if(index > selected_token_index) index--; // Delete the token token.remove(); selected_token = null; // Show the input box and give it focus again input_box.focus(); // Remove this token from the saved list saved_tokens = saved_tokens.slice(0,index).concat(saved_tokens.slice(index+1)); if(index < selected_token_index) selected_token_index--; // Update the hidden input update_hidden_input(saved_tokens, hidden_input); token_count -= 1; if(settings.tokenLimit !== null) { input_box .show() .val("") .focus(); } // Execute the onDelete callback if defined if($.isFunction(callback)) { callback.call(hidden_input,token_data); } } // Update the hidden input box value function update_hidden_input(saved_tokens, hidden_input) { var token_values = $.map(saved_tokens, function (el) { return el[settings.tokenValue]; }); hidden_input.val(token_values.join(settings.tokenDelimiter)); } // Hide and clear the results dropdown function hide_dropdown () { dropdown.hide().empty(); selected_dropdown_item = null; } function show_dropdown() { dropdown .css({ position: "absolute", top: $(token_list).offset().top + $(token_list).outerHeight(), left: $(token_list).offset().left, zindex: 999 }) .show(); } function show_dropdown_searching () { if(settings.searchingText) { dropdown.html("<p>"+settings.searchingText+"</p>"); show_dropdown(); } } function show_dropdown_hint () { if(settings.hintText) { dropdown.html("<p>"+settings.hintText+"</p>"); show_dropdown(); } } // Highlight the query part of the search term function highlight_term(value, term) { return value;//.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<b>$1</b>"); } function find_value_and_highlight_term(template, value, term) { return template;//.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + value + ")(?![^<>]*>)(?![^&;]+;)", "g"), highlight_term(value, term)); } // Populate the results dropdown with some results function populate_dropdown (query, results) { if(results && results.length) { dropdown.empty(); var dropdown_ul = $("<ul>") .appendTo(dropdown) .mouseover(function (event) { select_dropdown_item($(event.target).closest("li")); }) .mousedown(function (event) { add_token($(event.target).closest("li").data("tokeninput")); hidden_input.change(); return false; }) .hide(); $.each(results, function(index, value) { var this_li = settings.resultsFormatter(value); this_li = find_value_and_highlight_term(this_li ,value[settings.propertyToSearch], query); this_li = $(this_li).appendTo(dropdown_ul); if(index % 2) { this_li.addClass(settings.classes.dropdownItem); } else { this_li.addClass(settings.classes.dropdownItem2); } if(index === 0) { select_dropdown_item(this_li); } $.data(this_li.get(0), "tokeninput", value); }); show_dropdown(); if(settings.animateDropdown) { dropdown_ul.slideDown("fast"); } else { dropdown_ul.show(); } } else { if(settings.noResultsText) { dropdown.html("<p>"+settings.noResultsText+"</p>"); show_dropdown(); } } } // Highlight an item in the results dropdown function select_dropdown_item (item) { if(item) { if(selected_dropdown_item) { deselect_dropdown_item($(selected_dropdown_item)); } item.addClass(settings.classes.selectedDropdownItem); selected_dropdown_item = item.get(0); } } // Remove highlighting from an item in the results dropdown function deselect_dropdown_item (item) { item.removeClass(settings.classes.selectedDropdownItem); selected_dropdown_item = null; } // Do a search and show the "searching" dropdown if the input is longer // than settings.minChars function do_search() { var query = input_box.val().toLowerCase(); if(query && query.length) { if(selected_token) { deselect_token($(selected_token), POSITION.AFTER); } if(query.length >= settings.minChars) { show_dropdown_searching(); clearTimeout(timeout); timeout = setTimeout(function(){ run_search(query); }, settings.searchDelay); } else { hide_dropdown(); } } } // Do the actual search function run_search(query) { var cache_key = query + computeURL(); var cached_results = cache.get(cache_key); if(cached_results) { populate_dropdown(query, cached_results); } else { // Are we doing an ajax search or local data search? if(settings.url) { var url = computeURL(); // Extract exisiting get params var ajax_params = {}; ajax_params.data = {}; if(url.indexOf("?") > -1) { var parts = url.split("?"); ajax_params.url = parts[0]; var param_array = parts[1].split("&"); $.each(param_array, function (index, value) { var kv = value.split("="); ajax_params.data[kv[0]] = kv[1]; }); } else { ajax_params.url = url; } // Prepare the request ajax_params.data[settings.queryParam] = query; ajax_params.type = settings.method; ajax_params.dataType = settings.contentType; if(settings.crossDomain) { ajax_params.dataType = "jsonp"; } // Attach the success callback ajax_params.success = function(results) { if($.isFunction(settings.onResult)) { results = settings.onResult.call(hidden_input, results); } cache.add(cache_key, settings.jsonContainer ? results[settings.jsonContainer] : results); // only populate the dropdown if the results are associated with the active search query if(input_box.val().toLowerCase() === query) { populate_dropdown(query, settings.jsonContainer ? results[settings.jsonContainer] : results); } }; // Make the request $.ajax(ajax_params); } else if(settings.local_data) { // Do the search through local data var results = $.grep(settings.local_data, function (row) { return row[settings.propertyToSearch].toLowerCase().indexOf(query.toLowerCase()) > -1; }); if($.isFunction(settings.onResult)) { results = settings.onResult.call(hidden_input, results); } cache.add(cache_key, results); populate_dropdown(query, results); } } } // compute the dynamic URL function computeURL() { var url = settings.url; if(typeof settings.url == 'function') { url = settings.url.call(); } return url; } }; // Really basic cache for the results $.TokenList.Cache = function (options) { var settings = $.extend({ max_size: 500 }, options); var data = {}; var size = 0; var flush = function () { data = {}; size = 0; }; this.add = function (query, results) { if(size > settings.max_size) { flush(); } if(!data[query]) { size += 1; } data[query] = results; }; this.get = function (query) { return data[query]; }; }; }(jQuery));
JavaScript
/*! * jQuery Cycle Plugin (with Transition Definitions) * Examples and documentation at: http://jquery.malsup.com/cycle/ * Copyright (c) 2007-2013 M. Alsup * Version: 3.0.2 (19-APR-2013) * Dual licensed under the MIT and GPL licenses. * http://jquery.malsup.com/license.html * Requires: jQuery v1.7.1 or later */ ;(function($, undefined) { "use strict"; var ver = '3.0.2'; function debug(s) { if ($.fn.cycle.debug) log(s); } function log() { if (window.console && console.log) console.log('[cycle] ' + Array.prototype.join.call(arguments,' ')); } $.expr[':'].paused = function(el) { return el.cyclePause; }; // the options arg can be... // a number - indicates an immediate transition should occur to the given slide index // a string - 'pause', 'resume', 'toggle', 'next', 'prev', 'stop', 'destroy' or the name of a transition effect (ie, 'fade', 'zoom', etc) // an object - properties to control the slideshow // // the arg2 arg can be... // the name of an fx (only used in conjunction with a numeric value for 'options') // the value true (only used in first arg == 'resume') and indicates // that the resume should occur immediately (not wait for next timeout) $.fn.cycle = function(options, arg2) { var o = { s: this.selector, c: this.context }; // in 1.3+ we can fix mistakes with the ready state if (this.length === 0 && options != 'stop') { if (!$.isReady && o.s) { log('DOM not ready, queuing slideshow'); $(function() { $(o.s,o.c).cycle(options,arg2); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } // iterate the matched nodeset return this.each(function() { var opts = handleArguments(this, options, arg2); if (opts === false) return; opts.updateActivePagerLink = opts.updateActivePagerLink || $.fn.cycle.updateActivePagerLink; // stop existing slideshow for this container (if there is one) if (this.cycleTimeout) clearTimeout(this.cycleTimeout); this.cycleTimeout = this.cyclePause = 0; this.cycleStop = 0; // issue #108 var $cont = $(this); var $slides = opts.slideExpr ? $(opts.slideExpr, this) : $cont.children(); var els = $slides.get(); if (els.length < 2) { log('terminating; too few slides: ' + els.length); return; } var opts2 = buildOptions($cont, $slides, els, opts, o); if (opts2 === false) return; var startTime = opts2.continuous ? 10 : getTimeout(els[opts2.currSlide], els[opts2.nextSlide], opts2, !opts2.backwards); // if it's an auto slideshow, kick it off if (startTime) { startTime += (opts2.delay || 0); if (startTime < 10) startTime = 10; debug('first timeout: ' + startTime); this.cycleTimeout = setTimeout(function(){go(els,opts2,0,!opts.backwards);}, startTime); } }); }; function triggerPause(cont, byHover, onPager) { var opts = $(cont).data('cycle.opts'); if (!opts) return; var paused = !!cont.cyclePause; if (paused && opts.paused) opts.paused(cont, opts, byHover, onPager); else if (!paused && opts.resumed) opts.resumed(cont, opts, byHover, onPager); } // process the args that were passed to the plugin fn function handleArguments(cont, options, arg2) { if (cont.cycleStop === undefined) cont.cycleStop = 0; if (options === undefined || options === null) options = {}; if (options.constructor == String) { switch(options) { case 'destroy': case 'stop': var opts = $(cont).data('cycle.opts'); if (!opts) return false; cont.cycleStop++; // callbacks look for change if (cont.cycleTimeout) clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; if (opts.elements) $(opts.elements).stop(); $(cont).removeData('cycle.opts'); if (options == 'destroy') destroy(cont, opts); return false; case 'toggle': cont.cyclePause = (cont.cyclePause === 1) ? 0 : 1; checkInstantResume(cont.cyclePause, arg2, cont); triggerPause(cont); return false; case 'pause': cont.cyclePause = 1; triggerPause(cont); return false; case 'resume': cont.cyclePause = 0; checkInstantResume(false, arg2, cont); triggerPause(cont); return false; case 'prev': case 'next': opts = $(cont).data('cycle.opts'); if (!opts) { log('options not found, "prev/next" ignored'); return false; } if (typeof arg2 == 'string') opts.oneTimeFx = arg2; $.fn.cycle[options](opts); return false; default: options = { fx: options }; } return options; } else if (options.constructor == Number) { // go to the requested slide var num = options; options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not advance slide'); return false; } if (num < 0 || num >= options.elements.length) { log('invalid slide index: ' + num); return false; } options.nextSlide = num; if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } if (typeof arg2 == 'string') options.oneTimeFx = arg2; go(options.elements, options, 1, num >= options.currSlide); return false; } return options; function checkInstantResume(isPaused, arg2, cont) { if (!isPaused && arg2 === true) { // resume now! var options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not resume'); return false; } if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } go(options.elements, options, 1, !options.backwards); } } } function removeFilter(el, opts) { if (!$.support.opacity && opts.cleartype && el.style.filter) { try { el.style.removeAttribute('filter'); } catch(smother) {} // handle old opera versions } } // unbind event handlers function destroy(cont, opts) { if (opts.next) $(opts.next).unbind(opts.prevNextEvent); if (opts.prev) $(opts.prev).unbind(opts.prevNextEvent); if (opts.pager || opts.pagerAnchorBuilder) $.each(opts.pagerAnchors || [], function() { this.unbind().remove(); }); opts.pagerAnchors = null; $(cont).unbind('mouseenter.cycle mouseleave.cycle'); if (opts.destroy) // callback opts.destroy(opts); } // one-time initialization function buildOptions($cont, $slides, els, options, o) { var startingSlideSpecified; // support metadata plugin (v1.0 and v2.0) var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {}); var meta = $.isFunction($cont.data) ? $cont.data(opts.metaAttr) : null; if (meta) opts = $.extend(opts, meta); if (opts.autostop) opts.countdown = opts.autostopCount || els.length; var cont = $cont[0]; $cont.data('cycle.opts', opts); opts.$cont = $cont; opts.stopCount = cont.cycleStop; opts.elements = els; opts.before = opts.before ? [opts.before] : []; opts.after = opts.after ? [opts.after] : []; // push some after callbacks if (!$.support.opacity && opts.cleartype) opts.after.push(function() { removeFilter(this, opts); }); if (opts.continuous) opts.after.push(function() { go(els,opts,0,!opts.backwards); }); saveOriginalOpts(opts); // clearType corrections if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($slides); // container requires non-static position so that slides can be position within if ($cont.css('position') == 'static') $cont.css('position', 'relative'); if (opts.width) $cont.width(opts.width); if (opts.height && opts.height != 'auto') $cont.height(opts.height); if (opts.startingSlide !== undefined) { opts.startingSlide = parseInt(opts.startingSlide,10); if (opts.startingSlide >= els.length || opts.startSlide < 0) opts.startingSlide = 0; // catch bogus input else startingSlideSpecified = true; } else if (opts.backwards) opts.startingSlide = els.length - 1; else opts.startingSlide = 0; // if random, mix up the slide array if (opts.random) { opts.randomMap = []; for (var i = 0; i < els.length; i++) opts.randomMap.push(i); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); if (startingSlideSpecified) { // try to find the specified starting slide and if found set start slide index in the map accordingly for ( var cnt = 0; cnt < els.length; cnt++ ) { if ( opts.startingSlide == opts.randomMap[cnt] ) { opts.randomIndex = cnt; } } } else { opts.randomIndex = 1; opts.startingSlide = opts.randomMap[1]; } } else if (opts.startingSlide >= els.length) opts.startingSlide = 0; // catch bogus input opts.currSlide = opts.startingSlide || 0; var first = opts.startingSlide; // set position and zIndex on all the slides $slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) { var z; if (opts.backwards) z = first ? i <= first ? els.length + (i-first) : first-i : els.length-i; else z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i; $(this).css('z-index', z); }); // make sure first slide is visible $(els[first]).css('opacity',1).show(); // opacity bit needed to handle restart use case removeFilter(els[first], opts); // stretch slides if (opts.fit) { if (!opts.aspect) { if (opts.width) $slides.width(opts.width); if (opts.height && opts.height != 'auto') $slides.height(opts.height); } else { $slides.each(function(){ var $slide = $(this); var ratio = (opts.aspect === true) ? $slide.width()/$slide.height() : opts.aspect; if( opts.width && $slide.width() != opts.width ) { $slide.width( opts.width ); $slide.height( opts.width / ratio ); } if( opts.height && $slide.height() < opts.height ) { $slide.height( opts.height ); $slide.width( opts.height * ratio ); } }); } } if (opts.center && ((!opts.fit) || opts.aspect)) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } if (opts.center && !opts.fit && !opts.slideResize) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } // stretch container var reshape = (opts.containerResize || opts.containerResizeHeight) && $cont.innerHeight() < 1; if (reshape) { // do this only if container has no size http://tinyurl.com/da2oa9 var maxw = 0, maxh = 0; for(var j=0; j < els.length; j++) { var $e = $(els[j]), e = $e[0], w = $e.outerWidth(), h = $e.outerHeight(); if (!w) w = e.offsetWidth || e.width || $e.attr('width'); if (!h) h = e.offsetHeight || e.height || $e.attr('height'); maxw = w > maxw ? w : maxw; maxh = h > maxh ? h : maxh; } if (opts.containerResize && maxw > 0 && maxh > 0) $cont.css({width:maxw+'px',height:maxh+'px'}); if (opts.containerResizeHeight && maxh > 0) $cont.css({height:maxh+'px'}); } var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pause) $cont.bind('mouseenter.cycle', function(){ pauseFlag = true; this.cyclePause++; triggerPause(cont, true); }).bind('mouseleave.cycle', function(){ if (pauseFlag) this.cyclePause--; triggerPause(cont, true); }); if (supportMultiTransitions(opts) === false) return false; // apparently a lot of people use image slideshows without height/width attributes on the images. // Cycle 2.50+ requires the sizing info for every slide; this block tries to deal with that. var requeue = false; options.requeueAttempts = options.requeueAttempts || 0; $slides.each(function() { // try to get height/width of each slide var $el = $(this); this.cycleH = (opts.fit && opts.height) ? opts.height : ($el.height() || this.offsetHeight || this.height || $el.attr('height') || 0); this.cycleW = (opts.fit && opts.width) ? opts.width : ($el.width() || this.offsetWidth || this.width || $el.attr('width') || 0); if ( $el.is('img') ) { var loading = (this.cycleH === 0 && this.cycleW === 0 && !this.complete); // don't requeue for images that are still loading but have a valid size if (loading) { if (o.s && opts.requeueOnImageNotLoaded && ++options.requeueAttempts < 100) { // track retry count so we don't loop forever log(options.requeueAttempts,' - img slide not loaded, requeuing slideshow: ', this.src, this.cycleW, this.cycleH); setTimeout(function() {$(o.s,o.c).cycle(options);}, opts.requeueTimeout); requeue = true; return false; // break each loop } else { log('could not determine size of image: '+this.src, this.cycleW, this.cycleH); } } } return true; }); if (requeue) return false; opts.cssBefore = opts.cssBefore || {}; opts.cssAfter = opts.cssAfter || {}; opts.cssFirst = opts.cssFirst || {}; opts.animIn = opts.animIn || {}; opts.animOut = opts.animOut || {}; $slides.not(':eq('+first+')').css(opts.cssBefore); $($slides[first]).css(opts.cssFirst); if (opts.timeout) { opts.timeout = parseInt(opts.timeout,10); // ensure that timeout and speed settings are sane if (opts.speed.constructor == String) opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed,10); if (!opts.sync) opts.speed = opts.speed / 2; var buffer = opts.fx == 'none' ? 0 : opts.fx == 'shuffle' ? 500 : 250; while((opts.timeout - opts.speed) < buffer) // sanitize timeout opts.timeout += opts.speed; } if (opts.easing) opts.easeIn = opts.easeOut = opts.easing; if (!opts.speedIn) opts.speedIn = opts.speed; if (!opts.speedOut) opts.speedOut = opts.speed; opts.slideCount = els.length; opts.currSlide = opts.lastSlide = first; if (opts.random) { if (++opts.randomIndex == els.length) opts.randomIndex = 0; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.backwards) opts.nextSlide = opts.startingSlide === 0 ? (els.length-1) : opts.startingSlide-1; else opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1; // run transition init fn if (!opts.multiFx) { var init = $.fn.cycle.transitions[opts.fx]; if ($.isFunction(init)) init($cont, $slides, opts); else if (opts.fx != 'custom' && !opts.multiFx) { log('unknown transition: ' + opts.fx,'; slideshow terminating'); return false; } } // fire artificial events var e0 = $slides[first]; if (!opts.skipInitializationCallbacks) { if (opts.before.length) opts.before[0].apply(e0, [e0, e0, opts, true]); if (opts.after.length) opts.after[0].apply(e0, [e0, e0, opts, true]); } if (opts.next) $(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,1);}); if (opts.prev) $(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,0);}); if (opts.pager || opts.pagerAnchorBuilder) buildPager(els,opts); exposeAddSlide(opts, els); return opts; } // save off original opts so we can restore after clearing state function saveOriginalOpts(opts) { opts.original = { before: [], after: [] }; opts.original.cssBefore = $.extend({}, opts.cssBefore); opts.original.cssAfter = $.extend({}, opts.cssAfter); opts.original.animIn = $.extend({}, opts.animIn); opts.original.animOut = $.extend({}, opts.animOut); $.each(opts.before, function() { opts.original.before.push(this); }); $.each(opts.after, function() { opts.original.after.push(this); }); } function supportMultiTransitions(opts) { var i, tx, txs = $.fn.cycle.transitions; // look for multiple effects if (opts.fx.indexOf(',') > 0) { opts.multiFx = true; opts.fxs = opts.fx.replace(/\s*/g,'').split(','); // discard any bogus effect names for (i=0; i < opts.fxs.length; i++) { var fx = opts.fxs[i]; tx = txs[fx]; if (!tx || !txs.hasOwnProperty(fx) || !$.isFunction(tx)) { log('discarding unknown transition: ',fx); opts.fxs.splice(i,1); i--; } } // if we have an empty list then we threw everything away! if (!opts.fxs.length) { log('No valid transitions named; slideshow terminating.'); return false; } } else if (opts.fx == 'all') { // auto-gen the list of transitions opts.multiFx = true; opts.fxs = []; for (var p in txs) { if (txs.hasOwnProperty(p)) { tx = txs[p]; if (txs.hasOwnProperty(p) && $.isFunction(tx)) opts.fxs.push(p); } } } if (opts.multiFx && opts.randomizeEffects) { // munge the fxs array to make effect selection random var r1 = Math.floor(Math.random() * 20) + 30; for (i = 0; i < r1; i++) { var r2 = Math.floor(Math.random() * opts.fxs.length); opts.fxs.push(opts.fxs.splice(r2,1)[0]); } debug('randomized fx sequence: ',opts.fxs); } return true; } // provide a mechanism for adding slides after the slideshow has started function exposeAddSlide(opts, els) { opts.addSlide = function(newSlide, prepend) { var $s = $(newSlide), s = $s[0]; if (!opts.autostopCount) opts.countdown++; els[prepend?'unshift':'push'](s); if (opts.els) opts.els[prepend?'unshift':'push'](s); // shuffle needs this opts.slideCount = els.length; // add the slide to the random map and resort if (opts.random) { opts.randomMap.push(opts.slideCount-1); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } $s.css('position','absolute'); $s[prepend?'prependTo':'appendTo'](opts.$cont); if (prepend) { opts.currSlide++; opts.nextSlide++; } if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($s); if (opts.fit && opts.width) $s.width(opts.width); if (opts.fit && opts.height && opts.height != 'auto') $s.height(opts.height); s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height(); s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width(); $s.css(opts.cssBefore); if (opts.pager || opts.pagerAnchorBuilder) $.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts); if ($.isFunction(opts.onAddSlide)) opts.onAddSlide($s); else $s.hide(); // default behavior }; } // reset internal state; we do this on every pass in order to support multiple effects $.fn.cycle.resetState = function(opts, fx) { fx = fx || opts.fx; opts.before = []; opts.after = []; opts.cssBefore = $.extend({}, opts.original.cssBefore); opts.cssAfter = $.extend({}, opts.original.cssAfter); opts.animIn = $.extend({}, opts.original.animIn); opts.animOut = $.extend({}, opts.original.animOut); opts.fxFn = null; $.each(opts.original.before, function() { opts.before.push(this); }); $.each(opts.original.after, function() { opts.after.push(this); }); // re-init var init = $.fn.cycle.transitions[fx]; if ($.isFunction(init)) init(opts.$cont, $(opts.elements), opts); }; // this is the main engine fn, it handles the timeouts, callbacks and slide index mgmt function go(els, opts, manual, fwd) { var p = opts.$cont[0], curr = els[opts.currSlide], next = els[opts.nextSlide]; // opts.busy is true if we're in the middle of an animation if (manual && opts.busy && opts.manualTrump) { // let manual transitions requests trump active ones debug('manualTrump in go(), stopping active transition'); $(els).stop(true,true); opts.busy = 0; clearTimeout(p.cycleTimeout); } // don't begin another timeout-based transition if there is one active if (opts.busy) { debug('transition active, ignoring new tx request'); return; } // stop cycling if we have an outstanding stop request if (p.cycleStop != opts.stopCount || p.cycleTimeout === 0 && !manual) return; // check to see if we should stop cycling based on autostop options if (!manual && !p.cyclePause && !opts.bounce && ((opts.autostop && (--opts.countdown <= 0)) || (opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) { if (opts.end) opts.end(opts); return; } // if slideshow is paused, only transition on a manual trigger var changed = false; if ((manual || !p.cyclePause) && (opts.nextSlide != opts.currSlide)) { changed = true; var fx = opts.fx; // keep trying to get the slide size if we don't have it yet curr.cycleH = curr.cycleH || $(curr).height(); curr.cycleW = curr.cycleW || $(curr).width(); next.cycleH = next.cycleH || $(next).height(); next.cycleW = next.cycleW || $(next).width(); // support multiple transition types if (opts.multiFx) { if (fwd && (opts.lastFx === undefined || ++opts.lastFx >= opts.fxs.length)) opts.lastFx = 0; else if (!fwd && (opts.lastFx === undefined || --opts.lastFx < 0)) opts.lastFx = opts.fxs.length - 1; fx = opts.fxs[opts.lastFx]; } // one-time fx overrides apply to: $('div').cycle(3,'zoom'); if (opts.oneTimeFx) { fx = opts.oneTimeFx; opts.oneTimeFx = null; } $.fn.cycle.resetState(opts, fx); // run the before callbacks if (opts.before.length) $.each(opts.before, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); // stage the after callacks var after = function() { opts.busy = 0; $.each(opts.after, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); if (!p.cycleStop) { // queue next transition queueNext(); } }; debug('tx firing('+fx+'); currSlide: ' + opts.currSlide + '; nextSlide: ' + opts.nextSlide); // get ready to perform the transition opts.busy = 1; if (opts.fxFn) // fx function provided? opts.fxFn(curr, next, opts, after, fwd, manual && opts.fastOnEvent); else if ($.isFunction($.fn.cycle[opts.fx])) // fx plugin ? $.fn.cycle[opts.fx](curr, next, opts, after, fwd, manual && opts.fastOnEvent); else $.fn.cycle.custom(curr, next, opts, after, fwd, manual && opts.fastOnEvent); } else { queueNext(); } if (changed || opts.nextSlide == opts.currSlide) { // calculate the next slide var roll; opts.lastSlide = opts.currSlide; if (opts.random) { opts.currSlide = opts.nextSlide; if (++opts.randomIndex == els.length) { opts.randomIndex = 0; opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } opts.nextSlide = opts.randomMap[opts.randomIndex]; if (opts.nextSlide == opts.currSlide) opts.nextSlide = (opts.currSlide == opts.slideCount - 1) ? 0 : opts.currSlide + 1; } else if (opts.backwards) { roll = (opts.nextSlide - 1) < 0; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = 1; opts.currSlide = 0; } else { opts.nextSlide = roll ? (els.length-1) : opts.nextSlide-1; opts.currSlide = roll ? 0 : opts.nextSlide+1; } } else { // sequence roll = (opts.nextSlide + 1) == els.length; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = els.length-2; opts.currSlide = els.length-1; } else { opts.nextSlide = roll ? 0 : opts.nextSlide+1; opts.currSlide = roll ? els.length-1 : opts.nextSlide-1; } } } if (changed && opts.pager) opts.updateActivePagerLink(opts.pager, opts.currSlide, opts.activePagerClass); function queueNext() { // stage the next transition var ms = 0, timeout = opts.timeout; if (opts.timeout && !opts.continuous) { ms = getTimeout(els[opts.currSlide], els[opts.nextSlide], opts, fwd); if (opts.fx == 'shuffle') ms -= opts.speedOut; } else if (opts.continuous && p.cyclePause) // continuous shows work off an after callback, not this timer logic ms = 10; if (ms > 0) p.cycleTimeout = setTimeout(function(){ go(els, opts, 0, !opts.backwards); }, ms); } } // invoked after transition $.fn.cycle.updateActivePagerLink = function(pager, currSlide, clsName) { $(pager).each(function() { $(this).children().removeClass(clsName).eq(currSlide).addClass(clsName); }); }; // calculate timeout value for current transition function getTimeout(curr, next, opts, fwd) { if (opts.timeoutFn) { // call user provided calc fn var t = opts.timeoutFn.call(curr,curr,next,opts,fwd); while (opts.fx != 'none' && (t - opts.speed) < 250) // sanitize timeout t += opts.speed; debug('calculated timeout: ' + t + '; speed: ' + opts.speed); if (t !== false) return t; } return opts.timeout; } // expose next/prev function, caller must pass in state $.fn.cycle.next = function(opts) { advance(opts,1); }; $.fn.cycle.prev = function(opts) { advance(opts,0);}; // advance slide forward or back function advance(opts, moveForward) { var val = moveForward ? 1 : -1; var els = opts.elements; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } if (opts.random && val < 0) { // move back to the previously display slide opts.randomIndex--; if (--opts.randomIndex == -2) opts.randomIndex = els.length-2; else if (opts.randomIndex == -1) opts.randomIndex = els.length-1; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.random) { opts.nextSlide = opts.randomMap[opts.randomIndex]; } else { opts.nextSlide = opts.currSlide + val; if (opts.nextSlide < 0) { if (opts.nowrap) return false; opts.nextSlide = els.length - 1; } else if (opts.nextSlide >= els.length) { if (opts.nowrap) return false; opts.nextSlide = 0; } } var cb = opts.onPrevNextEvent || opts.prevNextClick; // prevNextClick is deprecated if ($.isFunction(cb)) cb(val > 0, opts.nextSlide, els[opts.nextSlide]); go(els, opts, 1, moveForward); return false; } function buildPager(els, opts) { var $p = $(opts.pager); $.each(els, function(i,o) { $.fn.cycle.createPagerAnchor(i,o,$p,els,opts); }); opts.updateActivePagerLink(opts.pager, opts.startingSlide, opts.activePagerClass); } $.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) { var a; if ($.isFunction(opts.pagerAnchorBuilder)) { a = opts.pagerAnchorBuilder(i,el); debug('pagerAnchorBuilder('+i+', el) returned: ' + a); } else a = '<a href="#">'+(i+1)+'</a>'; if (!a) return; var $a = $(a); // don't reparent if anchor is in the dom if ($a.parents('body').length === 0) { var arr = []; if ($p.length > 1) { $p.each(function() { var $clone = $a.clone(true); $(this).append($clone); arr.push($clone[0]); }); $a = $(arr); } else { $a.appendTo($p); } } opts.pagerAnchors = opts.pagerAnchors || []; opts.pagerAnchors.push($a); var pagerFn = function(e) { e.preventDefault(); opts.nextSlide = i; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } var cb = opts.onPagerEvent || opts.pagerClick; // pagerClick is deprecated if ($.isFunction(cb)) cb(opts.nextSlide, els[opts.nextSlide]); go(els,opts,1,opts.currSlide < i); // trigger the trans // return false; // <== allow bubble }; if ( /mouseenter|mouseover/i.test(opts.pagerEvent) ) { $a.hover(pagerFn, function(){/* no-op */} ); } else { $a.bind(opts.pagerEvent, pagerFn); } if ( ! /^click/.test(opts.pagerEvent) && !opts.allowPagerClickBubble) $a.bind('click.cycle', function(){return false;}); // suppress click var cont = opts.$cont[0]; var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pauseOnPagerHover) { $a.hover( function() { pauseFlag = true; cont.cyclePause++; triggerPause(cont,true,true); }, function() { if (pauseFlag) cont.cyclePause--; triggerPause(cont,true,true); } ); } }; // helper fn to calculate the number of slides between the current and the next $.fn.cycle.hopsFromLast = function(opts, fwd) { var hops, l = opts.lastSlide, c = opts.currSlide; if (fwd) hops = c > l ? c - l : opts.slideCount - l; else hops = c < l ? l - c : l + opts.slideCount - c; return hops; }; // fix clearType problems in ie6 by setting an explicit bg color // (otherwise text slides look horrible during a fade transition) function clearTypeFix($slides) { debug('applying clearType background-color hack'); function hex(s) { s = parseInt(s,10).toString(16); return s.length < 2 ? '0'+s : s; } function getBg(e) { for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) { var v = $.css(e,'background-color'); if (v && v.indexOf('rgb') >= 0 ) { var rgb = v.match(/\d+/g); return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]); } if (v && v != 'transparent') return v; } return '#ffffff'; } $slides.each(function() { $(this).css('background-color', getBg(this)); }); } // reset common props before the next transition $.fn.cycle.commonReset = function(curr,next,opts,w,h,rev) { $(opts.elements).not(curr).hide(); if (typeof opts.cssBefore.opacity == 'undefined') opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; if (opts.slideResize && w !== false && next.cycleW > 0) opts.cssBefore.width = next.cycleW; if (opts.slideResize && h !== false && next.cycleH > 0) opts.cssBefore.height = next.cycleH; opts.cssAfter = opts.cssAfter || {}; opts.cssAfter.display = 'none'; $(curr).css('zIndex',opts.slideCount + (rev === true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev === true ? 0 : 1)); }; // the actual fn for effecting a transition $.fn.cycle.custom = function(curr, next, opts, cb, fwd, speedOverride) { var $l = $(curr), $n = $(next); var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut; $n.css(opts.cssBefore); if (speedOverride) { if (typeof speedOverride == 'number') speedIn = speedOut = speedOverride; else speedIn = speedOut = 1; easeIn = easeOut = null; } var fn = function() { $n.animate(opts.animIn, speedIn, easeIn, function() { cb(); }); }; $l.animate(opts.animOut, speedOut, easeOut, function() { $l.css(opts.cssAfter); if (!opts.sync) fn(); }); if (opts.sync) fn(); }; // transition definitions - only fade is defined here, transition pack defines the rest $.fn.cycle.transitions = { fade: function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css('opacity',0); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.opacity = 0; }); opts.animIn = { opacity: 1 }; opts.animOut = { opacity: 0 }; opts.cssBefore = { top: 0, left: 0 }; } }; $.fn.cycle.ver = function() { return ver; }; // override these globally if you like (they are all optional) $.fn.cycle.defaults = { activePagerClass: 'activeSlide', // class name used for the active pager link after: null, // transition callback (scope set to element that was shown): function(currSlideElement, nextSlideElement, options, forwardFlag) allowPagerClickBubble: false, // allows or prevents click event on pager anchors from bubbling animIn: null, // properties that define how the slide animates in animOut: null, // properties that define how the slide animates out aspect: false, // preserve aspect ratio during fit resizing, cropping if necessary (must be used with fit option) autostop: 0, // true to end slideshow after X transitions (where X == slide count) autostopCount: 0, // number of transitions (optionally used with autostop to define X) backwards: false, // true to start slideshow at last slide and move backwards through the stack before: null, // transition callback (scope set to element to be shown): function(currSlideElement, nextSlideElement, options, forwardFlag) center: null, // set to true to have cycle add top/left margin to each slide (use with width and height options) cleartype: !$.support.opacity, // true if clearType corrections should be applied (for IE) cleartypeNoBg: false, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides) containerResize: 1, // resize container to fit largest slide containerResizeHeight: 0, // resize containers height to fit the largest slide but leave the width dynamic continuous: 0, // true to start next transition immediately after current one completes cssAfter: null, // properties that defined the state of the slide after transitioning out cssBefore: null, // properties that define the initial state of the slide before transitioning in delay: 0, // additional delay (in ms) for first transition (hint: can be negative) easeIn: null, // easing for "in" transition easeOut: null, // easing for "out" transition easing: null, // easing method for both in and out transitions end: null, // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options) fastOnEvent: 0, // force fast transitions when triggered manually (via pager or prev/next); value == time in ms fit: 0, // force slides to fit container fx: 'fade', // name of transition effect (or comma separated names, ex: 'fade,scrollUp,shuffle') fxFn: null, // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag) height: 'auto', // container height (if the 'fit' option is true, the slides will be set to this height as well) manualTrump: true, // causes manual transition to stop an active transition instead of being ignored metaAttr: 'cycle', // data- attribute that holds the option data for the slideshow next: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for next slide nowrap: 0, // true to prevent slideshow from wrapping onPagerEvent: null, // callback fn for pager events: function(zeroBasedSlideIndex, slideElement) onPrevNextEvent: null, // callback fn for prev/next events: function(isNext, zeroBasedSlideIndex, slideElement) pager: null, // element, jQuery object, or jQuery selector string for the element to use as pager container pagerAnchorBuilder: null, // callback fn for building anchor links: function(index, DOMelement) pagerEvent: 'click.cycle', // name of event which drives the pager navigation pause: 0, // true to enable "pause on hover" pauseOnPagerHover: 0, // true to pause when hovering over pager link prev: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for previous slide prevNextEvent: 'click.cycle',// event which drives the manual transition to the previous or next slide random: 0, // true for random, false for sequence (not applicable to shuffle fx) randomizeEffects: 1, // valid when multiple effects are used; true to make the effect sequence random requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded requeueTimeout: 250, // ms delay for requeue rev: 0, // causes animations to transition in reverse (for effects that support it such as scrollHorz/scrollVert/shuffle) shuffle: null, // coords for shuffle animation, ex: { top:15, left: 200 } skipInitializationCallbacks: false, // set to true to disable the first before/after callback that occurs prior to any transition slideExpr: null, // expression for selecting slides (if something other than all children is required) slideResize: 1, // force slide width/height to fixed size before every transition speed: 1000, // speed of the transition (any valid fx speed value) speedIn: null, // speed of the 'in' transition speedOut: null, // speed of the 'out' transition startingSlide: undefined,// zero-based index of the first slide to be displayed sync: 1, // true if in/out transitions should occur simultaneously timeout: 4000, // milliseconds between slide transitions (0 to disable auto advance) timeoutFn: null, // callback for determining per-slide timeout value: function(currSlideElement, nextSlideElement, options, forwardFlag) updateActivePagerLink: null,// callback fn invoked to update the active pager link (adds/removes activePagerClass style) width: null // container width (if the 'fit' option is true, the slides will be set to this width as well) }; })(jQuery); /*! * jQuery Cycle Plugin Transition Definitions * This script is a plugin for the jQuery Cycle Plugin * Examples and documentation at: http://malsup.com/jquery/cycle/ * Copyright (c) 2007-2010 M. Alsup * Version: 2.73 * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function($) { "use strict"; // // These functions define slide initialization and properties for the named // transitions. To save file size feel free to remove any of these that you // don't need. // $.fn.cycle.transitions.none = function($cont, $slides, opts) { opts.fxFn = function(curr,next,opts,after){ $(next).show(); $(curr).hide(); after(); }; }; // not a cross-fade, fadeout only fades out the top slide $.fn.cycle.transitions.fadeout = function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css({ display: 'block', 'opacity': 1 }); opts.before.push(function(curr,next,opts,w,h,rev) { $(curr).css('zIndex',opts.slideCount + (rev !== true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev !== true ? 0 : 1)); }); opts.animIn.opacity = 1; opts.animOut.opacity = 0; opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; opts.cssAfter.zIndex = 0; }; // scrollUp/Down/Left/Right $.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.cssFirst.top = 0; opts.animIn.top = 0; opts.animOut.top = -h; }; $.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssFirst.top = 0; opts.cssBefore.top = -h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; $.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = 0-w; }; $.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = -w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; $.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) { $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW); opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW; }); opts.cssFirst.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.top = 0; }; $.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.top = fwd ? (1-next.cycleH) : (next.cycleH-1); opts.animOut.top = fwd ? curr.cycleH : -curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.left = 0; }; // slideX/slideY $.fn.cycle.transitions.slideX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.width = 'show'; opts.animOut.width = 0; }; $.fn.cycle.transitions.slideY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animIn.height = 'show'; opts.animOut.height = 0; }; // shuffle $.fn.cycle.transitions.shuffle = function($cont, $slides, opts) { var i, w = $cont.css('overflow', 'visible').width(); $slides.css({left: 0, top: 0}); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); }); // only adjust speed once! if (!opts.speedAdjusted) { opts.speed = opts.speed / 2; // shuffle has 2 transitions opts.speedAdjusted = true; } opts.random = 0; opts.shuffle = opts.shuffle || {left:-w, top:15}; opts.els = []; for (i=0; i < $slides.length; i++) opts.els.push($slides[i]); for (i=0; i < opts.currSlide; i++) opts.els.push(opts.els.shift()); // custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!) opts.fxFn = function(curr, next, opts, cb, fwd) { if (opts.rev) fwd = !fwd; var $el = fwd ? $(curr) : $(next); $(next).css(opts.cssBefore); var count = opts.slideCount; $el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() { var hops = $.fn.cycle.hopsFromLast(opts, fwd); for (var k=0; k < hops; k++) { if (fwd) opts.els.push(opts.els.shift()); else opts.els.unshift(opts.els.pop()); } if (fwd) { for (var i=0, len=opts.els.length; i < len; i++) $(opts.els[i]).css('z-index', len-i+count); } else { var z = $(curr).css('z-index'); $el.css('z-index', parseInt(z,10)+1+count); } $el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() { $(fwd ? this : curr).hide(); if (cb) cb(); }); }); }; $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); }; // turnUp/Down/Left/Right $.fn.cycle.transitions.turnUp = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = next.cycleH; opts.animIn.height = next.cycleH; opts.animOut.width = next.cycleW; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.height = 0; opts.animIn.top = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnDown = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = next.cycleW; opts.animIn.width = next.cycleW; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.left = 0; opts.animOut.width = 0; }; $.fn.cycle.transitions.turnRight = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); $.extend(opts.cssBefore, { top: 0, left: 0, width: 0 }); opts.animIn.left = 0; opts.animOut.width = 0; }; // zoom $.fn.cycle.transitions.zoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false,true); opts.cssBefore.top = next.cycleH/2; opts.cssBefore.left = next.cycleW/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); $.extend(opts.animOut, { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 }); }); opts.cssFirst.top = 0; opts.cssFirst.left = 0; opts.cssBefore.width = 0; opts.cssBefore.height = 0; }; // fadeZoom $.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false); opts.cssBefore.left = next.cycleW/2; opts.cssBefore.top = next.cycleH/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); }); opts.cssBefore.width = 0; opts.cssBefore.height = 0; opts.animOut.opacity = 0; }; // blindX $.fn.cycle.transitions.blindX = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; // blindY $.fn.cycle.transitions.blindY = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; // blindZ $.fn.cycle.transitions.blindZ = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); var w = $cont.width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = w; opts.animIn.top = 0; opts.animIn.left = 0; opts.animOut.top = h; opts.animOut.left = w; }; // growX - grow horizontally from centered 0 width $.fn.cycle.transitions.growX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = this.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // growY - grow vertically from centered 0 height $.fn.cycle.transitions.growY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = this.cycleH/2; opts.animIn.top = 0; opts.animIn.height = this.cycleH; opts.animOut.top = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // curtainX - squeeze in both edges horizontally $.fn.cycle.transitions.curtainX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true,true); opts.cssBefore.left = next.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = curr.cycleW/2; opts.animOut.width = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // curtainY - squeeze in both edges vertically $.fn.cycle.transitions.curtainY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false,true); opts.cssBefore.top = next.cycleH/2; opts.animIn.top = 0; opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH/2; opts.animOut.height = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // cover - curr slide covered by next slide $.fn.cycle.transitions.cover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssAfter.display = ''; if (d == 'right') opts.cssBefore.left = -w; else if (d == 'up') opts.cssBefore.top = h; else if (d == 'down') opts.cssBefore.top = -h; else opts.cssBefore.left = w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // uncover - curr slide moves off next slide $.fn.cycle.transitions.uncover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); if (d == 'right') opts.animOut.left = w; else if (d == 'up') opts.animOut.top = -h; else if (d == 'down') opts.animOut.top = h; else opts.animOut.left = -w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // toss - move top slide and fade away $.fn.cycle.transitions.toss = function($cont, $slides, opts) { var w = $cont.css('overflow','visible').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); // provide default toss settings if animOut not provided if (!opts.animOut.left && !opts.animOut.top) $.extend(opts.animOut, { left: w*2, top: -h/2, opacity: 0 }); else opts.animOut.opacity = 0; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; }; // wipe - clip animation $.fn.cycle.transitions.wipe = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.cssBefore = opts.cssBefore || {}; var clip; if (opts.clip) { if (/l2r/.test(opts.clip)) clip = 'rect(0px 0px '+h+'px 0px)'; else if (/r2l/.test(opts.clip)) clip = 'rect(0px '+w+'px '+h+'px '+w+'px)'; else if (/t2b/.test(opts.clip)) clip = 'rect(0px '+w+'px 0px 0px)'; else if (/b2t/.test(opts.clip)) clip = 'rect('+h+'px '+w+'px '+h+'px 0px)'; else if (/zoom/.test(opts.clip)) { var top = parseInt(h/2,10); var left = parseInt(w/2,10); clip = 'rect('+top+'px '+left+'px '+top+'px '+left+'px)'; } } opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)'; var d = opts.cssBefore.clip.match(/(\d+)/g); var t = parseInt(d[0],10), r = parseInt(d[1],10), b = parseInt(d[2],10), l = parseInt(d[3],10); opts.before.push(function(curr, next, opts) { if (curr == next) return; var $curr = $(curr), $next = $(next); $.fn.cycle.commonReset(curr,next,opts,true,true,false); opts.cssAfter.display = 'block'; var step = 1, count = parseInt((opts.speedIn / 13),10) - 1; (function f() { var tt = t ? t - parseInt(step * (t/count),10) : 0; var ll = l ? l - parseInt(step * (l/count),10) : 0; var bb = b < h ? b + parseInt(step * ((h-b)/count || 1),10) : h; var rr = r < w ? r + parseInt(step * ((w-r)/count || 1),10) : w; $next.css({ clip: 'rect('+tt+'px '+rr+'px '+bb+'px '+ll+'px)' }); (step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none'); })(); }); $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); opts.animIn = { left: 0 }; opts.animOut = { left: 0 }; }; })(jQuery);
JavaScript
/* * File: jquery.loadJSON.js * Version: 1.2.5. * Author: Jovan Popovic * * Copyright 2011 Jovan Popovic, all rights reserved. * * This source file is free software, under either the GPL v2 license or a * BSD style license, as supplied with this software. * * This source file is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * * This file contains implementation of the JQuery templating engine that load JSON * objects into the HTML code. It is based on Alexandre Caprais notemplate plugin * with several enchancements that are added to this plugin. */ (function ($) { $.fn.loadJSON = function (obj, options) { function refreshMobileSelect(element) { try { if ($.isFunction($(element).selectmenu)) $(element).selectmenu('refresh'); //used in the JQuery mobile } catch (ex) { try { //$(element).selectmenu();//This will create duplicate select menu!!!!! //$(element).selectmenu('refresh'); } catch (ex) { } } } function refreshMobileCheckBox(element) { try { if ($.isFunction($(element).checkboxradio)) $(element).checkboxradio('refresh'); //used in the JQuery mobile } catch (ex) { } } function loadSelect(element, aoValues, name) { ///<summary> ///Load options into the select list ///</summary> ///<param name="element" type="JQuery:select">Select list</param> ///<param name="aoValues" type="Array{value,text,selected}">Array of object containin the options</param> ///<param name="name" type="String">Name of the select list</param> var arr = jQuery.makeArray(element); var template = $(arr[arr.length - 1]).clone(true); //how many duplicate var nbToCreate = obj.length; var i = 0; //fill started by last i = obj.length - 1; var iCreate = 0; for (iCreate = 0; iCreate < nbToCreate; iCreate++) { //duplicate the last var last = template.clone(true).insertAfter(arr[arr.length - 1]); //setElementValue(last, obj[i], name); $(last).attr("value", obj[i].value); $(last).text(obj[i].text); if (obj[i].selected) $(last).attr("selected", true); i--; } /////////////////////////////////////////////////////////////////////////////////////////// refreshMobileSelect(element) ////////////////////////////////////////////////////////////////////////////////////////// } function setElementValue(element, value, name) { var type = element.type || element.tagName; if (type == null) { type = element[0].type || element[0].tagName; //select returns undefined if called directly if (type == null) { return; } } type = type.toLowerCase(); switch (type) { case 'radio': if (value.toString().toLowerCase() == element.value.toLowerCase()) { $(element).attr("checked", "checked"); refreshMobileCheckBox(element); } break; case 'checkbox': if (value) { //$(element).attr("checked", "checked"); $(element).attr("checked", true); refreshMobileCheckBox(element); } break; case 'option': //$(element).attr("value", value.value); $(element).text(value.text); if (value.selected) $(element).attr("selected", true); break; case 'select-multiple': //This is "interesting". In mobile use element.options while in the desktop use element[0].options var select = element[0]; if (element[0].options == null || typeof (element[0].options) == "undefined") { select = element; } if (select.options.length > 1) { //If select list is not empty use values array to select optionses var values = value.constructor == Array ? value : [value]; //replaced element with element[0] ???? because now it reports that element.optons does not exists for (var i = 0; i < select.options.length; i++) { for (var j = 0; j < values.length; j++) { select.options[i].selected |= select.options[i].value == values[j]; } } refreshMobileSelect(element); } else { //ELSE: Instead of selecting values use values array to populate select list loadSelect(element, value, name); } break; case 'select': case 'select-one': if (typeof value == "string") { //$(element).attr("value", value); $(element).val(value); //refreshMobileSelect(element); }else { //loadSelect(element, value, name); } break; case 'text': case 'hidden': //$(element).attr("value", value); $(element).val(value); break; // case 'a': // var href = $(element).attr("href"); // // // // var iPosition = href.indexOf('#'); // if (iPosition > 1000000) { // href = href.substr(0, iPosition) + '&' + name + '=' + value + href.substr(iPosition) // // } else { // iPosition = href.indexOf('?'); // if (iPosition > 0) // if parameters in the URL exists add new pair using & // href += '&' + name + '=' + value; // else//otherwise attach pair to URL // href = href + '?' + name + '=' + value; // } // $(element).attr("href", href); // break; case 'img': if (obj.constructor == "String") { //Assumption is that value is in the HREF$ALT format var iPosition = value.indexOf('$'); var src = ""; var alt = ""; if (iPosition > 0) { src = value.substring(0, iPosition); alt = value.substring(iPosition + 1); } else { src = value; var iPositionStart = value.lastIndexOf('/') + 1; var iPositionEnd = value.indexOf('.'); alt = value.substring(iPositionStart, iPositionEnd); } $(element).attr("src", src); $(element).attr("alt", alt); } else { $(element).attr("src", obj.src); $(element).attr("alt", obj.alt); $(element).attr("title", obj.title); } break; case 'textarea': //case 'submit': //case 'button': default: try { //$(element).html(value.toString()); } catch (exc) { } } } function browseJSON(obj, element, name) { // no object if (obj == undefined) { } // branch else if (obj.constructor == Object) { if (element.length >= 1 && element[0].tagName == "OPTION") { setElementValue(element[0], obj, name); //return; } for (var prop in obj) { if (prop == null || typeof prop == "undefined") continue; else { //Find an element with class, id, name, or rel attribute that matches the propertu name var child = jQuery.makeArray(jQuery("." + prop, element)).length > 0 ? jQuery("." + prop, element) : jQuery("#" + prop, element).length > 0 ? jQuery("#" + prop, element) : jQuery('[name="' + prop + '"]', element).length > 0 ? jQuery('[name="' + prop + '"]', element) : jQuery('[rel="' + prop + '"]'); if (child.length != 0) { browseJSON(obj[prop], jQuery(child, element), prop); } } } } // array /*ELSE*/else if (obj.constructor == Array) { if (element.length == 1 && (element.type == "select" || element.type == "select-one" || element.type == "select-multiple" || element[0].type == "select" || element[0].type == "select-one" || element[0].type == "select-multiple" )) { //setElementValue(element[0], obj, name); ///nova dva reda setElementValue(element, obj, name); return; /////////////////////////////////////////////////////////////////////////////////////////// //if ($.isFunction($(element[0]).selectmenu)) // $(element[0]).selectmenu('refresh', true); //used in the JQuery mobile /////////////////////////////////////////////////////////////////////////////////////////// } else { var arrayElements = $(element).children("[rel]"); if (arrayElements.length > 0) {//if there are rel=[index] elements populate them instead of iteration arrayElements.each(function () { var rel = $(this).attr("rel"); //setElementValue(this, obj[rel], name); browseJSON(obj[rel], $(this), name); }); } else {//recursive iteration var arr = jQuery.makeArray(element); var template = $(arr[arr.length - 1]).clone(true); //how many duplicate var nbToCreate = obj.length; var i = 0; if (element[0] == null || (element[0] != null && element[0].tagName != "OPTION")) { var iExist = 0; for (iExist = 0; iExist < arr.length; iExist++) { if (i < obj.length) { var elem = $(element).eq(iExist); browseJSON(obj[i], elem, name); } i++; } var nbToCreate = obj.length - arr.length; ; } //fill started by last i = obj.length - 1; var iCreate = 0; for (iCreate = 0; iCreate < nbToCreate; iCreate++) { //duplicate the last var last = template.clone(true).insertAfter(arr[arr.length - 1]); browseJSON(obj[i], last, name); i--; } /////////////////////////////////////////////////////////////////////////////////////////// //if ($.isFunction($(element).selectmenu)) // $(element).selectmenu('refresh', true); //used in the JQuery mobile ////////////////////////////////////////////////////////////////////////////////////////// } } } // data only else { var value = obj; var type; if (element.length > 0) { var i = 0; for (i = 0; i < element.length; i++) setElementValue(element[i], obj, name); } else { setElementValue(element, obj, name); } } } //function browseJSON end function init(placeholder) { if (placeholder.data("loadJSON-template") != null && placeholder.data("loadJSON-template") != "") { var template = placeholder.data("loadJSON-template"); placeholder.html(template); } else { var template = placeholder.html() placeholder.data("loadJSON-template", template); } } var defaults = { onLoading: function () { }, onLoaded: function () { }, mobile: false }; properties = $.extend(defaults, options); return this.each(function () { if (obj.constructor == String) { if (obj.charAt(0) == '{' || obj.charAt(0) == '[') { var data = $.parseJSON(obj); init($(this)); properties.onLoading(); browseJSON(data, this); properties.onLoaded(); } else { var element = $(this); $.ajax({ url: obj, success: function (data) { element.loadJSON(data, properties); }, cache: false, dataType: "json" }); } } else { init($(this)); properties.onLoading(); browseJSON(obj, this); properties.onLoaded(); } }); }; })(jQuery);
JavaScript
/* Project : 48c6c450f1a4a0cc53d9585dc0fee742 Created on : Mar 16, 2013, 11:29:15 PM Author : Truong Khuong - khuongxuantruong@gmail.com Description : Purpose of the stylesheet follows. */ function a(){alert("a")}
JavaScript
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ function _goto_tab(o){ var index=$(o).data("tabIndex"); $(".tab",$(o).parents(".etabs")[0]).hide(); $(".tab.t-"+index,$(o).parents(".etabs")[0]).show(); $(o).parent().find('li.hover').removeClass('hover'); $(o).addClass('hover'); } function _addtab(o){ var index=Math.floor(Math.random()*10000); if(!confirm("Add new tab?")) return; var i=Math.random() $(o).parents(".etabs") .find('li.hover') .removeClass('hover'); $(o).before('<li class="hover mceNonEditable" data-tab-index="'+index+'" data-mce-contenteditable="false" onclick="_goto_tab(this)">\ <span class="mceEditable" data-mce-contenteditable="true">newtab</span>\ </li>'); $(".tab",$(o).parents(".etabs")).hide(); $(o).parents(".etabs") .find('.tab-content') .append('<div class="tab mceNonEditable t-'+index+'" data-mce-contenteditable="false" style="display:block">\ <div data-mce-contenteditable="false" class="paragraph mceNoneEditable">\ <div data-mce-contenteditable="true" class="paragraph mceEditable">Tab content here...</div>\ <div>\ </div>'); }
JavaScript
/*! * jQuery Migrate - v1.2.1 - 2013-05-08 * https://github.com/jquery/jquery-migrate * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors; Licensed MIT */ (function( jQuery, window, undefined ) { // See http://bugs.jquery.com/ticket/13335 // "use strict"; var warnedAbout = {}; // List of warnings already given; public read only jQuery.migrateWarnings = []; // Set to true to prevent console output; migrateWarnings still maintained // jQuery.migrateMute = false; // Show a message on the console so devs know we're active if ( !jQuery.migrateMute && window.console && window.console.log ) { window.console.log("JQMIGRATE: Logging is active"); } // Set to false to disable traces that appear with warnings if ( jQuery.migrateTrace === undefined ) { jQuery.migrateTrace = true; } // Forget any warnings we've already given; public jQuery.migrateReset = function() { warnedAbout = {}; jQuery.migrateWarnings.length = 0; }; function migrateWarn( msg) { var console = window.console; if ( !warnedAbout[ msg ] ) { warnedAbout[ msg ] = true; jQuery.migrateWarnings.push( msg ); if ( console && console.warn && !jQuery.migrateMute ) { console.warn( "JQMIGRATE: " + msg ); if ( jQuery.migrateTrace && console.trace ) { console.trace(); } } } } function migrateWarnProp( obj, prop, value, msg ) { if ( Object.defineProperty ) { // On ES5 browsers (non-oldIE), warn if the code tries to get prop; // allow property to be overwritten in case some other plugin wants it try { Object.defineProperty( obj, prop, { configurable: true, enumerable: true, get: function() { migrateWarn( msg ); return value; }, set: function( newValue ) { migrateWarn( msg ); value = newValue; } }); return; } catch( err ) { // IE8 is a dope about Object.defineProperty, can't warn there } } // Non-ES5 (or broken) browser; just set the property jQuery._definePropertyBroken = true; obj[ prop ] = value; } if ( document.compatMode === "BackCompat" ) { // jQuery has never supported or tested Quirks Mode migrateWarn( "jQuery is not compatible with Quirks Mode" ); } var attrFn = jQuery( "<input/>", { size: 1 } ).attr("size") && jQuery.attrFn, oldAttr = jQuery.attr, valueAttrGet = jQuery.attrHooks.value && jQuery.attrHooks.value.get || function() { return null; }, valueAttrSet = jQuery.attrHooks.value && jQuery.attrHooks.value.set || function() { return undefined; }, rnoType = /^(?:input|button)$/i, rnoAttrNodeType = /^[238]$/, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, ruseDefault = /^(?:checked|selected)$/i; // jQuery.attrFn migrateWarnProp( jQuery, "attrFn", attrFn || {}, "jQuery.attrFn is deprecated" ); jQuery.attr = function( elem, name, value, pass ) { var lowerName = name.toLowerCase(), nType = elem && elem.nodeType; if ( pass ) { // Since pass is used internally, we only warn for new jQuery // versions where there isn't a pass arg in the formal params if ( oldAttr.length < 4 ) { migrateWarn("jQuery.fn.attr( props, pass ) is deprecated"); } if ( elem && !rnoAttrNodeType.test( nType ) && (attrFn ? name in attrFn : jQuery.isFunction(jQuery.fn[name])) ) { return jQuery( elem )[ name ]( value ); } } // Warn if user tries to set `type`, since it breaks on IE 6/7/8; by checking // for disconnected elements we don't warn on $( "<button>", { type: "button" } ). if ( name === "type" && value !== undefined && rnoType.test( elem.nodeName ) && elem.parentNode ) { migrateWarn("Can't change the 'type' of an input or button in IE 6/7/8"); } // Restore boolHook for boolean property/attribute synchronization if ( !jQuery.attrHooks[ lowerName ] && rboolean.test( lowerName ) ) { jQuery.attrHooks[ lowerName ] = { 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; } }; // Warn only for attributes that can remain distinct from their properties post-1.9 if ( ruseDefault.test( lowerName ) ) { migrateWarn( "jQuery.fn.attr('" + lowerName + "') may use property instead of attribute" ); } } return oldAttr.call( jQuery, elem, name, value ); }; // attrHooks: value jQuery.attrHooks.value = { get: function( elem, name ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "button" ) { return valueAttrGet.apply( this, arguments ); } if ( nodeName !== "input" && nodeName !== "option" ) { migrateWarn("jQuery.fn.attr('value') no longer gets properties"); } return name in elem ? elem.value : null; }, set: function( elem, value ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "button" ) { return valueAttrSet.apply( this, arguments ); } if ( nodeName !== "input" && nodeName !== "option" ) { migrateWarn("jQuery.fn.attr('value', val) no longer sets properties"); } // Does not return so that setAttribute is also used elem.value = value; } }; var matched, browser, oldInit = jQuery.fn.init, oldParseJSON = jQuery.parseJSON, // Note: XSS check is done below after string is trimmed rquickExpr = /^([^<]*)(<[\w\W]+>)([^>]*)$/; // $(html) "looks like html" rule change jQuery.fn.init = function( selector, context, rootjQuery ) { var match; if ( selector && typeof selector === "string" && !jQuery.isPlainObject( context ) && (match = rquickExpr.exec( jQuery.trim( selector ) )) && match[ 0 ] ) { // This is an HTML string according to the "old" rules; is it still? if ( selector.charAt( 0 ) !== "<" ) { migrateWarn("$(html) HTML strings must start with '<' character"); } if ( match[ 3 ] ) { migrateWarn("$(html) HTML text after last tag is ignored"); } // Consistently reject any HTML-like string starting with a hash (#9521) // Note that this may break jQuery 1.6.x code that otherwise would work. if ( match[ 0 ].charAt( 0 ) === "#" ) { migrateWarn("HTML string cannot start with a '#' character"); jQuery.error("JQMIGRATE: Invalid selector string (XSS)"); } // Now process using loose rules; let pre-1.8 play too if ( context && context.context ) { // jQuery object as context; parseHTML expects a DOM object context = context.context; } if ( jQuery.parseHTML ) { return oldInit.call( this, jQuery.parseHTML( match[ 2 ], context, true ), context, rootjQuery ); } } return oldInit.apply( this, arguments ); }; jQuery.fn.init.prototype = jQuery.fn; // Let $.parseJSON(falsy_value) return null jQuery.parseJSON = function( json ) { if ( !json && json !== null ) { migrateWarn("jQuery.parseJSON requires a valid JSON string"); return null; } return oldParseJSON.apply( this, arguments ); }; jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; // Don't clobber any existing jQuery.browser in case it's different if ( !jQuery.browser ) { matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; } // Warn if the code tries to get jQuery.browser migrateWarnProp( jQuery, "browser", jQuery.browser, "jQuery.browser is deprecated" ); jQuery.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); migrateWarn( "jQuery.sub() is deprecated" ); return jQuerySub; }; // Ensure that $.ajax gets the new parseJSON defined in core.js jQuery.ajaxSetup({ converters: { "text json": jQuery.parseJSON } }); var oldFnData = jQuery.fn.data; jQuery.fn.data = function( name ) { var ret, evt, elem = this[0]; // Handles 1.7 which has this behavior and 1.8 which doesn't if ( elem && name === "events" && arguments.length === 1 ) { ret = jQuery.data( elem, name ); evt = jQuery._data( elem, name ); if ( ( ret === undefined || ret === evt ) && evt !== undefined ) { migrateWarn("Use of jQuery.fn.data('events') is deprecated"); return evt; } } return oldFnData.apply( this, arguments ); }; var rscriptType = /\/(java|ecma)script/i, oldSelf = jQuery.fn.andSelf || jQuery.fn.addBack; jQuery.fn.andSelf = function() { migrateWarn("jQuery.fn.andSelf() replaced by jQuery.fn.addBack()"); return oldSelf.apply( this, arguments ); }; // Since jQuery.clean is used internally on older versions, we only shim if it's missing if ( !jQuery.clean ) { jQuery.clean = function( elems, context, fragment, scripts ) { // Set context per 1.8 logic context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; migrateWarn("jQuery.clean() is deprecated"); var i, elem, handleScript, jsTags, ret = []; jQuery.merge( ret, jQuery.buildFragment( elems, context ).childNodes ); // Complex logic lifted directly from jQuery 1.8 if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }; } var eventAdd = jQuery.event.add, eventRemove = jQuery.event.remove, eventTrigger = jQuery.event.trigger, oldToggle = jQuery.fn.toggle, oldLive = jQuery.fn.live, oldDie = jQuery.fn.die, ajaxEvents = "ajaxStart|ajaxStop|ajaxSend|ajaxComplete|ajaxError|ajaxSuccess", rajaxEvent = new RegExp( "\\b(?:" + ajaxEvents + ")\\b" ), rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, hoverHack = function( events ) { if ( typeof( events ) !== "string" || jQuery.event.special.hover ) { return events; } if ( rhoverHack.test( events ) ) { migrateWarn("'hover' pseudo-event is deprecated, use 'mouseenter mouseleave'"); } return events && events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; // Event props removed in 1.9, put them back if needed; no practical way to warn them if ( jQuery.event.props && jQuery.event.props[ 0 ] !== "attrChange" ) { jQuery.event.props.unshift( "attrChange", "attrName", "relatedNode", "srcElement" ); } // Undocumented jQuery.event.handle was "deprecated" in jQuery 1.7 if ( jQuery.event.dispatch ) { migrateWarnProp( jQuery.event, "handle", jQuery.event.dispatch, "jQuery.event.handle is undocumented and deprecated" ); } // Support for 'hover' pseudo-event and ajax event warnings jQuery.event.add = function( elem, types, handler, data, selector ){ if ( elem !== document && rajaxEvent.test( types ) ) { migrateWarn( "AJAX events should be attached to document: " + types ); } eventAdd.call( this, elem, hoverHack( types || "" ), handler, data, selector ); }; jQuery.event.remove = function( elem, types, handler, selector, mappedTypes ){ eventRemove.call( this, elem, hoverHack( types ) || "", handler, selector, mappedTypes ); }; jQuery.fn.error = function() { var args = Array.prototype.slice.call( arguments, 0); migrateWarn("jQuery.fn.error() is deprecated"); args.splice( 0, 0, "error" ); if ( arguments.length ) { return this.bind.apply( this, args ); } // error event should not bubble to window, although it does pre-1.7 this.triggerHandler.apply( this, args ); return this; }; jQuery.fn.toggle = function( fn, fn2 ) { // Don't mess with animation or css toggles if ( !jQuery.isFunction( fn ) || !jQuery.isFunction( fn2 ) ) { return oldToggle.apply( this, arguments ); } migrateWarn("jQuery.fn.toggle(handler, handler...) is deprecated"); // 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 ); }; jQuery.fn.live = function( types, data, fn ) { migrateWarn("jQuery.fn.live() is deprecated"); if ( oldLive ) { return oldLive.apply( this, arguments ); } jQuery( this.context ).on( types, this.selector, data, fn ); return this; }; jQuery.fn.die = function( types, fn ) { migrateWarn("jQuery.fn.die() is deprecated"); if ( oldDie ) { return oldDie.apply( this, arguments ); } jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }; // Turn global events into document-triggered events jQuery.event.trigger = function( event, data, elem, onlyHandlers ){ if ( !elem && !rajaxEvent.test( event ) ) { migrateWarn( "Global events are undocumented and deprecated" ); } return eventTrigger.call( this, event, data, elem || document, onlyHandlers ); }; jQuery.each( ajaxEvents.split("|"), function( _, name ) { jQuery.event.special[ name ] = { setup: function() { var elem = this; // The document needs no shimming; must be !== for oldIE if ( elem !== document ) { jQuery.event.add( document, name + "." + jQuery.guid, function() { jQuery.event.trigger( name, null, elem, true ); }); jQuery._data( this, name, jQuery.guid++ ); } return false; }, teardown: function() { if ( this !== document ) { jQuery.event.remove( document, name + "." + jQuery._data( this, name ) ); } return false; } }; } ); })( jQuery, window );
JavaScript
/* Project : 48c6c450f1a4a0cc53d9585dc0fee742 Created on : Mar 16, 2013, 11:29:15 PM Author : Truong Khuong - khuongxuantruong@gmail.com Description : Purpose of the stylesheet follows. */ var Categories=(function(){ var init=false; var datafields=[ { name : 'cate_id' ,type : 'int'}, { name : 'cate_type' }, { name : 'cate_title' }, { name : 'cate_display_title' }, { name : 'cate_alias' }, { name : 'cate_parent_title' }, { name : 'cate_position',type : 'int' }, { name : 'cate_link' }, { name : 'cate_thumb' }, { name : 'cate_status', type : 'bool' }, { name : 'cate_insert' }, { name : 'cate_update' }, { name : 'cate_value' }, { name : 'cate_target' }, { name : 'cate_desc' } ], columns=[ { text: 'Id' , dataField: 'cate_id' ,width:60,filterable:false ,sortable: false, cellsrenderer : function (row, column, value) { var str="<span style='margin: 4px; float: left;'>"; if(value && value>0){ try{ //value = $.parseJSON(value); str+="\ <div onclick=\"Categories.EditItem('"+value+"');\" \ class='w-16 h-16 f-l m-r-4 c-s-p hover-50 edit-icon' title='Edit'></div>\ "; str+="\ <div onclick=\"Categories.DeleteItem('"+value+"');\" \ class='w-16 h-16 f-l m-r-4 c-s-p hover-50 del-icon' title='Delete'></div>\ "; }catch(e){ErrorMsg(e.message);} } str+="</span>"; return str; } }, { text: 'Thumb' , dataField: 'cate_thumb' ,width:60,filterable:false ,sortable: false, cellsrenderer : function (row, datafield, value) { if(value==undefined || value=='') return '<img class="m-0-a d-p-b p-t-2" height="22" src="'+base_url+'libraries/images/22/picture.png"/>'; else return '<img class="m-0-a d-p-b p-t-2" height="22" src="/data/thumbs/' + value + '"/>'; } }, { text: 'Title' , dataField: 'cate_display_title' ,filterable:false }, { text: 'Parent' , dataField: 'cate_parent_title' ,width:100,filterable:false }, { text: 'Position' , dataField: 'cate_position' ,width:80,filterable:false, cellsalign:'right',columntype:'numberinput',filtertype:'number'}, { text: 'Type' , dataField: 'cate_type' ,width:100,filterable:false ,sortable: false}, { text: 'Status' , dataField: 'cate_status' ,width:80,filterable:false ,columntype:'checkbox',threestatecheckbox:false,filtertype:'bool'}, { text: 'Insert' , dataField: 'cate_insert' ,width:120,filterable:false ,cellsformat:'yyyy-MM-dd HH:mm:ss'}, ], source,dataAdapter, grid_element='#jqxGrid_Backend_Categories'; return { OnInit:function(){ try{ NoticeMsg('beforeprocessing: function(data){ source.totalrecords = data.total_rows; }'); WarningMsg("<pre>filter : function(){ $(\"#jqxReportGrid\").jqxGrid('updatebounddata', 'filter'); },\ sort : function(){ $(\"#jqxReportGrid\").jqxGrid('updatebounddata'); },\ root : 'rows',\ beforeprocessing: function(data){ source.totalrecords = data.total_rows; }</pre>") if(init) return; init=true; //grid_element=$('#jqxGrid_Backend_Categories'); source ={ datatype: "json",type : "POST", datafields: datafields, id: 'cate_id', url: base_url+'backend/category/binding/news.html', filter : function(){ $(grid_element).jqxGrid('updatebounddata', 'filter'); }, sort : function(){ $(grid_element).jqxGrid('updatebounddata'); }, root : 'rows', beforeprocessing: function(data){ source.totalrecords = data.total_rows; } }; dataAdapter = new $.jqx.dataAdapter(source, { loadError: function(xhr, status, error){ ErrorMsg("<b>Status</b>:"+xhr.status+"<br/><b>ThrownError</b>:"+error+"<br/>"); } }); $(grid_element).jqxGrid({ rendergridrows: function(obj){ return obj.data; },ready: function () { Categories.Filter('cate_type','news'); }, width: '100%',//height:'100%', source: dataAdapter, theme: theme,sortable: true, //filterable: true, //autoshowfiltericon: true, //showfilterrow: true, showemptyrow: true, virtualmode:false, columns: columns }); }catch(e){ ErrorMsg(e.message); } }, AddItem:function(){ this.EditItem(0); }, EditItem:function(Id){ $('#category_edit_panel_popup').load(base_url+"backend/category/loadEditPanel/news",{Id:Id},function(){ $('#category_edit_panel_tabs').jqxTabs({ theme: 'metro', height: 'auto', scrollable: true, selectionTracker: true, animationType: 'fade' }); bckdialog({ message:$('#category_edit_panel_popup'), title:'Category edit panel' }).open(); $("#category_form_edit_panel").validationEngine(); }); //$("#category_edit_panel_popup") }, Save:function(){ }, Cancel:function(){ }, DeleteItem:function(id){ accessdenied(); }, RestoreItem:function(){ accessdenied(); }, Permission:function(id){ }, PrivateItem:function(){ accessdenied(); }, Setting:function(){ bckdialog({ message:$('#window-sOpt'), icon:"<img class='p-a t-7 l-8' src='"+base_url+"/libraries/images/16/option.gif'/>", title:'Setting' }).open(); }, Refresh:function(){ //$("#jqxGrid").jqxGrid('updatebounddata'); Msg('✔ Dép bông nhung mềm mịn - 68.000 | Bộ màu vẽ 68 món - 85.000 | Máy uốn tóc new - 135.000'); }, Filter:function(datafield,filtervalue){ var filtertype = 'stringfilter'; var filtergroup = new $.jqx.filter(); var filter_or_operator = 1; var filtercondition = 'equal'; var filter = filtergroup.createfilter(filtertype, filtervalue, filtercondition); filtergroup.addfilter(filter_or_operator, filter); //$(grid_element).jqxGrid('clearfilters'); // add the filters. $(grid_element).jqxGrid('addfilter', datafield, filtergroup); // apply the filters. $(grid_element).jqxGrid('applyfilters'); } }; }()); $(document).ready(function () { //Btree().Init(); });
JavaScript
/* Project : 48c6c450f1a4a0cc53d9585dc0fee742 Created on : Mar 16, 2013, 11:29:15 PM Author : Truong Khuong - khuongxuantruong@gmail.com Description : Purpose of the stylesheet follows. */ isrunning =false; function includejs(url){ try{ var headID = document.getElementsByTagName("head")[0]; var newScript = document.createElement('script'); newScript.type = 'text/javascript'; newScript.src = url; headID.appendChild(newScript); return; var _ui = document.createElement('script'); _ui.type = 'text/javascript'; _ui.src = url; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(_ui, s); }catch(e){} } function includecss(url){ try{ var headID = document.getElementsByTagName("head")[0]; var cssNode = document.createElement('link'); cssNode.type = 'text/css'; cssNode.rel = 'stylesheet'; cssNode.href = url; cssNode.media = 'screen'; headID.appendChild(cssNode); return; var _ui = document.createElement('link'); _ui.rel = 'stylesheet'; _ui.type = 'text/javascript'; _ui.href = url; var s = document.getElementsByTagName('link')[0]; s.parentNode.insertBefore(_ui, s); }catch(e){} } function checkStrength(password){ //initial strength var strength = 0; //if the password length is less than 6, return message. if (password.length < 6)return 'Too short'; //length is ok, lets continue. //if length is 8 characters or more, increase strength value if (password.length >=6) strength += 1; //if password contains both lower and uppercase characters, increase strength value if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1; //if it has numbers and characters, increase strength value if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1 ; //if it has one special character, increase strength value if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1; //if it has two special characters, increase strength value if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1; //now we have calculated strength value, we can return messages //if value is less than 2 if ( strength ===1 ) return 'Weak'; else if (strength === 2 ) return 'Fair'; else if (strength === 3 ) return 'Good'; else if (strength === 4 ) return 'Strong'; else return 'Verry Strong'; } function backendloading(){$('#backendload').show()} function backendloaded(){$('#backendload').hide()} function ShowLoadding(){ $("#loaddingbar").show(); $("#loaddingbar div").stop(true).width(0).css({ bottom:1 }) .animate({ width:'30%' },500) .animate({ width:'50%' },1000) .animate({ width:'75%' },2000) .animate({ width:'95%' },5000); } function HideLoadding(){ $("#loaddingbar div").stop(true) .animate({ width:'100%' },1000,function(){ $("#loaddingbar").hide(); }); } function HideLoadding(){ $("#loaddingAjax .proccessbar").stop(true) .animate({ width:'100%', backgroundColor:"red" },500,function(){ $("#loaddingAjax").hide(); }); } function ErrorMsg(message){ //Msg(message,'Error !','0x08') Msg('<p style="color:red;border-bottom: 1px dotted #ccc;padding-bottom: 6px;">Error Message !!!</p><p>'+message+'</p>'); } function WarningMsg(message){ //Msg(message,'Warning !','0x12') Msg('<p style="color:orangered;border-bottom: 1px dotted #ccc;padding-bottom: 6px;">Warning Message !!</p><p>'+message+'</p>'); } function NoticeMsg(message){ //Msg(message) Msg('<p style="border-bottom: 1px dotted #ccc;padding-bottom: 6px;">Notice Message !!</p><p>'+message+'</p>'); } function Msg(message,title,type,timeout){ var msg,titcolor='border-bottom:1px solid #ccc;background-color:#efefef'; if($("#notications").length===0)$('body').append('<div id="notications"></div>'); if(title===undefined)title='Message'; if(type===undefined)type='0x00'; if(type!=='0x00'){ titcolor='color:#fff;'; msg = $('<div class="centerscreen grid_8 d-p-b m-t-4 d-'+type+'"><div class="p-r l-h-20 p-l-8 b-'+type+'" style="'+titcolor+'">'+title+'<span class="msgclose p-a t-2 r-2 w-16 h-16 l-h-16 c-s-p t-a-c t-d-n c-0xff h-c-0xff">×</span></div><div class="b-0xff t-a-j p-4 c-'+type+'">'+message+'</div></div>'); }else msg = $('<div class="notice-box m-t-4"><div>'+message+'</div><div onclick="destroy_parent(this)" class="c-s-p notice-box-close-btn"></div></div>') msg.appendTo("#notications").delay(1000) .animate({bottom:'0%',right:'0%',marginRight:0},2000,function(){ $(this).removeClass('centerscreen'); }); $('.msgclose',msg).click(function(){msg.remove();}); if(timeout!==undefined){ msg.delay(timeout) .animate({opacity:0},2000,function(){ $(this).remove(); }); } } function uiMessage(msg,title,type){ //NoticeMsg(msg);return; if($("#uiMessage").length===0){ $('body').append('\ <div id="uiMessage" onmouseover="stoptipui()" class="tranf-b-20 b-r-5 ui-corner-all d-p-n" style="position: fixed; left: 50%; top: 36px; padding: 8px;z-index: 99999;margin-left:-360px;">\ <div class="ui-dialog-content ui-widget-content p-8 o-v-f-h o-v-f-x-a f-z-11" style="min-width: 720px;" > \ </div>\ <div class="p-a t-8 r-8 w-16 h-16 c-s-p t-a-c a t-d-n" onclick="untipui()" style="">×</div>\ </div>\ '); } if($("#notications").length===0){ $('body').append('<div id="notications"></div>'); } if(title===undefined){ title='Message'; } $('<div class="centerscreen m-t-4 b-d-c-ccc b-g-c-w grid_8"><h4 class="p-4 b-d-b-c-ddd">'+title+'</h4><p class="p-4">'+msg+'</p></div>') .appendTo("#notications").delay(1000) .animate({bottom:'0%',right:'0%',marginRight:0},2000,function(){ $(this).removeClass('centerscreen'); }).delay(8000) .animate({opacity:0},2000,function(){ $(this).remove(); }); } function untipui(){ $("#uiMessage").stop().hide(); } function stoptipui(){ $("#uiMessage").stop().css({display:"block",opacity:1}); } function bckdialog(_option){ var me=this; this.option={ type : "notice",//notice,error,question,custom title : null, message : null, uidialog : $("#dialog-message"), icon : null, hideclose : false, autoOpen : false, minwidth : '320px', height : 'auto', dialogClass : '', proc_start : null, proc_end : null, onload : null, onclose : null, onopen : null, callback : null }; var option=this.option; if(_option){ //$.map(_option,function(value,key){ // option[key]=value; //}); $.each(_option,function(index,value){ option[index]=value; }); this.option=option; } if($("#bckdialog").length===0){ $('body').append('\ <span class="d-p-n">\ <div id="uiMessage" onmouseover="stoptipui()" class="tranf-b-20 b-r-5 ui-corner-all d-p-n" style="position: fixed; left: 50%; top: 36px; padding: 8px;z-index: 99999;margin-left:-360px;">\ <div class="ui-dialog-content ui-widget-content p-8 o-v-f-h o-v-f-x-a f-z-11" style="min-width: 720px;" > \ </div>\ <div class="p-a t-8 r-8 w-16 h-16 c-s-p t-a-c a t-d-n" onclick="untipui()" style="">×</div>\ </div>\ <div id="loadding-dialog" class="uidialog" title="Loadding...">Processing. Please, wait...</div>\ <div id="bckdialog" class="p-20" title="Notice Message !"></div>\ </span>\ '); } if(option.type==="notice"){ if(option.icon===null) option.icon="<img class='p-a t-7 l-8' src='"+base_url+"libraries/ui/themes/base/images/dialog_warning.png'/>"; option.title="<font class='p-l-20'>"+(option.title===null?"Notice Message !":option.title)+"</font>"; }else if(option.type==="error"){ if(option.icon===null) option.icon="<img class='p-a t-7 l-8' src='"+base_url+"libraries/ui/themes/base/images/dialog_error.png'/>"; option.title="<font class='p-l-20 erc'>"+(option.title===null?"Error Exception !":option.title)+"</font>"; } if(option.message===null || option.message ===undefined){ //$("#dialog-message").html("Message type must be String or HTML DOM Element !"); option.uidialog=$("#bckdialog"); }else if(typeof(option.message)==="object"){ option.uidialog=option.message; }else if(typeof(option.message)==="string"){ $("#bckdialog").html('<div class="p-20">'+option.message+'</div>'); option.uidialog=$("#bckdialog"); }else{ $("#bckdialog").html("Message type must be String or HTML DOM element !"); option.uidialog=$("#bckdialog"); } return { open:function(str){ if(str)$("#bckdialog").html('<div class="p-20">'+str+'</div>'); option.uidialog.dialog({ modal : true, //autoOpen : option.autoOpen, minwidth : option.minwidth, dialogClass :'b-s-d-32 pie '+option.dialogClass, resizable : false, width :'auto', title : option.icon + option.title, closeOnEscape : true, //hide : "explode", buttons : { }, open : function(event, ui) { if (option.onopen && typeof(option.onopen) === "function") { try{ option.onopen(); }catch(e){} } $(event.target).dialog('widget') .css({position: 'fixed'}) .position({my: 'center', at: 'center', of: window}); }, close : function(event, ui) { if (option.onclose && typeof(option.onclose) === "function") { try{ option.onclose(); }catch(e){} } }, create :function(){ if(option.hideclose===true){ $(this).closest(".ui-dialog") .find(".ui-dialog-titlebar-close") .hide(); } } }); }, close:function(){ option.uidialog.dialog('close'); } }; } function backend(_option){ var option={ url : null, data : null, datatype : "json", proc_start : null, proc_end : null, callback : null }; if(_option) $.each(_option,function(index,value){ option[index]=value; }); if(option.datatype.toUpperCase()==='JSON'){ option.data.ajaxtype='json'; } return { call:function(_url,_data,_callback){ if(isrunning===true)return; if(_url) option.url=_url; if(_data) option.data=_data; if(_callback) option.callback=_callback; if(typeof(option.proc_start)==='function')option.proc_start(); else{backendloading()} jQuery.ajax({ type:"POST", //cache:false, //timeout:10000, data:option.data, dataType:option.datatype, url:option.url, success: function (data_result){ isrunning=false; if(typeof(option.callback)==='function')option.callback(data_result); if(typeof(option.proc_end)==='function')option.proc_end(); else{backendloaded()} }, error: function (xhr, ajaxOptions, thrownError){ isrunning=false; if(typeof(option.proc_end)==='function')option.proc_end(); else{backendloaded()} ErrorMsg("Sorry. Your request could not be completed.<br/> Please check your input data and try again."); } }); } }; } function BrowseServer( elementid ) { if($(elementid).length===0)uiMessage("Input element is not exist."); try{ window.KCFinder = {}; window.KCFinder.callBack = function(url) { url=url.replace('/data/','') window.KCFinder = null; $(elementid).val(url); }; window.open( base_url+'libraries/kcfinder/browse.php?lang=vi', 'kcfinder_textbox', 'status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=1, scrollbars=0, width=700, height=500' ); }catch(e){ ErrorMsg(e.message); } } function addRedactorEditor(Element){ Element.redactor({ //air: true, //wym: true, buttons: ['html','formatting', '|', 'bold', 'italic', 'deleted', '|','unorderedlist','orderedlist','outdent','indent','alignment','|','video','link','|','fontcolor','backcolor'] , plugins: ['advanced'] }); } function addEditorContent(ElementID,height){ try{ tinyMCE.init({// <![CDATA[ // General options // document_base_url : "/", // relative_urls : true, // remove_script_host : true, language : 'en', mode : "exact", elements : ElementID, body_class : 'my-content', theme : "advanced", //skin : "o2k7", //skin_variant : "silver", //plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template", plugins : "backend,safari,pagebreak,autolink,lists,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,media,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras", noneditable_regexp: /\[\[[^\]]+\]\]/g, height :height?height:500, width : "100%", extended_valid_elements :'*[*]', relative_urls : false,inline_styles : true, // Theme options theme_advanced_buttons1 : "newdocument,undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,outdent,indent,|,formatselect,fontselect,fontsizeselect", theme_advanced_buttons2 : "forecolor,backcolor,styleprops,|,blockquote,link,unlink,|,hr,sub,sup,charmap,emotions,iespell,image,media,|,template,|,removeformat,visualaid,cleanup,help,code,fullscreen", theme_advanced_buttons3 : "tablecontrols,|,mysplitbutton", theme_advanced_buttons4 : "", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "bottom", theme_advanced_resizing : true, jquery_url : base_url + 'libraries/script/jquery-1.9.0.js', // Example content CSS (should be your site CSS) content_css : base_url + "libraries/typography/typography.css", // template_templates:[ // { // title : "Backend Tabs Editor", // src : base_url+"backend/template/tab.html", // description : "Backend Tabs Editor" // }, // { // title : "Win Tabs Editor", // src : base_url+"backend/template/wintab.html", // description : "Win Tabs Editor" // } // ], // Drop lists for link/image/media/template dialogs //template_external_list_url : "js/template_list.js", //external_link_list_url : "js/link_list.js", //external_image_list_url : "js/image_list.js", //media_external_list_url : "js/media_list.js", file_browser_callback: 'openKCFinder', setup :function(ed) { //ed.onInit.add(function(ed, evt) { // tinymce.ScriptLoader.add(tinyMCE.baseURL+"/../script/mcontent.jquery.js"); // tinymce.ScriptLoader.loadQueue(); //}); }// ]]> }); }catch(e){ ErrorMsg(e.message); } } function openKCFinder(field_name, url, type, win) { try{ tinyMCE.activeEditor.windowManager.open({ file: base_url + 'libraries/kcfinder/browse.php?opener=tinymce&type=' + type, title: 'KCFinder', width: 700, height: 500, resizable: "yes", inline: true, close_previous: "no", popup_css: false }, { window: win, input: field_name }); }catch(e){ ErrorMsg(e.message); } return false; } function proc_sart(elem){ $(".i-l-d",$(elem)) .addClass("b-g-c-w-50") .show(); } function proc_end(elem){ $(".i-l-d",$(elem)) .removeClass("b-g-c-w-50") .fadeOut(500); } function islc(opt){ try{ $(opt.element).multiselect({ multiple : opt.multi ? opt.multi : false, header : opt.header ? opt.header : opt.filter ? opt.filter : false, noneSelectedText: opt.title ? opt.title : (opt.multi?"Select an Option":"Select a Option"), selectedList : opt.num ? opt.num : 1, menuwidth : opt.menuwidth ? opt.menuwidth : null, minWidth : opt.minwidth ? opt.minwidth : 'auto',//$(opt.element).parent().width(), height : opt.height ? opt.height : 'auto', classes : opt.aclass ? opt.aclass : null, style : opt.style ? opt.style : null, biz : opt.biz ? opt.biz : null, beforeclose : function(){ try{ if($(this).hasClass("validate")){ if($(this).show().validationEngine('validate')){ $(this).multiselect("option",{classes:opt.multi?'_mul erb':null}); }else{ $(this).multiselect("option",{classes:opt.multi?'_mul':null}); } $(this).hide(); } }catch(e){ErrorMsg(e.message);} } }); if(opt.filter) $(opt.element).multiselectfilter(); }catch(e){ErrorMsg(e.message);} } function choosealbum(){ if($('#frm_backend_album').length===0){ $('body').append('<div id="frm_backend_album"><div id="frm_backend_album_box" class="grid_18 h-g-12 o-v-y-a"><p class="p-20">Loading...</p></div></div>'); } $('#frm_backend_album #frm_backend_album_box').load(base_url+'backend/plugin/choosealbum') var frmalbum=$('#frm_backend_album'); bckdialog({ title:'Backend Plugin - Album maker', message:frmalbum }).open(); } function BrowseServerCallBack(callback) { try{ window.KCFinder = {}; window.KCFinder.callBack = function(url) { url=url.replace(base_url+'0x4D/',''); window.KCFinder = null; callback(url); }; window.open( base_url + 'libraries/kcfinder/browse.php?lang=vi', 'kcfinder_textbox', 'status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=1, scrollbars=0, width=700, height=500' ); }catch(e){ ErrorMsg(e.message); } } function choosegalleria(){ alert('open album'); } function accessdenied(){ bckdialog({ title:'<font color="red">Access Denied</font>', icon:'<img class="p-a t-8 l-8 w-16 h-16" src="'+base_url+'libraries/images/16/denied.png">', message:'Access is denied.<br>This function to requires an administrative account.<br>Please check your authority, and try again.<br/><br/>\ <a class="t-d-n" href="'+base_url+'backend">&bull; Return home.</a><br/>\n\ <a class="t-d-n" href="'+base_url+'backend/auth/logout">&bull; Login with different user.</a><br/>' }).open(); } function backend_update(fun,table,prefix,_id,_data){ backend({ url : base_url+"backend/excution/update_backend/"+fun+"/"+table+"/"+prefix+"/"+_id, data : _data, callback : function(rsdata){ if(rsdata.result<0){ WarningMsg(rsdata.message); }else{ NoticeMsg(rsdata.message); } } }).call(); } function destroy_parent(elem){ $(elem).parent().remove(); } function AliasTo(from,element){ if($(from).val()==$(from+'_curent').val())return; var url=base_url+"backend/excution/getalias"; var data={text:$(from).val()}; var proc=new backend({ url:url,data:data, callback:function(rsdata){ if(rsdata.result===1){ $(element).val(rsdata.alias); $(from+'_curent').val($(from).val()); }else{ WarningMsg(rsdata.message); } } }).call(); } $(document).ready(function(){ if($("#bckdialog").length===0){ $('body').append('\ <span class="d-p-n">\ <div id="loadding-dialog" class="uidialog" title="Loadding...">Processing. Please, wait...</div>\ <div id="bckdialog" class="p-20" title="Notice Message !"></div>\ </span>\ '); } });
JavaScript
/* Project : 48c6c450f1a4a0cc53d9585dc0fee742 Created on : Mar 16, 2013, 11:29:15 PM Author : Truong Khuong - khuongxuantruong@gmail.com Description : Purpose of the stylesheet follows. */ var menu=(function(){ return{ AddItem:function(){ $('#gridview').hide(); $('#detail').show(); _detail(''); }, EditItem:function(type){ try{ //var cells = $("#jqxGrid").jqxGrid('getselectedcells'); var rowindex = $('#jqxGrid').jqxGrid('getselectedrowindex'); var _id=undefined,url,data,obj; if(rowindex>-1){ var _dataRow=$("#jqxGrid").jqxGrid('getrowdata', rowindex); _id=_dataRow._id===undefined?(_dataRow.ID===undefined?_dataRow.ProductID:_dataRow.ID):_dataRow._id; if(_id!==undefined){ if(_id !== $("#news_id").val()){ _detail(_id); }else{ $(".frmjqxgrid").hide(); $(".frmeditting").show(); $(".group-events.g").hide(); $(".group-events.e").show(); } }else{ uiMessage("Row ID is not defined."); } }else{ uiMessage("No row selected. Please select one or more rows."); } }catch(e){ uiMessage(e.message); } }, Save:function(){ tinyMCE.triggerSave(false,false); if( $('#news_frm').validationEngine('validate') === false)return; new backend({ url : base_url+"admincp/content/save", data : $('#news_frm').serialize(), callback : function(data){ if(data.result<0){ new bckdialog({type:'error'}).open(data.message); }else{ uiMessage(data.message); $('#gridview').show(); $('#detail').hide(); $(".group-events.e").hide(); $(".group-events.g").show(); $("#jqxGrid").jqxGrid('updatebounddata'); } console.log(data); } }).call(); }, Cancel:function(){ $('#gridview').show(); $('#detail').hide(); $(".group-events.e").hide(); $(".group-events.g").show(); }, DeleteItem:function(){ }, RestoreItem:function(){ }, PublicItem:function(){ }, PrivateItem:function(){ }, Setting:function(){ bckdialog({ message:$('#window-sOpt'), icon:"<img class='p-a t-7 l-8' src='/libraries/images/16/option.gif'/>", title:'Setting' }).open(); }, Refresh:function(){ $("#jqxGrid").jqxGrid('updatebounddata'); } }; }()); function handleEvents(){ try{ // $("#jqxGrid").bind('rowselect', function (event) { // var rowData=$("#jqxGrid").jqxGrid('getrowdata', event.args.rowindex); // var ID = rowData._id; // $("#detail").load(base_url + "admincp/permission/detail/"+ID); // console.log(rowData); // }); }catch(e){ tipMessage(e.message); } } $(document).ready(function () { });
JavaScript
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ function cust_reg(){ if( $('#cust_frm').validationEngine('validate') === false)return false; new backend({ url : "/excution/addcustomer", data : $('#cust_frm').serialize(), callback : function(data){ if(data.result<0){ $('#cust_frm_err').html(data.message); }else{ document.cust_frm.reset(); $('#cust_frm_err').html('Đăng ký thành công.'); login(); } console.log(data); } }).call(); return false; } function cust_login(){ if( $('#login_frm').validationEngine('validate') === false)return false; new backend({ url : "/excution/custlogin", data : $('#login_frm').serialize(), callback : function(data){ if(data.result<0){ $('#login_frm_err').html(data.message); }else{ document.login_frm.reset(); $('#login_frm_err').html('Đăng nhập thành công.'); window.location.reload(); } console.log(data); } }).call(); return false; } function reg(){ $('.jfk-bubble.regfrm').toggle(); $('.jfk-bubble.loginfrm').hide() } function login(){ $('.jfk-bubble.loginfrm').toggle(); $('.jfk-bubble.regfrm').hide() } $(document).ready(function(){ $('.services a div').hover(function(){ $(this).stop().animate({top:'-172px'},200); //$(this).css({'background-position-y:':'-172px'}); console.log('a'); },function(){ $(this).stop().animate({top:'0px'},200); }); $('#cust_frm').validationEngine(); $('#login_frm').validationEngine(); try{ $('.cycleSlider').cycle({ timeout: 3000 , pager: '#cycleNav', activePagerClass:'active', pagerAnchorBuilder: function(idx, slide) { return '<a href="#">'+idx+'</a>'; } }); }catch(e){} Galleria.configure({ transition: 'pulse', thumbCrop: 'width', imageCrop: false, carousel: false, show: false, easing: 'galleriaOut', fullscreenDoubleTap: false, trueFullscreen: false, imageMargin: 50 }); //Galleria.loadTheme('/libraries/galleria/themes/folio/galleria.folio.min.js'); //$('.fontend_album.classic_album').css({height:300,width:'100%'}); //Galleria.run('.fontend_album.classic_album'); //theme : classic, azur, folio, twelve //‘fade’ crossfade betweens images //‘flash’ fades into background color between images //‘pulse’ quickly removes the image into background color, then fades the next image //‘slide’ slides the images depending on image position //‘fadeslide’ fade between images and slide slightly at the same time });
JavaScript
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, boss:true, undef:true, curly:true, browser:true, jquery:true */ /* * jQuery MultiSelect UI Widget 1.14pre * Copyright (c) 2012 Eric Hynds * * http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/ * * Depends: * - jQuery 1.4.2+ * - jQuery UI 1.8 widget factory * * Optional: * - jQuery UI effects * - jQuery UI position utility * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ (function($, undefined) { var multiselectID = 0; var $doc = $(document); $.widget("ech.multiselect", { // default options options: { header: true, height: 175, minWidth: 224, //menuwidth: 224, classes: '', checkAllText: 'Check all', uncheckAllText: 'Uncheck all', noneSelectedText: 'Select options', selectedText: '# selected', selectedList: 0, show : null, hide : null, autoOpen : false, multiple : true, position : {}, style :{} }, _create: function() { var el = this.element.hide(); var o = this.options; this.speed = $.fx.speeds._default; // default speed for effects this._isOpen = false; // assume no // create a unique namespace for events that the widget // factory cannot unbind automatically. Use eventNamespace if on // jQuery UI 1.9+, and otherwise fallback to a custom string. this._namespaceID = this.eventNamespace || ('multiselect' + multiselectID); var button = (this.button = $('<div><span class="ui-icon ui-icon-triangle-1-s"></span></div>')) .addClass('ui-multiselect ui-widget ui-state-default ui-corner-all') .addClass(o.classes) .attr({ 'title':el.attr('title'), 'aria-haspopup':true, 'tabIndex':el.attr('tabIndex') }) .insertBefore(el), buttonlabel = (this.buttonlabel = $('<span />')) .html(o.noneSelectedText) .appendTo(button), menu = (this.menu = $('<div />')) .addClass('ui-multiselect-menu ui-widget ui-widget-content ui-corner-all') .addClass(o.classes) .appendTo(document.body), header = (this.header = $('<div />')) .addClass('ui-widget-header ui-corner-all ui-multiselect-header ui-helper-clearfix') .appendTo(menu), headerLinkContainer = (this.headerLinkContainer = $('<ul />')) .addClass('ui-helper-reset') .html(function() { if(o.header === true) { return '<li><a class="ui-multiselect-all" href="#"><span class="ui-icon ui-icon-check"></span><span>' + o.checkAllText + '</span></a></li><li><a class="ui-multiselect-none" href="#"><span class="ui-icon ui-icon-closethick"></span><span>' + o.uncheckAllText + '</span></a></li>'; } else if(typeof o.header === "string") { return '<li>' + o.header + '</li>'; } else { return ''; } }) .append('<li class="ui-multiselect-close"><a href="#" class="ui-multiselect-close"><span class="ui-icon ui-icon-circle-close"></span></a></li>') .appendTo(header), checkboxContainer = (this.checkboxContainer = $('<ul />')) .addClass('ui-multiselect-checkboxes ui-helper-reset') .appendTo(menu); if(o.biz) menu.addClass("m-w-a"); // perform event bindings this._bindEvents(); // build menu this.refresh(true); // some addl. logic for single selects if(!o.multiple) { menu.addClass('ui-multiselect-single'); } if(o.style) menu.css(o.style); // bump unique ID multiselectID++; }, _init: function() { if(this.options.header === false) { this.header.hide(); } if(!this.options.multiple) { this.headerLinkContainer.find('.ui-multiselect-all, .ui-multiselect-none').hide(); } if(this.options.autoOpen) { this.open(); } if(this.element.is(':disabled')) { this.disable(); } }, refresh: function(init) { var el = this.element; var o = this.options; var menu = this.menu; var checkboxContainer = this.checkboxContainer; var optgroups = []; var html = ""; var id = el.attr('id') || multiselectID++; // unique ID for the label & option tags // build items el.find('option').each(function(i) { var $this = $(this); var parent = this.parentNode; var title = this.innerHTML; var description = this.title; var value = this.value; var inputID = 'ui-multiselect-' + (this.id || id + '-option-' + i); var isDisabled = this.disabled; var isSelected = this.selected; var labelClasses = [ 'ui-corner-all' ]; var liClasses = (isDisabled ? 'ui-multiselect-disabled ' : ' ') + this.className; var optLabel; // is this an optgroup? if(parent.tagName === 'OPTGROUP') { optLabel = parent.getAttribute('label'); // has this optgroup been added already? if($.inArray(optLabel, optgroups) === -1) { html += '<li class="ui-multiselect-optgroup-label ' + parent.className + '"><a href="#">' + optLabel + '</a></li>'; optgroups.push(optLabel); } } if(isDisabled) { labelClasses.push('ui-state-disabled'); } // browsers automatically select the first option // by default with single selects if(isSelected && !o.multiple) { labelClasses.push('ui-state-active'); } html += '<li class="' + liClasses + '">'; // create the label html += '<label for="' + inputID + '" title="' + description + '" class="' + labelClasses.join(' ') + '">'; html += '<input id="' + inputID + '" name="multiselect_' + id + '" type="' + (o.multiple ? "checkbox" : "radio") + '" value="' + value + '" title="' + title + '"'; // pre-selected? if(isSelected) { html += ' checked="checked"'; html += ' aria-selected="true"'; } // disabled? if(isDisabled) { html += ' disabled="disabled"'; html += ' aria-disabled="true"'; } // add the title and close everything off html += ' /><span>' + title + '</span></label></li>'; }); // insert into the DOM checkboxContainer.html(html); // cache some moar useful elements this.labels = menu.find('label'); this.inputs = this.labels.children('input'); // set widths this._setButtonWidth(); this._setMenuWidth(); // remember default value this.button[0].defaultValue = this.update(); // broadcast refresh event; useful for widgets if(!init) { this._trigger('refresh'); } }, // updates the button text. call refresh() to rebuild update: function() { var o = this.options; var $inputs = this.inputs; var $checked = $inputs.filter(':checked'); var numChecked = $checked.length; var value; if(numChecked === 0) { value = o.noneSelectedText; } else { if($.isFunction(o.selectedText)) { value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get()); } else if(/\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList) { value = $checked.map(function() { return $(this).next().html(); }).get().join(', '); } else { value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length); } } this._setButtonValue(value); return value; }, // this exists as a separate method so that the developer // can easily override it. _setButtonValue: function(value) { this.buttonlabel.text(value); }, // binds events _bindEvents: function() { var self = this; var button = this.button; function clickHandler() { self[ self._isOpen ? 'close' : 'open' ](); return false; } // webkit doesn't like it when you click on the span :( button .find('span') .bind('click.multiselect', clickHandler); // button events button.bind({ click: clickHandler, keypress: function(e) { switch(e.which) { case 27: // esc case 38: // up case 37: // left self.close(); break; case 39: // right case 40: // down self.open(); break; } }, mouseenter: function() { if(!button.hasClass('ui-state-disabled')) { $(this).addClass('ui-state-hover'); } }, mouseleave: function() { $(this).removeClass('ui-state-hover'); }, focus: function() { if(!button.hasClass('ui-state-disabled')) { $(this).addClass('ui-state-focus'); } }, blur: function() { $(this).removeClass('ui-state-focus'); } }); // header links this.header.delegate('a', 'click.multiselect', function(e) { // close link if($(this).hasClass('ui-multiselect-close')) { self.close(); // check all / uncheck all } else { self[$(this).hasClass('ui-multiselect-all') ? 'checkAll' : 'uncheckAll'](); } e.preventDefault(); }); // optgroup label toggle support this.menu.delegate('li.ui-multiselect-optgroup-label a', 'click.multiselect', function(e) { e.preventDefault(); var $this = $(this); var $inputs = $this.parent().nextUntil('li.ui-multiselect-optgroup-label').find('input:visible:not(:disabled)'); var nodes = $inputs.get(); var label = $this.parent().text(); // trigger event and bail if the return is false if(self._trigger('beforeoptgrouptoggle', e, { inputs:nodes, label:label }) === false) { return; } // toggle inputs self._toggleChecked( $inputs.filter(':checked').length !== $inputs.length, $inputs ); self._trigger('optgrouptoggle', e, { inputs: nodes, label: label, checked: nodes[0].checked }); }) .delegate('label', 'mouseenter.multiselect', function() { if(!$(this).hasClass('ui-state-disabled')) { self.labels.removeClass('ui-state-hover'); $(this).addClass('ui-state-hover').find('input').focus(); } }) .delegate('label', 'keydown.multiselect', function(e) { e.preventDefault(); switch(e.which) { case 9: // tab case 27: // esc self.close(); break; case 38: // up case 40: // down case 37: // left case 39: // right self._traverse(e.which, this); break; case 13: // enter $(this).find('input')[0].click(); break; } }) .delegate('input[type="checkbox"], input[type="radio"]', 'click.multiselect', function(e) { var $this = $(this); var val = this.value; var checked = this.checked; var tags = self.element.find('option'); // bail if this input is disabled or the event is cancelled if(this.disabled || self._trigger('click', e, { value: val, text: this.title, checked: checked }) === false) { e.preventDefault(); return; } // make sure the input has focus. otherwise, the esc key // won't close the menu after clicking an item. $this.focus(); // toggle aria state $this.attr('aria-selected', checked); // change state on the original option tags tags.each(function() { if(this.value === val) { this.selected = checked; } else if(!self.options.multiple) { this.selected = false; } }); // some additional single select-specific logic if(!self.options.multiple) { self.labels.removeClass('ui-state-active'); $this.closest('label').toggleClass('ui-state-active', checked); // close menu self.close(); } // fire change on the select box self.element.trigger("change"); // setTimeout is to fix multiselect issue #14 and #47. caused by jQuery issue #3827 // http://bugs.jquery.com/ticket/3827 setTimeout($.proxy(self.update, self), 10); }); // close each widget when clicking on any other element/anywhere else on the page $doc.bind('mousedown.' + this._namespaceID, function(event) { var target = event.target; if(self._isOpen && !$.contains(self.menu[0], target) && !$.contains(self.button[0], target) && target !== self.button[0] && target !== self.menu[0]) { self.close(); } }); // deal with form resets. the problem here is that buttons aren't // restored to their defaultValue prop on form reset, and the reset // handler fires before the form is actually reset. delaying it a bit // gives the form inputs time to clear. $(this.element[0].form).bind('reset.multiselect', function() { setTimeout($.proxy(self.refresh, self), 10); }); }, // set button width _setButtonWidth: function() { var width = this.element.outerWidth(); var o = this.options; if(/\d/.test(o.minWidth) && width < o.minWidth) { width = o.minWidth; } // set widths this.button.outerWidth(width); }, // set menu width _setMenuWidth: function() { var w=this.button.outerWidth(); try{ if( this.options.menuwidth){ if( this.options.menuwidth == 'auto' ) if(this.menu.outerWidth()>w) w=this.options.menuwidth; else w=this.options.menuwidth; } }catch(e){ } var m = this.menu; m.outerWidth(w); }, // move up or down within the menu _traverse: function(which, start) { var $start = $(start); var moveToLast = which === 38 || which === 37; // select the first li that isn't an optgroup label / disabled $next = $start.parent()[moveToLast ? 'prevAll' : 'nextAll']('li:not(.ui-multiselect-disabled, .ui-multiselect-optgroup-label)')[ moveToLast ? 'last' : 'first'](); // if at the first/last element if(!$next.length) { var $container = this.menu.find('ul').last(); // move to the first/last this.menu.find('label')[ moveToLast ? 'last' : 'first' ]().trigger('mouseover'); // set scroll position $container.scrollTop(moveToLast ? $container.height() : 0); } else { $next.find('label').trigger('mouseover'); } }, // This is an internal function to toggle the checked property and // other related attributes of a checkbox. // // The context of this function should be a checkbox; do not proxy it. _toggleState: function(prop, flag) { return function() { if(!this.disabled) { this[ prop ] = flag; } if(flag) { this.setAttribute('aria-selected', true); } else { this.removeAttribute('aria-selected'); } }; }, _toggleChecked: function(flag, group) { var $inputs = (group && group.length) ? group : this.inputs; var self = this; // toggle state on inputs $inputs.each(this._toggleState('checked', flag)); // give the first input focus $inputs.eq(0).focus(); // update button text this.update(); // gather an array of the values that actually changed var values = $inputs.map(function() { return this.value; }).get(); // toggle state on original option tags this.element .find('option') .each(function() { if(!this.disabled && $.inArray(this.value, values) > -1) { self._toggleState('selected', flag).call(this); } }); // trigger the change event on the select if($inputs.length) { this.element.trigger("change"); } }, _toggleDisabled: function(flag) { this.button.attr({ 'disabled':flag, 'aria-disabled':flag })[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled'); var inputs = this.menu.find('input'); var key = "ech-multiselect-disabled"; if(flag) { // remember which elements this widget disabled (not pre-disabled) // elements, so that they can be restored if the widget is re-enabled. inputs = inputs.filter(':enabled').data(key, true) } else { inputs = inputs.filter(function() { return $.data(this, key) === true; }).removeData(key); } inputs .attr({ 'disabled':flag, 'arial-disabled':flag }) .parent()[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled'); this.element.attr({ 'disabled':flag, 'aria-disabled':flag }); }, // open the menu open: function(e) { var self = this; var button = this.button; var menu = this.menu; var speed = this.speed; var o = this.options; var args = []; // bail if the multiselectopen event returns false, this widget is disabled, or is already open if(this._trigger('beforeopen') === false || button.hasClass('ui-state-disabled') || this._isOpen) { return; } var $container = menu.find('ul').last(); var effect = o.show; // figure out opening effects/speeds if($.isArray(o.show)) { effect = o.show[0]; speed = o.show[1] || self.speed; } // if there's an effect, assume jQuery UI is in use // build the arguments to pass to show() if(effect) { args = [ effect, speed ]; } // set the scroll of the checkbox container $container.scrollTop(0).height(o.height); // positon this.position(); // show the menu, maybe with a speed/effect combo $.fn.show.apply(menu, args); // select the first not disabled option // triggering both mouseover and mouseover because 1.4.2+ has a bug where triggering mouseover // will actually trigger mouseenter. the mouseenter trigger is there for when it's eventually fixed this.labels.filter(':not(.ui-state-disabled)').eq(0).trigger('mouseover').trigger('mouseenter').find('input').trigger('focus'); button.addClass('ui-state-active'); this._isOpen = true; this._trigger('open'); }, // close the menu close: function() { if(this._trigger('beforeclose') === false) { return; } var o = this.options; var effect = o.hide; var speed = this.speed; var args = []; // figure out opening effects/speeds if($.isArray(o.hide)) { effect = o.hide[0]; speed = o.hide[1] || this.speed; } if(effect) { args = [ effect, speed ]; } $.fn.hide.apply(this.menu, args); this.button.removeClass('ui-state-active').trigger('blur').trigger('mouseleave'); this._isOpen = false; this._trigger('close'); }, enable: function() { this._toggleDisabled(false); }, disable: function() { this._toggleDisabled(true); }, checkAll: function(e) { this._toggleChecked(true); this._trigger('checkAll'); }, uncheckAll: function() { this._toggleChecked(false); this._trigger('uncheckAll'); }, getChecked: function() { return this.menu.find('input').filter(':checked'); }, destroy: function() { // remove classes + data $.Widget.prototype.destroy.call(this); // unbind events $doc.unbind(this._namespaceID); this.button.remove(); this.menu.remove(); this.element.show(); return this; }, isOpen: function() { return this._isOpen; }, widget: function() { return this.menu; }, getButton: function() { return this.button; }, position: function() { var o = this.options; // use the position utility if it exists and options are specifified if($.ui.position && !$.isEmptyObject(o.position)) { o.position.of = o.position.of || this.button; this.menu .show() .position(o.position) .hide(); // otherwise fallback to custom positioning } else { var pos = this.button.offset(); this.menu.css({ top: pos.top + this.button.outerHeight(), left: pos.left }); } }, // react to option changes after initialization _setOption: function(key, value) { var menu = this.menu; switch(key) { case 'header': menu.find('div.ui-multiselect-header')[value ? 'show' : 'hide'](); break; case 'checkAllText': menu.find('a.ui-multiselect-all span').eq(-1).text(value); break; case 'uncheckAllText': menu.find('a.ui-multiselect-none span').eq(-1).text(value); break; case 'height': menu.find('ul').last().height(parseInt(value, 10)); break; case 'minWidth': this.options[key] = parseInt(value, 10); this._setButtonWidth(); this._setMenuWidth(); break; case 'selectedText': case 'selectedList': case 'noneSelectedText': this.options[key] = value; // these all needs to update immediately for the update() call this.update(); break; case 'classes': menu.add(this.button).removeClass(this.options.classes).addClass(value); break; case 'multiple': menu.toggleClass('ui-multiselect-single', !value); this.options.multiple = value; this.element[0].multiple = value; this.refresh(); break; case 'position': this.position(); break; } $.Widget.prototype._setOption.apply(this, arguments); } }); })(jQuery);
JavaScript
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, boss:true, undef:true, curly:true, browser:true, jquery:true */ /* * jQuery MultiSelect UI Widget Filtering Plugin 1.5pre * Copyright (c) 2012 Eric Hynds * * http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/ * * Depends: * - jQuery UI MultiSelect widget * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ (function($) { var rEscape = /[\-\[\]{}()*+?.,\\\^$|#\s]/g; $.widget('ech.multiselectfilter', { options: { label: 'Filter:', width: null, /* override default width set in css file (px). null will inherit */ placeholder: 'Enter keywords', autoReset: false }, _create: function() { var opts = this.options; var elem = $(this.element); // get the multiselect instance var instance = (this.instance = (elem.data('echMultiselect') || elem.data("multiselect"))); // store header; add filter class so the close/check all/uncheck all links can be positioned correctly var header = (this.header = instance.menu.find('.ui-multiselect-header').addClass('ui-multiselect-hasfilter')); // wrapper elem var wrapper = (this.wrapper = $('<div class="ui-multiselect-filter">' + (opts.label.length ? opts.label : '') + '<input placeholder="'+opts.placeholder+'" type="search"' + (/\d/.test(opts.width) ? 'style="width:'+opts.width+'px"' : '') + ' /></div>').prependTo(this.header)); // reference to the actual inputs this.inputs = instance.menu.find('input[type="checkbox"], input[type="radio"]'); // build the input box this.input = wrapper.find('input').bind({ keydown: function(e) { // prevent the enter key from submitting the form / closing the widget if(e.which === 13) { e.preventDefault(); } }, keyup: $.proxy(this._handler, this), click: $.proxy(this._handler, this) }); // cache input values for searching this.updateCache(); // rewrite internal _toggleChecked fn so that when checkAll/uncheckAll is fired, // only the currently filtered elements are checked instance._toggleChecked = function(flag, group) { var $inputs = (group && group.length) ? group : this.labels.find('input'); var _self = this; // do not include hidden elems if the menu isn't open. var selector = instance._isOpen ? ':disabled, :hidden' : ':disabled'; $inputs = $inputs .not(selector) .each(this._toggleState('checked', flag)); // update text this.update(); // gather an array of the values that actually changed var values = $inputs.map(function() { return this.value; }).get(); // select option tags this.element.find('option').filter(function() { if(!this.disabled && $.inArray(this.value, values) > -1) { _self._toggleState('selected', flag).call(this); } }); // trigger the change event on the select if($inputs.length) { this.element.trigger('change'); } }; // rebuild cache when multiselect is updated var doc = $(document).bind('multiselectrefresh', $.proxy(function() { this.updateCache(); this._handler(); }, this)); // automatically reset the widget on close? if(this.options.autoReset) { doc.bind('multiselectclose', $.proxy(this._reset, this)); } }, // thx for the logic here ben alman _handler: function(e) { var term = $.trim(this.input[0].value.toLowerCase()), // speed up lookups rows = this.rows, inputs = this.inputs, cache = this.cache; if(!term) { rows.show(); } else { rows.hide(); var regex = new RegExp(term.replace(rEscape, "\\$&"), 'gi'); this._trigger("filter", e, $.map(cache, function(v, i) { if(v.search(regex) !== -1) { rows.eq(i).show(); return inputs.get(i); } return null; })); } // show/hide optgroups this.instance.menu.find(".ui-multiselect-optgroup-label").each(function() { var $this = $(this); var isVisible = $this.nextUntil('.ui-multiselect-optgroup-label').filter(function() { return $.css(this, "display") !== 'none'; }).length; $this[isVisible ? 'show' : 'hide'](); }); }, _reset: function() { this.input.val('').trigger('keyup'); }, updateCache: function() { // each list item this.rows = this.instance.menu.find(".ui-multiselect-checkboxes li:not(.ui-multiselect-optgroup-label)"); // cache this.cache = this.element.children().map(function() { var elem = $(this); // account for optgroups if(this.tagName.toLowerCase() === "optgroup") { elem = elem.children(); } return elem.map(function() { return this.innerHTML.toLowerCase(); }).get(); }).get(); }, widget: function() { return this.wrapper; }, destroy: function() { $.Widget.prototype.destroy.call(this); this.input.val('').trigger("keyup"); this.wrapper.remove(); } }); })(jQuery);
JavaScript
/* PIE: CSS3 rendering for IE Version 1.0.0 http://css3pie.com Dual-licensed for use under the Apache License Version 2.0 or the General Public License (GPL) Version 2. */ (function(){ var doc = document;var PIE = window['PIE']; if( !PIE ) { PIE = window['PIE'] = { CSS_PREFIX: '-pie-', STYLE_PREFIX: 'Pie', CLASS_PREFIX: 'pie_', tableCellTags: { 'TD': 1, 'TH': 1 }, /** * Lookup table of elements which cannot take custom children. */ childlessElements: { 'TABLE':1, 'THEAD':1, 'TBODY':1, 'TFOOT':1, 'TR':1, 'INPUT':1, 'TEXTAREA':1, 'SELECT':1, 'OPTION':1, 'IMG':1, 'HR':1 }, /** * Elements that can receive user focus */ focusableElements: { 'A':1, 'INPUT':1, 'TEXTAREA':1, 'SELECT':1, 'BUTTON':1 }, /** * Values of the type attribute for input elements displayed as buttons */ inputButtonTypes: { 'submit':1, 'button':1, 'reset':1 }, emptyFn: function() {} }; // Force the background cache to be used. No reason it shouldn't be. try { doc.execCommand( 'BackgroundImageCache', false, true ); } catch(e) {} (function() { /* * IE version detection approach by James Padolsey, with modifications -- from * http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/ */ var ieVersion = 4, div = doc.createElement('div'), all = div.getElementsByTagName('i'), shape; while ( div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->', all[0] ) {} PIE.ieVersion = ieVersion; // Detect IE6 if( ieVersion === 6 ) { // IE6 can't access properties with leading dash, but can without it. PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' ); } PIE.ieDocMode = doc.documentMode || PIE.ieVersion; // Detect VML support (a small number of IE installs don't have a working VML engine) div.innerHTML = '<v:shape adj="1"/>'; shape = div.firstChild; shape.style['behavior'] = 'url(#default#VML)'; PIE.supportsVML = (typeof shape['adj'] === "object"); }()); /** * Utility functions */ (function() { var vmlCreatorDoc, idNum = 0, imageSizes = {}; PIE.Util = { /** * To create a VML element, it must be created by a Document which has the VML * namespace set. Unfortunately, if you try to add the namespace programatically * into the main document, you will get an "Unspecified error" when trying to * access document.namespaces before the document is finished loading. To get * around this, we create a DocumentFragment, which in IE land is apparently a * full-fledged Document. It allows adding namespaces immediately, so we add the * namespace there and then have it create the VML element. * @param {string} tag The tag name for the VML element * @return {Element} The new VML element */ createVmlElement: function( tag ) { var vmlPrefix = 'css3vml'; if( !vmlCreatorDoc ) { vmlCreatorDoc = doc.createDocumentFragment(); vmlCreatorDoc.namespaces.add( vmlPrefix, 'urn:schemas-microsoft-com:vml' ); } return vmlCreatorDoc.createElement( vmlPrefix + ':' + tag ); }, /** * Generate and return a unique ID for a given object. The generated ID is stored * as a property of the object for future reuse. * @param {Object} obj */ getUID: function( obj ) { return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + ++idNum ); }, /** * Simple utility for merging objects * @param {Object} obj1 The main object into which all others will be merged * @param {...Object} var_args Other objects which will be merged into the first, in order */ merge: function( obj1 ) { var i, len, p, objN, args = arguments; for( i = 1, len = args.length; i < len; i++ ) { objN = args[i]; for( p in objN ) { if( objN.hasOwnProperty( p ) ) { obj1[ p ] = objN[ p ]; } } } return obj1; }, /** * Execute a callback function, passing it the dimensions of a given image once * they are known. * @param {string} src The source URL of the image * @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known * @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function */ withImageSize: function( src, func, ctx ) { var size = imageSizes[ src ], img, queue; if( size ) { // If we have a queue, add to it if( Object.prototype.toString.call( size ) === '[object Array]' ) { size.push( [ func, ctx ] ); } // Already have the size cached, call func right away else { func.call( ctx, size ); } } else { queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue img = new Image(); img.onload = function() { size = imageSizes[ src ] = { w: img.width, h: img.height }; for( var i = 0, len = queue.length; i < len; i++ ) { queue[ i ][ 0 ].call( queue[ i ][ 1 ], size ); } img.onload = null; }; img.src = src; } } }; })();/** * Utility functions for handling gradients */ PIE.GradientUtil = { getGradientMetrics: function( el, width, height, gradientInfo ) { var angle = gradientInfo.angle, startPos = gradientInfo.gradientStart, startX, startY, endX, endY, startCornerX, startCornerY, endCornerX, endCornerY, deltaX, deltaY, p, UNDEF; // Find the "start" and "end" corners; these are the corners furthest along the gradient line. // This is used below to find the start/end positions of the CSS3 gradient-line, and also in finding // the total length of the VML rendered gradient-line corner to corner. function findCorners() { startCornerX = ( angle >= 90 && angle < 270 ) ? width : 0; startCornerY = angle < 180 ? height : 0; endCornerX = width - startCornerX; endCornerY = height - startCornerY; } // Normalize the angle to a value between [0, 360) function normalizeAngle() { while( angle < 0 ) { angle += 360; } angle = angle % 360; } // Find the start and end points of the gradient if( startPos ) { startPos = startPos.coords( el, width, height ); startX = startPos.x; startY = startPos.y; } if( angle ) { angle = angle.degrees(); normalizeAngle(); findCorners(); // If no start position was specified, then choose a corner as the starting point. if( !startPos ) { startX = startCornerX; startY = startCornerY; } // Find the end position by extending a perpendicular line from the gradient-line which // intersects the corner opposite from the starting corner. p = PIE.GradientUtil.perpendicularIntersect( startX, startY, angle, endCornerX, endCornerY ); endX = p[0]; endY = p[1]; } else if( startPos ) { // Start position but no angle specified: find the end point by rotating 180deg around the center endX = width - startX; endY = height - startY; } else { // Neither position nor angle specified; create vertical gradient from top to bottom startX = startY = endX = 0; endY = height; } deltaX = endX - startX; deltaY = endY - startY; if( angle === UNDEF ) { // Get the angle based on the change in x/y from start to end point. Checks first for horizontal // or vertical angles so they get exact whole numbers rather than what atan2 gives. angle = ( !deltaX ? ( deltaY < 0 ? 90 : 270 ) : ( !deltaY ? ( deltaX < 0 ? 180 : 0 ) : -Math.atan2( deltaY, deltaX ) / Math.PI * 180 ) ); normalizeAngle(); findCorners(); } return { angle: angle, startX: startX, startY: startY, endX: endX, endY: endY, startCornerX: startCornerX, startCornerY: startCornerY, endCornerX: endCornerX, endCornerY: endCornerY, deltaX: deltaX, deltaY: deltaY, lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY ) } }, /** * Find the point along a given line (defined by a starting point and an angle), at which * that line is intersected by a perpendicular line extending through another point. * @param x1 - x coord of the starting point * @param y1 - y coord of the starting point * @param angle - angle of the line extending from the starting point (in degrees) * @param x2 - x coord of point along the perpendicular line * @param y2 - y coord of point along the perpendicular line * @return [ x, y ] */ perpendicularIntersect: function( x1, y1, angle, x2, y2 ) { // Handle straight vertical and horizontal angles, for performance and to avoid // divide-by-zero errors. if( angle === 0 || angle === 180 ) { return [ x2, y1 ]; } else if( angle === 90 || angle === 270 ) { return [ x1, y2 ]; } else { // General approach: determine the Ax+By=C formula for each line (the slope of the second // line is the negative inverse of the first) and then solve for where both formulas have // the same x/y values. var a1 = Math.tan( -angle * Math.PI / 180 ), c1 = a1 * x1 - y1, a2 = -1 / a1, c2 = a2 * x2 - y2, d = a2 - a1, endX = ( c2 - c1 ) / d, endY = ( a1 * c2 - a2 * c1 ) / d; return [ endX, endY ]; } }, /** * Find the distance between two points * @param {Number} p1x * @param {Number} p1y * @param {Number} p2x * @param {Number} p2y * @return {Number} the distance */ distance: function( p1x, p1y, p2x, p2y ) { var dx = p2x - p1x, dy = p2y - p1y; return Math.abs( dx === 0 ? dy : dy === 0 ? dx : Math.sqrt( dx * dx + dy * dy ) ); } };/** * */ PIE.Observable = function() { /** * List of registered observer functions */ this.observers = []; /** * Hash of function ids to their position in the observers list, for fast lookup */ this.indexes = {}; }; PIE.Observable.prototype = { observe: function( fn ) { var id = PIE.Util.getUID( fn ), indexes = this.indexes, observers = this.observers; if( !( id in indexes ) ) { indexes[ id ] = observers.length; observers.push( fn ); } }, unobserve: function( fn ) { var id = PIE.Util.getUID( fn ), indexes = this.indexes; if( id && id in indexes ) { delete this.observers[ indexes[ id ] ]; delete indexes[ id ]; } }, fire: function() { var o = this.observers, i = o.length; while( i-- ) { o[ i ] && o[ i ](); } } };/* * Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not * always firing the onmove and onresize events when elements are moved or resized. We check a few * times every second to make sure the elements have the correct position and size. See Element.js * which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9 * and false elsewhere. */ PIE.Heartbeat = new PIE.Observable(); PIE.Heartbeat.run = function() { var me = this, interval; if( !me.running ) { interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250; (function beat() { me.fire(); setTimeout(beat, interval); })(); me.running = 1; } }; /** * Create an observable listener for the onunload event */ (function() { PIE.OnUnload = new PIE.Observable(); function handleUnload() { PIE.OnUnload.fire(); window.detachEvent( 'onunload', handleUnload ); window[ 'PIE' ] = null; } window.attachEvent( 'onunload', handleUnload ); /** * Attach an event which automatically gets detached onunload */ PIE.OnUnload.attachManagedEvent = function( target, name, handler ) { target.attachEvent( name, handler ); this.observe( function() { target.detachEvent( name, handler ); } ); }; })()/** * Create a single observable listener for window resize events. */ PIE.OnResize = new PIE.Observable(); PIE.OnUnload.attachManagedEvent( window, 'onresize', function() { PIE.OnResize.fire(); } ); /** * Create a single observable listener for scroll events. Used for lazy loading based * on the viewport, and for fixed position backgrounds. */ (function() { PIE.OnScroll = new PIE.Observable(); function scrolled() { PIE.OnScroll.fire(); } PIE.OnUnload.attachManagedEvent( window, 'onscroll', scrolled ); PIE.OnResize.observe( scrolled ); })(); /** * Listen for printing events, destroy all active PIE instances when printing, and * restore them afterward. */ (function() { var elements; function beforePrint() { elements = PIE.Element.destroyAll(); } function afterPrint() { if( elements ) { for( var i = 0, len = elements.length; i < len; i++ ) { PIE[ 'attach' ]( elements[i] ); } elements = 0; } } if( PIE.ieDocMode < 9 ) { PIE.OnUnload.attachManagedEvent( window, 'onbeforeprint', beforePrint ); PIE.OnUnload.attachManagedEvent( window, 'onafterprint', afterPrint ); } })();/** * Create a single observable listener for document mouseup events. */ PIE.OnMouseup = new PIE.Observable(); PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } ); /** * Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique * value is returned from PIE.getLength() - always use that instead of instantiating directly. * @constructor * @param {string} val The CSS string representing the length. It is assumed that this will already have * been validated as a valid length or percentage syntax. */ PIE.Length = (function() { var lengthCalcEl = doc.createElement( 'length-calc' ), parent = doc.body || doc.documentElement, s = lengthCalcEl.style, conversions = {}, units = [ 'mm', 'cm', 'in', 'pt', 'pc' ], i = units.length, instances = {}; s.position = 'absolute'; s.top = s.left = '-9999px'; parent.appendChild( lengthCalcEl ); while( i-- ) { s.width = '100' + units[i]; conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100; } parent.removeChild( lengthCalcEl ); // All calcs from here on will use 1em s.width = '1em'; function Length( val ) { this.val = val; } Length.prototype = { /** * Regular expression for matching the length unit * @private */ unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/, /** * Get the numeric value of the length * @return {number} The value */ getNumber: function() { var num = this.num, UNDEF; if( num === UNDEF ) { num = this.num = parseFloat( this.val ); } return num; }, /** * Get the unit of the length * @return {string} The unit */ getUnit: function() { var unit = this.unit, m; if( !unit ) { m = this.val.match( this.unitRE ); unit = this.unit = ( m && m[0] ) || 'px'; } return unit; }, /** * Determine whether this is a percentage length value * @return {boolean} */ isPercentage: function() { return this.getUnit() === '%'; }, /** * Resolve this length into a number of pixels. * @param {Element} el - the context element, used to resolve font-relative values * @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a * function which will be called to return the number. */ pixels: function( el, pct100 ) { var num = this.getNumber(), unit = this.getUnit(); switch( unit ) { case "px": return num; case "%": return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100; case "em": return num * this.getEmPixels( el ); case "ex": return num * this.getEmPixels( el ) / 2; default: return num * conversions[ unit ]; } }, /** * The em and ex units are relative to the font-size of the current element, * however if the font-size is set using non-pixel units then we get that value * rather than a pixel conversion. To get around this, we keep a floating element * with width:1em which we insert into the target element and then read its offsetWidth. * For elements that won't accept a child we insert into the parent node and perform * additional calculation. If the font-size *is* specified in pixels, then we use that * directly to avoid the expensive DOM manipulation. * @param {Element} el * @return {number} */ getEmPixels: function( el ) { var fs = el.currentStyle.fontSize, px, parent, me; if( fs.indexOf( 'px' ) > 0 ) { return parseFloat( fs ); } else if( el.tagName in PIE.childlessElements ) { me = this; parent = el.parentNode; return PIE.getLength( fs ).pixels( parent, function() { return me.getEmPixels( parent ); } ); } else { el.appendChild( lengthCalcEl ); px = lengthCalcEl.offsetWidth; if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is el.removeChild( lengthCalcEl ); } return px; } } }; /** * Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value. * @param {string} val The CSS string representing the length. It is assumed that this will already have * been validated as a valid length or percentage syntax. */ PIE.getLength = function( val ) { return instances[ val ] || ( instances[ val ] = new Length( val ) ); }; return Length; })(); /** * Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages. * @constructor * @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value. */ PIE.BgPosition = (function() { var length_fifty = PIE.getLength( '50%' ), vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 }, horiz_idents = { 'left': 1, 'center': 1, 'right': 1 }; function BgPosition( tokens ) { this.tokens = tokens; } BgPosition.prototype = { /** * Normalize the values into the form: * [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ] * where: xOffsetSide is either 'left' or 'right', * yOffsetSide is either 'top' or 'bottom', * and x/yOffsetLength are both PIE.Length objects. * @return {Array} */ getValues: function() { if( !this._values ) { var tokens = this.tokens, len = tokens.length, Tokenizer = PIE.Tokenizer, identType = Tokenizer.Type, length_zero = PIE.getLength( '0' ), type_ident = identType.IDENT, type_length = identType.LENGTH, type_percent = identType.PERCENT, type, value, vals = [ 'left', length_zero, 'top', length_zero ]; // If only one value, the second is assumed to be 'center' if( len === 1 ) { tokens.push( new Tokenizer.Token( type_ident, 'center' ) ); len++; } // Two values - CSS2 if( len === 2 ) { // If both idents, they can appear in either order, so switch them if needed if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) && tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) { tokens.push( tokens.shift() ); } if( tokens[0].tokenType & type_ident ) { if( tokens[0].tokenValue === 'center' ) { vals[1] = length_fifty; } else { vals[0] = tokens[0].tokenValue; } } else if( tokens[0].isLengthOrPercent() ) { vals[1] = PIE.getLength( tokens[0].tokenValue ); } if( tokens[1].tokenType & type_ident ) { if( tokens[1].tokenValue === 'center' ) { vals[3] = length_fifty; } else { vals[2] = tokens[1].tokenValue; } } else if( tokens[1].isLengthOrPercent() ) { vals[3] = PIE.getLength( tokens[1].tokenValue ); } } // Three or four values - CSS3 else { // TODO } this._values = vals; } return this._values; }, /** * Find the coordinates of the background image from the upper-left corner of the background area. * Note that these coordinate values are not rounded. * @param {Element} el * @param {number} width - the width for percentages (background area width minus image width) * @param {number} height - the height for percentages (background area height minus image height) * @return {Object} { x: Number, y: Number } */ coords: function( el, width, height ) { var vals = this.getValues(), pxX = vals[1].pixels( el, width ), pxY = vals[3].pixels( el, height ); return { x: vals[0] === 'right' ? width - pxX : pxX, y: vals[2] === 'bottom' ? height - pxY : pxY }; } }; return BgPosition; })(); /** * Wrapper for a CSS3 background-size value. * @constructor * @param {String|PIE.Length} w The width parameter * @param {String|PIE.Length} h The height parameter, if any */ PIE.BgSize = (function() { var CONTAIN = 'contain', COVER = 'cover', AUTO = 'auto'; function BgSize( w, h ) { this.w = w; this.h = h; } BgSize.prototype = { pixels: function( el, areaW, areaH, imgW, imgH ) { var me = this, w = me.w, h = me.h, areaRatio = areaW / areaH, imgRatio = imgW / imgH; if ( w === CONTAIN ) { w = imgRatio > areaRatio ? areaW : areaH * imgRatio; h = imgRatio > areaRatio ? areaW / imgRatio : areaH; } else if ( w === COVER ) { w = imgRatio < areaRatio ? areaW : areaH * imgRatio; h = imgRatio < areaRatio ? areaW / imgRatio : areaH; } else if ( w === AUTO ) { h = ( h === AUTO ? imgH : h.pixels( el, areaH ) ); w = h * imgRatio; } else { w = w.pixels( el, areaW ); h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) ); } return { w: w, h: h }; } }; BgSize.DEFAULT = new BgSize( AUTO, AUTO ); return BgSize; })(); /** * Wrapper for angle values; handles conversion to degrees from all allowed angle units * @constructor * @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated. */ PIE.Angle = (function() { function Angle( val ) { this.val = val; } Angle.prototype = { unitRE: /[a-z]+$/i, /** * @return {string} The unit of the angle value */ getUnit: function() { return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() ); }, /** * Get the numeric value of the angle in degrees. * @return {number} The degrees value */ degrees: function() { var deg = this._deg, u, n; if( deg === undefined ) { u = this.getUnit(); n = parseFloat( this.val, 10 ); deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 ); } return deg; } }; return Angle; })();/** * Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique * value is returned from PIE.getColor() - always use that instead of instantiating directly. * @constructor * @param {string} val The raw CSS string value for the color */ PIE.Color = (function() { var instances = {}; function Color( val ) { this.val = val; } /** * Regular expression for matching rgba colors and extracting their components * @type {RegExp} */ Color.rgbaRE = /\s*rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d+|\d*\.\d+)\s*\)\s*/; Color.names = { "aliceblue":"F0F8FF", "antiquewhite":"FAEBD7", "aqua":"0FF", "aquamarine":"7FFFD4", "azure":"F0FFFF", "beige":"F5F5DC", "bisque":"FFE4C4", "black":"000", "blanchedalmond":"FFEBCD", "blue":"00F", "blueviolet":"8A2BE2", "brown":"A52A2A", "burlywood":"DEB887", "cadetblue":"5F9EA0", "chartreuse":"7FFF00", "chocolate":"D2691E", "coral":"FF7F50", "cornflowerblue":"6495ED", "cornsilk":"FFF8DC", "crimson":"DC143C", "cyan":"0FF", "darkblue":"00008B", "darkcyan":"008B8B", "darkgoldenrod":"B8860B", "darkgray":"A9A9A9", "darkgreen":"006400", "darkkhaki":"BDB76B", "darkmagenta":"8B008B", "darkolivegreen":"556B2F", "darkorange":"FF8C00", "darkorchid":"9932CC", "darkred":"8B0000", "darksalmon":"E9967A", "darkseagreen":"8FBC8F", "darkslateblue":"483D8B", "darkslategray":"2F4F4F", "darkturquoise":"00CED1", "darkviolet":"9400D3", "deeppink":"FF1493", "deepskyblue":"00BFFF", "dimgray":"696969", "dodgerblue":"1E90FF", "firebrick":"B22222", "floralwhite":"FFFAF0", "forestgreen":"228B22", "fuchsia":"F0F", "gainsboro":"DCDCDC", "ghostwhite":"F8F8FF", "gold":"FFD700", "goldenrod":"DAA520", "gray":"808080", "green":"008000", "greenyellow":"ADFF2F", "honeydew":"F0FFF0", "hotpink":"FF69B4", "indianred":"CD5C5C", "indigo":"4B0082", "ivory":"FFFFF0", "khaki":"F0E68C", "lavender":"E6E6FA", "lavenderblush":"FFF0F5", "lawngreen":"7CFC00", "lemonchiffon":"FFFACD", "lightblue":"ADD8E6", "lightcoral":"F08080", "lightcyan":"E0FFFF", "lightgoldenrodyellow":"FAFAD2", "lightgreen":"90EE90", "lightgrey":"D3D3D3", "lightpink":"FFB6C1", "lightsalmon":"FFA07A", "lightseagreen":"20B2AA", "lightskyblue":"87CEFA", "lightslategray":"789", "lightsteelblue":"B0C4DE", "lightyellow":"FFFFE0", "lime":"0F0", "limegreen":"32CD32", "linen":"FAF0E6", "magenta":"F0F", "maroon":"800000", "mediumauqamarine":"66CDAA", "mediumblue":"0000CD", "mediumorchid":"BA55D3", "mediumpurple":"9370D8", "mediumseagreen":"3CB371", "mediumslateblue":"7B68EE", "mediumspringgreen":"00FA9A", "mediumturquoise":"48D1CC", "mediumvioletred":"C71585", "midnightblue":"191970", "mintcream":"F5FFFA", "mistyrose":"FFE4E1", "moccasin":"FFE4B5", "navajowhite":"FFDEAD", "navy":"000080", "oldlace":"FDF5E6", "olive":"808000", "olivedrab":"688E23", "orange":"FFA500", "orangered":"FF4500", "orchid":"DA70D6", "palegoldenrod":"EEE8AA", "palegreen":"98FB98", "paleturquoise":"AFEEEE", "palevioletred":"D87093", "papayawhip":"FFEFD5", "peachpuff":"FFDAB9", "peru":"CD853F", "pink":"FFC0CB", "plum":"DDA0DD", "powderblue":"B0E0E6", "purple":"800080", "red":"F00", "rosybrown":"BC8F8F", "royalblue":"4169E1", "saddlebrown":"8B4513", "salmon":"FA8072", "sandybrown":"F4A460", "seagreen":"2E8B57", "seashell":"FFF5EE", "sienna":"A0522D", "silver":"C0C0C0", "skyblue":"87CEEB", "slateblue":"6A5ACD", "slategray":"708090", "snow":"FFFAFA", "springgreen":"00FF7F", "steelblue":"4682B4", "tan":"D2B48C", "teal":"008080", "thistle":"D8BFD8", "tomato":"FF6347", "turquoise":"40E0D0", "violet":"EE82EE", "wheat":"F5DEB3", "white":"FFF", "whitesmoke":"F5F5F5", "yellow":"FF0", "yellowgreen":"9ACD32" }; Color.prototype = { /** * @private */ parse: function() { if( !this._color ) { var me = this, v = me.val, vLower, m = v.match( Color.rgbaRE ); if( m ) { me._color = 'rgb(' + m[1] + ',' + m[2] + ',' + m[3] + ')'; me._alpha = parseFloat( m[4] ); } else { if( ( vLower = v.toLowerCase() ) in Color.names ) { v = '#' + Color.names[vLower]; } me._color = v; me._alpha = ( v === 'transparent' ? 0 : 1 ); } } }, /** * Retrieve the value of the color in a format usable by IE natively. This will be the same as * the raw input value, except for rgba values which will be converted to an rgb value. * @param {Element} el The context element, used to get 'currentColor' keyword value. * @return {string} Color value */ colorValue: function( el ) { this.parse(); return this._color === 'currentColor' ? el.currentStyle.color : this._color; }, /** * Retrieve the alpha value of the color. Will be 1 for all values except for rgba values * with an alpha component. * @return {number} The alpha value, from 0 to 1. */ alpha: function() { this.parse(); return this._alpha; } }; /** * Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value. * @param {string} val The CSS string representing the color. It is assumed that this will already have * been validated as a valid color syntax. */ PIE.getColor = function(val) { return instances[ val ] || ( instances[ val ] = new Color( val ) ); }; return Color; })();/** * A tokenizer for CSS value strings. * @constructor * @param {string} css The CSS value string */ PIE.Tokenizer = (function() { function Tokenizer( css ) { this.css = css; this.ch = 0; this.tokens = []; this.tokenIndex = 0; } /** * Enumeration of token type constants. * @enum {number} */ var Type = Tokenizer.Type = { ANGLE: 1, CHARACTER: 2, COLOR: 4, DIMEN: 8, FUNCTION: 16, IDENT: 32, LENGTH: 64, NUMBER: 128, OPERATOR: 256, PERCENT: 512, STRING: 1024, URL: 2048 }; /** * A single token * @constructor * @param {number} type The type of the token - see PIE.Tokenizer.Type * @param {string} value The value of the token */ Tokenizer.Token = function( type, value ) { this.tokenType = type; this.tokenValue = value; }; Tokenizer.Token.prototype = { isLength: function() { return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' ); }, isLengthOrPercent: function() { return this.isLength() || this.tokenType & Type.PERCENT; } }; Tokenizer.prototype = { whitespace: /\s/, number: /^[\+\-]?(\d*\.)?\d+/, url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i, ident: /^\-?[_a-z][\w-]*/i, string: /^("([^"]*)"|'([^']*)')/, operator: /^[\/,]/, hash: /^#[\w]+/, hashColor: /^#([\da-f]{6}|[\da-f]{3})/i, unitTypes: { 'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH, 'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH, 'pt': Type.LENGTH, 'pc': Type.LENGTH, 'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE }, colorFunctions: { 'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1 }, /** * Advance to and return the next token in the CSS string. If the end of the CSS string has * been reached, null will be returned. * @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev(). * @return {PIE.Tokenizer.Token} */ next: function( forget ) { var css, ch, firstChar, match, val, me = this; function newToken( type, value ) { var tok = new Tokenizer.Token( type, value ); if( !forget ) { me.tokens.push( tok ); me.tokenIndex++; } return tok; } function failure() { me.tokenIndex++; return null; } // In case we previously backed up, return the stored token in the next slot if( this.tokenIndex < this.tokens.length ) { return this.tokens[ this.tokenIndex++ ]; } // Move past leading whitespace characters while( this.whitespace.test( this.css.charAt( this.ch ) ) ) { this.ch++; } if( this.ch >= this.css.length ) { return failure(); } ch = this.ch; css = this.css.substring( this.ch ); firstChar = css.charAt( 0 ); switch( firstChar ) { case '#': if( match = css.match( this.hashColor ) ) { this.ch += match[0].length; return newToken( Type.COLOR, match[0] ); } break; case '"': case "'": if( match = css.match( this.string ) ) { this.ch += match[0].length; return newToken( Type.STRING, match[2] || match[3] || '' ); } break; case "/": case ",": this.ch++; return newToken( Type.OPERATOR, firstChar ); case 'u': if( match = css.match( this.url ) ) { this.ch += match[0].length; return newToken( Type.URL, match[2] || match[3] || match[4] || '' ); } } // Numbers and values starting with numbers if( match = css.match( this.number ) ) { val = match[0]; this.ch += val.length; // Check if it is followed by a unit if( css.charAt( val.length ) === '%' ) { this.ch++; return newToken( Type.PERCENT, val + '%' ); } if( match = css.substring( val.length ).match( this.ident ) ) { val += match[0]; this.ch += match[0].length; return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val ); } // Plain ol' number return newToken( Type.NUMBER, val ); } // Identifiers if( match = css.match( this.ident ) ) { val = match[0]; this.ch += val.length; // Named colors if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) { return newToken( Type.COLOR, val ); } // Functions if( css.charAt( val.length ) === '(' ) { this.ch++; // Color values in function format: rgb, rgba, hsl, hsla if( val.toLowerCase() in this.colorFunctions ) { function isNum( tok ) { return tok && tok.tokenType & Type.NUMBER; } function isNumOrPct( tok ) { return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) ); } function isValue( tok, val ) { return tok && tok.tokenValue === val; } function next() { return me.next( 1 ); } if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) && isValue( next(), ',' ) && isNumOrPct( next() ) && isValue( next(), ',' ) && isNumOrPct( next() ) && ( val === 'rgb' || val === 'hsa' || ( isValue( next(), ',' ) && isNum( next() ) ) ) && isValue( next(), ')' ) ) { return newToken( Type.COLOR, this.css.substring( ch, this.ch ) ); } return failure(); } return newToken( Type.FUNCTION, val ); } // Other identifier return newToken( Type.IDENT, val ); } // Standalone character this.ch++; return newToken( Type.CHARACTER, firstChar ); }, /** * Determine whether there is another token * @return {boolean} */ hasNext: function() { var next = this.next(); this.prev(); return !!next; }, /** * Back up and return the previous token * @return {PIE.Tokenizer.Token} */ prev: function() { return this.tokens[ this.tokenIndex-- - 2 ]; }, /** * Retrieve all the tokens in the CSS string * @return {Array.<PIE.Tokenizer.Token>} */ all: function() { while( this.next() ) {} return this.tokens; }, /** * Return a list of tokens from the current position until the given function returns * true. The final token will not be included in the list. * @param {function():boolean} func - test function * @param {boolean} require - if true, then if the end of the CSS string is reached * before the test function returns true, null will be returned instead of the * tokens that have been found so far. * @return {Array.<PIE.Tokenizer.Token>} */ until: function( func, require ) { var list = [], t, hit; while( t = this.next() ) { if( func( t ) ) { hit = true; this.prev(); break; } list.push( t ); } return require && !hit ? null : list; } }; return Tokenizer; })();/** * Handles calculating, caching, and detecting changes to size and position of the element. * @constructor * @param {Element} el the target element */ PIE.BoundsInfo = function( el ) { this.targetElement = el; }; PIE.BoundsInfo.prototype = { _locked: 0, positionChanged: function() { var last = this._lastBounds, bounds; return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) ); }, sizeChanged: function() { var last = this._lastBounds, bounds; return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) ); }, getLiveBounds: function() { var el = this.targetElement, rect = el.getBoundingClientRect(), isIE9 = PIE.ieDocMode === 9, isIE7 = PIE.ieVersion === 7, width = rect.right - rect.left; return { x: rect.left, y: rect.top, // In some cases scrolling the page will cause IE9 to report incorrect dimensions // in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height // instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements // so we must calculate the ratio and use it in certain places as a position adjustment. w: isIE9 || isIE7 ? el.offsetWidth : width, h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top, logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1 }; }, getBounds: function() { return this._locked ? ( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) : this.getLiveBounds(); }, hasBeenQueried: function() { return !!this._lastBounds; }, lock: function() { ++this._locked; }, unlock: function() { if( !--this._locked ) { if( this._lockedBounds ) this._lastBounds = this._lockedBounds; this._lockedBounds = null; } } }; (function() { function cacheWhenLocked( fn ) { var uid = PIE.Util.getUID( fn ); return function() { if( this._locked ) { var cache = this._lockedValues || ( this._lockedValues = {} ); return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) ); } else { return fn.call( this ); } } } PIE.StyleInfoBase = { _locked: 0, /** * Create a new StyleInfo class, with the standard constructor, and augmented by * the StyleInfoBase's members. * @param proto */ newStyleInfo: function( proto ) { function StyleInfo( el ) { this.targetElement = el; this._lastCss = this.getCss(); } PIE.Util.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto ); StyleInfo._propsCache = {}; return StyleInfo; }, /** * Get an object representation of the target CSS style, caching it for each unique * CSS value string. * @return {Object} */ getProps: function() { var css = this.getCss(), cache = this.constructor._propsCache; return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null; }, /** * Get the raw CSS value for the target style * @return {string} */ getCss: cacheWhenLocked( function() { var el = this.targetElement, ctor = this.constructor, s = el.style, cs = el.currentStyle, cssProp = this.cssProperty, styleProp = this.styleProperty, prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ), prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) ); return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp ); } ), /** * Determine whether the target CSS style is active. * @return {boolean} */ isActive: cacheWhenLocked( function() { return !!this.getProps(); } ), /** * Determine whether the target CSS style has changed since the last time it was used. * @return {boolean} */ changed: cacheWhenLocked( function() { var currentCss = this.getCss(), changed = currentCss !== this._lastCss; this._lastCss = currentCss; return changed; } ), cacheWhenLocked: cacheWhenLocked, lock: function() { ++this._locked; }, unlock: function() { if( !--this._locked ) { delete this._lockedValues; } } }; })();/** * Handles parsing, caching, and detecting changes to background (and -pie-background) CSS * @constructor * @param {Element} el the target element */ PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: PIE.CSS_PREFIX + 'background', styleProperty: PIE.STYLE_PREFIX + 'Background', attachIdents: { 'scroll':1, 'fixed':1, 'local':1 }, repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 }, originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 }, positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 }, sizeIdents: { 'contain':1, 'cover':1 }, propertyNames: { CLIP: 'backgroundClip', COLOR: 'backgroundColor', IMAGE: 'backgroundImage', ORIGIN: 'backgroundOrigin', POSITION: 'backgroundPosition', REPEAT: 'backgroundRepeat', SIZE: 'backgroundSize' }, /** * For background styles, we support the -pie-background property but fall back to the standard * backround* properties. The reason we have to use the prefixed version is that IE natively * parses the standard properties and if it sees something it doesn't know how to parse, for example * multiple values or gradient definitions, it will throw that away and not make it available through * currentStyle. * * Format of return object: * { * color: <PIE.Color>, * bgImages: [ * { * imgType: 'image', * imgUrl: 'image.png', * imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>, * bgPosition: <PIE.BgPosition>, * bgAttachment: <'scroll' | 'fixed' | 'local'>, * bgOrigin: <'border-box' | 'padding-box' | 'content-box'>, * bgClip: <'border-box' | 'padding-box'>, * bgSize: <PIE.BgSize>, * origString: 'url(img.png) no-repeat top left' * }, * { * imgType: 'linear-gradient', * gradientStart: <PIE.BgPosition>, * angle: <PIE.Angle>, * stops: [ * { color: <PIE.Color>, offset: <PIE.Length> }, * { color: <PIE.Color>, offset: <PIE.Length> }, ... * ] * } * ] * } * @param {String} css * @override */ parseCss: function( css ) { var el = this.targetElement, cs = el.currentStyle, tokenizer, token, image, tok_type = PIE.Tokenizer.Type, type_operator = tok_type.OPERATOR, type_ident = tok_type.IDENT, type_color = tok_type.COLOR, tokType, tokVal, beginCharIndex = 0, positionIdents = this.positionIdents, gradient, stop, width, height, props = { bgImages: [] }; function isBgPosToken( token ) { return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents ); } function sizeToken( token ) { return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) ); } // If the CSS3-specific -pie-background property is present, parse it if( this.getCss3() ) { tokenizer = new PIE.Tokenizer( css ); image = {}; while( token = tokenizer.next() ) { tokType = token.tokenType; tokVal = token.tokenValue; if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) { gradient = { stops: [], imgType: tokVal }; stop = {}; while( token = tokenizer.next() ) { tokType = token.tokenType; tokVal = token.tokenValue; // If we reached the end of the function and had at least 2 stops, flush the info if( tokType & tok_type.CHARACTER && tokVal === ')' ) { if( stop.color ) { gradient.stops.push( stop ); } if( gradient.stops.length > 1 ) { PIE.Util.merge( image, gradient ); } break; } // Color stop - must start with color if( tokType & type_color ) { // if we already have an angle/position, make sure that the previous token was a comma if( gradient.angle || gradient.gradientStart ) { token = tokenizer.prev(); if( token.tokenType !== type_operator ) { break; //fail } tokenizer.next(); } stop = { color: PIE.getColor( tokVal ) }; // check for offset following color token = tokenizer.next(); if( token.isLengthOrPercent() ) { stop.offset = PIE.getLength( token.tokenValue ); } else { tokenizer.prev(); } } // Angle - can only appear in first spot else if( tokType & tok_type.ANGLE && !gradient.angle && !stop.color && !gradient.stops.length ) { gradient.angle = new PIE.Angle( token.tokenValue ); } else if( isBgPosToken( token ) && !gradient.gradientStart && !stop.color && !gradient.stops.length ) { tokenizer.prev(); gradient.gradientStart = new PIE.BgPosition( tokenizer.until( function( t ) { return !isBgPosToken( t ); }, false ) ); } else if( tokType & type_operator && tokVal === ',' ) { if( stop.color ) { gradient.stops.push( stop ); stop = {}; } } else { // Found something we didn't recognize; fail without adding image break; } } } else if( !image.imgType && tokType & tok_type.URL ) { image.imgUrl = tokVal; image.imgType = 'image'; } else if( isBgPosToken( token ) && !image.bgPosition ) { tokenizer.prev(); image.bgPosition = new PIE.BgPosition( tokenizer.until( function( t ) { return !isBgPosToken( t ); }, false ) ); } else if( tokType & type_ident ) { if( tokVal in this.repeatIdents && !image.imgRepeat ) { image.imgRepeat = tokVal; } else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) { image.bgOrigin = tokVal; if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) && token.tokenValue in this.originAndClipIdents ) { image.bgClip = token.tokenValue; } else { image.bgClip = tokVal; tokenizer.prev(); } } else if( tokVal in this.attachIdents && !image.bgAttachment ) { image.bgAttachment = tokVal; } else { return null; } } else if( tokType & type_color && !props.color ) { props.color = PIE.getColor( tokVal ); } else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) { // background size token = tokenizer.next(); if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) { image.bgSize = new PIE.BgSize( token.tokenValue ); } else if( width = sizeToken( token ) ) { height = sizeToken( tokenizer.next() ); if ( !height ) { height = width; tokenizer.prev(); } image.bgSize = new PIE.BgSize( width, height ); } else { return null; } } // new layer else if( tokType & type_operator && tokVal === ',' && image.imgType ) { image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 ); beginCharIndex = tokenizer.ch; props.bgImages.push( image ); image = {}; } else { // Found something unrecognized; chuck everything return null; } } // leftovers if( image.imgType ) { image.origString = css.substring( beginCharIndex ); props.bgImages.push( image ); } } // Otherwise, use the standard background properties; let IE give us the values rather than parsing them else { this.withActualBg( PIE.ieDocMode < 9 ? function() { var propNames = this.propertyNames, posX = cs[propNames.POSITION + 'X'], posY = cs[propNames.POSITION + 'Y'], img = cs[propNames.IMAGE], color = cs[propNames.COLOR]; if( color !== 'transparent' ) { props.color = PIE.getColor( color ) } if( img !== 'none' ) { props.bgImages = [ { imgType: 'image', imgUrl: new PIE.Tokenizer( img ).next().tokenValue, imgRepeat: cs[propNames.REPEAT], bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() ) } ]; } } : function() { var propNames = this.propertyNames, splitter = /\s*,\s*/, images = cs[propNames.IMAGE].split( splitter ), color = cs[propNames.COLOR], repeats, positions, origins, clips, sizes, i, len, image, sizeParts; if( color !== 'transparent' ) { props.color = PIE.getColor( color ) } len = images.length; if( len && images[0] !== 'none' ) { repeats = cs[propNames.REPEAT].split( splitter ); positions = cs[propNames.POSITION].split( splitter ); origins = cs[propNames.ORIGIN].split( splitter ); clips = cs[propNames.CLIP].split( splitter ); sizes = cs[propNames.SIZE].split( splitter ); props.bgImages = []; for( i = 0; i < len; i++ ) { image = images[ i ]; if( image && image !== 'none' ) { sizeParts = sizes[i].split( ' ' ); props.bgImages.push( { origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' + origins[ i ] + ' ' + clips[ i ], imgType: 'image', imgUrl: new PIE.Tokenizer( image ).next().tokenValue, imgRepeat: repeats[ i ], bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ), bgOrigin: origins[ i ], bgClip: clips[ i ], bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] ) } ); } } } } ); } return ( props.color || props.bgImages[0] ) ? props : null; }, /** * Execute a function with the actual background styles (not overridden with runtimeStyle * properties set by the renderers) available via currentStyle. * @param fn */ withActualBg: function( fn ) { var isIE9 = PIE.ieDocMode > 8, propNames = this.propertyNames, rs = this.targetElement.runtimeStyle, rsImage = rs[propNames.IMAGE], rsColor = rs[propNames.COLOR], rsRepeat = rs[propNames.REPEAT], rsClip, rsOrigin, rsSize, rsPosition, ret; if( rsImage ) rs[propNames.IMAGE] = ''; if( rsColor ) rs[propNames.COLOR] = ''; if( rsRepeat ) rs[propNames.REPEAT] = ''; if( isIE9 ) { rsClip = rs[propNames.CLIP]; rsOrigin = rs[propNames.ORIGIN]; rsPosition = rs[propNames.POSITION]; rsSize = rs[propNames.SIZE]; if( rsClip ) rs[propNames.CLIP] = ''; if( rsOrigin ) rs[propNames.ORIGIN] = ''; if( rsPosition ) rs[propNames.POSITION] = ''; if( rsSize ) rs[propNames.SIZE] = ''; } ret = fn.call( this ); if( rsImage ) rs[propNames.IMAGE] = rsImage; if( rsColor ) rs[propNames.COLOR] = rsColor; if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat; if( isIE9 ) { if( rsClip ) rs[propNames.CLIP] = rsClip; if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin; if( rsPosition ) rs[propNames.POSITION] = rsPosition; if( rsSize ) rs[propNames.SIZE] = rsSize; } return ret; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { return this.getCss3() || this.withActualBg( function() { var cs = this.targetElement.currentStyle, propNames = this.propertyNames; return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' + cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y']; } ); } ), getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement; return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty ); } ), /** * Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6. */ isPngFix: function() { var val = 0, el; if( PIE.ieVersion < 7 ) { el = this.targetElement; val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' ); } return val; }, /** * The isActive logic is slightly different, because getProps() always returns an object * even if it is just falling back to the native background properties. But we only want * to report is as being "active" if either the -pie-background override property is present * and parses successfully or '-pie-png-fix' is set to true in IE6. */ isActive: PIE.StyleInfoBase.cacheWhenLocked( function() { return (this.getCss3() || this.isPngFix()) && !!this.getProps(); } ) } );/** * Handles parsing, caching, and detecting changes to border CSS * @constructor * @param {Element} el the target element */ PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( { sides: [ 'Top', 'Right', 'Bottom', 'Left' ], namedWidths: { 'thin': '1px', 'medium': '3px', 'thick': '5px' }, parseCss: function( css ) { var w = {}, s = {}, c = {}, active = false, colorsSame = true, stylesSame = true, widthsSame = true; this.withActualBorder( function() { var el = this.targetElement, cs = el.currentStyle, i = 0, style, color, width, lastStyle, lastColor, lastWidth, side, ltr; for( ; i < 4; i++ ) { side = this.sides[ i ]; ltr = side.charAt(0).toLowerCase(); style = s[ ltr ] = cs[ 'border' + side + 'Style' ]; color = cs[ 'border' + side + 'Color' ]; width = cs[ 'border' + side + 'Width' ]; if( i > 0 ) { if( style !== lastStyle ) { stylesSame = false; } if( color !== lastColor ) { colorsSame = false; } if( width !== lastWidth ) { widthsSame = false; } } lastStyle = style; lastColor = color; lastWidth = width; c[ ltr ] = PIE.getColor( color ); width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) ); if( width.pixels( this.targetElement ) > 0 ) { active = true; } } } ); return active ? { widths: w, styles: s, colors: c, widthsSame: widthsSame, colorsSame: colorsSame, stylesSame: stylesSame } : null; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement, cs = el.currentStyle, css; // Don't redraw or hide borders for cells in border-collapse:collapse tables if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) { this.withActualBorder( function() { css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor; } ); } return css; } ), /** * Execute a function with the actual border styles (not overridden with runtimeStyle * properties set by the renderers) available via currentStyle. * @param fn */ withActualBorder: function( fn ) { var rs = this.targetElement.runtimeStyle, rsWidth = rs.borderWidth, rsColor = rs.borderColor, ret; if( rsWidth ) rs.borderWidth = ''; if( rsColor ) rs.borderColor = ''; ret = fn.call( this ); if( rsWidth ) rs.borderWidth = rsWidth; if( rsColor ) rs.borderColor = rsColor; return ret; } } ); /** * Handles parsing, caching, and detecting changes to border-radius CSS * @constructor * @param {Element} el the target element */ (function() { PIE.BorderRadiusStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'border-radius', styleProperty: 'borderRadius', parseCss: function( css ) { var p = null, x, y, tokenizer, token, length, hasNonZero = false; if( css ) { tokenizer = new PIE.Tokenizer( css ); function collectLengths() { var arr = [], num; while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) { length = PIE.getLength( token.tokenValue ); num = length.getNumber(); if( num < 0 ) { return null; } if( num > 0 ) { hasNonZero = true; } arr.push( length ); } return arr.length > 0 && arr.length < 5 ? { 'tl': arr[0], 'tr': arr[1] || arr[0], 'br': arr[2] || arr[0], 'bl': arr[3] || arr[1] || arr[0] } : null; } // Grab the initial sequence of lengths if( x = collectLengths() ) { // See if there is a slash followed by more lengths, for the y-axis radii if( token ) { if( token.tokenType & PIE.Tokenizer.Type.OPERATOR && token.tokenValue === '/' ) { y = collectLengths(); } } else { y = x; } // Treat all-zero values the same as no value if( hasNonZero && x && y ) { p = { x: x, y : y }; } } } return p; } } ); var zero = PIE.getLength( '0' ), zeros = { 'tl': zero, 'tr': zero, 'br': zero, 'bl': zero }; PIE.BorderRadiusStyleInfo.ALL_ZERO = { x: zeros, y: zeros }; })();/** * Handles parsing, caching, and detecting changes to border-image CSS * @constructor * @param {Element} el the target element */ PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'border-image', styleProperty: 'borderImage', repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 }, parseCss: function( css ) { var p = null, tokenizer, token, type, value, slices, widths, outsets, slashCount = 0, Type = PIE.Tokenizer.Type, IDENT = Type.IDENT, NUMBER = Type.NUMBER, PERCENT = Type.PERCENT; if( css ) { tokenizer = new PIE.Tokenizer( css ); p = {}; function isSlash( token ) { return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' ); } function isFillIdent( token ) { return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' ); } function collectSlicesEtc() { slices = tokenizer.until( function( tok ) { return !( tok.tokenType & ( NUMBER | PERCENT ) ); } ); if( isFillIdent( tokenizer.next() ) && !p.fill ) { p.fill = true; } else { tokenizer.prev(); } if( isSlash( tokenizer.next() ) ) { slashCount++; widths = tokenizer.until( function( token ) { return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' ); } ); if( isSlash( tokenizer.next() ) ) { slashCount++; outsets = tokenizer.until( function( token ) { return !token.isLength(); } ); } } else { tokenizer.prev(); } } while( token = tokenizer.next() ) { type = token.tokenType; value = token.tokenValue; // Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values if( type & ( NUMBER | PERCENT ) && !slices ) { tokenizer.prev(); collectSlicesEtc(); } else if( isFillIdent( token ) && !p.fill ) { p.fill = true; collectSlicesEtc(); } // Idents: one or values for 'repeat' else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) { p.repeat = { h: value }; if( token = tokenizer.next() ) { if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) { p.repeat.v = token.tokenValue; } else { tokenizer.prev(); } } } // URL of the image else if( ( type & Type.URL ) && !p.src ) { p.src = value; } // Found something unrecognized; exit. else { return null; } } // Validate what we collected if( !p.src || !slices || slices.length < 1 || slices.length > 4 || ( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) || ( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) { return null; } // Fill in missing values if( !p.repeat ) { p.repeat = { h: 'stretch' }; } if( !p.repeat.v ) { p.repeat.v = p.repeat.h; } function distributeSides( tokens, convertFn ) { return { 't': convertFn( tokens[0] ), 'r': convertFn( tokens[1] || tokens[0] ), 'b': convertFn( tokens[2] || tokens[0] ), 'l': convertFn( tokens[3] || tokens[1] || tokens[0] ) }; } p.slice = distributeSides( slices, function( tok ) { return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue ); } ); if( widths && widths[0] ) { p.widths = distributeSides( widths, function( tok ) { return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue; } ); } if( outsets && outsets[0] ) { p.outset = distributeSides( outsets, function( tok ) { return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue; } ); } } return p; } } );/** * Handles parsing, caching, and detecting changes to box-shadow CSS * @constructor * @param {Element} el the target element */ PIE.BoxShadowStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'box-shadow', styleProperty: 'boxShadow', parseCss: function( css ) { var props, getLength = PIE.getLength, Type = PIE.Tokenizer.Type, tokenizer; if( css ) { tokenizer = new PIE.Tokenizer( css ); props = { outset: [], inset: [] }; function parseItem() { var token, type, value, color, lengths, inset, len; while( token = tokenizer.next() ) { value = token.tokenValue; type = token.tokenType; if( type & Type.OPERATOR && value === ',' ) { break; } else if( token.isLength() && !lengths ) { tokenizer.prev(); lengths = tokenizer.until( function( token ) { return !token.isLength(); } ); } else if( type & Type.COLOR && !color ) { color = value; } else if( type & Type.IDENT && value === 'inset' && !inset ) { inset = true; } else { //encountered an unrecognized token; fail. return false; } } len = lengths && lengths.length; if( len > 1 && len < 5 ) { ( inset ? props.inset : props.outset ).push( { xOffset: getLength( lengths[0].tokenValue ), yOffset: getLength( lengths[1].tokenValue ), blur: getLength( lengths[2] ? lengths[2].tokenValue : '0' ), spread: getLength( lengths[3] ? lengths[3].tokenValue : '0' ), color: PIE.getColor( color || 'currentColor' ) } ); return true; } return false; } while( parseItem() ) {} } return props && ( props.inset.length || props.outset.length ) ? props : null; } } ); /** * Retrieves the state of the element's visibility and display * @constructor * @param {Element} el the target element */ PIE.VisibilityStyleInfo = PIE.StyleInfoBase.newStyleInfo( { getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { var cs = this.targetElement.currentStyle; return cs.visibility + '|' + cs.display; } ), parseCss: function() { var el = this.targetElement, rs = el.runtimeStyle, cs = el.currentStyle, rsVis = rs.visibility, csVis; rs.visibility = ''; csVis = cs.visibility; rs.visibility = rsVis; return { visible: csVis !== 'hidden', displayed: cs.display !== 'none' } }, /** * Always return false for isActive, since this property alone will not trigger * a renderer to do anything. */ isActive: function() { return false; } } ); PIE.RendererBase = { /** * Create a new Renderer class, with the standard constructor, and augmented by * the RendererBase's members. * @param proto */ newRenderer: function( proto ) { function Renderer( el, boundsInfo, styleInfos, parent ) { this.targetElement = el; this.boundsInfo = boundsInfo; this.styleInfos = styleInfos; this.parent = parent; } PIE.Util.merge( Renderer.prototype, PIE.RendererBase, proto ); return Renderer; }, /** * Flag indicating the element has already been positioned at least once. * @type {boolean} */ isPositioned: false, /** * Determine if the renderer needs to be updated * @return {boolean} */ needsUpdate: function() { return false; }, /** * Run any preparation logic that would affect the main update logic of this * renderer or any of the other renderers, e.g. things that might affect the * element's size or style properties. */ prepareUpdate: PIE.emptyFn, /** * Tell the renderer to update based on modified properties */ updateProps: function() { this.destroy(); if( this.isActive() ) { this.draw(); } }, /** * Tell the renderer to update based on modified element position */ updatePos: function() { this.isPositioned = true; }, /** * Tell the renderer to update based on modified element dimensions */ updateSize: function() { if( this.isActive() ) { this.draw(); } else { this.destroy(); } }, /** * Add a layer element, with the given z-order index, to the renderer's main box element. We can't use * z-index because that breaks when the root rendering box's z-index is 'auto' in IE8+ standards mode. * So instead we make sure they are inserted into the DOM in the correct order. * @param {number} index * @param {Element} el */ addLayer: function( index, el ) { this.removeLayer( index ); for( var layers = this._layers || ( this._layers = [] ), i = index + 1, len = layers.length, layer; i < len; i++ ) { layer = layers[i]; if( layer ) { break; } } layers[index] = el; this.getBox().insertBefore( el, layer || null ); }, /** * Retrieve a layer element by its index, or null if not present * @param {number} index * @return {Element} */ getLayer: function( index ) { var layers = this._layers; return layers && layers[index] || null; }, /** * Remove a layer element by its index * @param {number} index */ removeLayer: function( index ) { var layer = this.getLayer( index ), box = this._box; if( layer && box ) { box.removeChild( layer ); this._layers[index] = null; } }, /** * Get a VML shape by name, creating it if necessary. * @param {string} name A name identifying the element * @param {string=} subElName If specified a subelement of the shape will be created with this tag name * @param {Element} parent The parent element for the shape; will be ignored if 'group' is specified * @param {number=} group If specified, an ordinal group for the shape. 1 or greater. Groups are rendered * using container elements in the correct order, to get correct z stacking without z-index. */ getShape: function( name, subElName, parent, group ) { var shapes = this._shapes || ( this._shapes = {} ), shape = shapes[ name ], s; if( !shape ) { shape = shapes[ name ] = PIE.Util.createVmlElement( 'shape' ); if( subElName ) { shape.appendChild( shape[ subElName ] = PIE.Util.createVmlElement( subElName ) ); } if( group ) { parent = this.getLayer( group ); if( !parent ) { this.addLayer( group, doc.createElement( 'group' + group ) ); parent = this.getLayer( group ); } } parent.appendChild( shape ); s = shape.style; s.position = 'absolute'; s.left = s.top = 0; s['behavior'] = 'url(#default#VML)'; } return shape; }, /** * Delete a named shape which was created by getShape(). Returns true if a shape with the * given name was found and deleted, or false if there was no shape of that name. * @param {string} name * @return {boolean} */ deleteShape: function( name ) { var shapes = this._shapes, shape = shapes && shapes[ name ]; if( shape ) { shape.parentNode.removeChild( shape ); delete shapes[ name ]; } return !!shape; }, /** * For a given set of border radius length/percentage values, convert them to concrete pixel * values based on the current size of the target element. * @param {Object} radii * @return {Object} */ getRadiiPixels: function( radii ) { var el = this.targetElement, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, tlX, tlY, trX, trY, brX, brY, blX, blY, f; tlX = radii.x['tl'].pixels( el, w ); tlY = radii.y['tl'].pixels( el, h ); trX = radii.x['tr'].pixels( el, w ); trY = radii.y['tr'].pixels( el, h ); brX = radii.x['br'].pixels( el, w ); brY = radii.y['br'].pixels( el, h ); blX = radii.x['bl'].pixels( el, w ); blY = radii.y['bl'].pixels( el, h ); // If any corner ellipses overlap, reduce them all by the appropriate factor. This formula // is taken straight from the CSS3 Backgrounds and Borders spec. f = Math.min( w / ( tlX + trX ), h / ( trY + brY ), w / ( blX + brX ), h / ( tlY + blY ) ); if( f < 1 ) { tlX *= f; tlY *= f; trX *= f; trY *= f; brX *= f; brY *= f; blX *= f; blY *= f; } return { x: { 'tl': tlX, 'tr': trX, 'br': brX, 'bl': blX }, y: { 'tl': tlY, 'tr': trY, 'br': brY, 'bl': blY } } }, /** * Return the VML path string for the element's background box, with corners rounded. * @param {Object.<{t:number, r:number, b:number, l:number}>} shrink - if present, specifies number of * pixels to shrink the box path inward from the element's four sides. * @param {number=} mult If specified, all coordinates will be multiplied by this number * @param {Object=} radii If specified, this will be used for the corner radii instead of the properties * from this renderer's borderRadiusInfo object. * @return {string} the VML path */ getBoxPath: function( shrink, mult, radii ) { mult = mult || 1; var r, str, bounds = this.boundsInfo.getBounds(), w = bounds.w * mult, h = bounds.h * mult, radInfo = this.styleInfos.borderRadiusInfo, floor = Math.floor, ceil = Math.ceil, shrinkT = shrink ? shrink.t * mult : 0, shrinkR = shrink ? shrink.r * mult : 0, shrinkB = shrink ? shrink.b * mult : 0, shrinkL = shrink ? shrink.l * mult : 0, tlX, tlY, trX, trY, brX, brY, blX, blY; if( radii || radInfo.isActive() ) { r = this.getRadiiPixels( radii || radInfo.getProps() ); tlX = r.x['tl'] * mult; tlY = r.y['tl'] * mult; trX = r.x['tr'] * mult; trY = r.y['tr'] * mult; brX = r.x['br'] * mult; brY = r.y['br'] * mult; blX = r.x['bl'] * mult; blY = r.y['bl'] * mult; str = 'm' + floor( shrinkL ) + ',' + floor( tlY ) + 'qy' + floor( tlX ) + ',' + floor( shrinkT ) + 'l' + ceil( w - trX ) + ',' + floor( shrinkT ) + 'qx' + ceil( w - shrinkR ) + ',' + floor( trY ) + 'l' + ceil( w - shrinkR ) + ',' + ceil( h - brY ) + 'qy' + ceil( w - brX ) + ',' + ceil( h - shrinkB ) + 'l' + floor( blX ) + ',' + ceil( h - shrinkB ) + 'qx' + floor( shrinkL ) + ',' + ceil( h - blY ) + ' x e'; } else { // simplified path for non-rounded box str = 'm' + floor( shrinkL ) + ',' + floor( shrinkT ) + 'l' + ceil( w - shrinkR ) + ',' + floor( shrinkT ) + 'l' + ceil( w - shrinkR ) + ',' + ceil( h - shrinkB ) + 'l' + floor( shrinkL ) + ',' + ceil( h - shrinkB ) + 'xe'; } return str; }, /** * Get the container element for the shapes, creating it if necessary. */ getBox: function() { var box = this.parent.getLayer( this.boxZIndex ), s; if( !box ) { box = doc.createElement( this.boxName ); s = box.style; s.position = 'absolute'; s.top = s.left = 0; this.parent.addLayer( this.boxZIndex, box ); } return box; }, /** * Hide the actual border of the element. In IE7 and up we can just set its color to transparent; * however IE6 does not support transparent borders so we have to get tricky with it. Also, some elements * like form buttons require removing the border width altogether, so for those we increase the padding * by the border size. */ hideBorder: function() { var el = this.targetElement, cs = el.currentStyle, rs = el.runtimeStyle, tag = el.tagName, isIE6 = PIE.ieVersion === 6, sides, side, i; if( ( isIE6 && ( tag in PIE.childlessElements || tag === 'FIELDSET' ) ) || tag === 'BUTTON' || ( tag === 'INPUT' && el.type in PIE.inputButtonTypes ) ) { rs.borderWidth = ''; sides = this.styleInfos.borderInfo.sides; for( i = sides.length; i--; ) { side = sides[ i ]; rs[ 'padding' + side ] = ''; rs[ 'padding' + side ] = ( PIE.getLength( cs[ 'padding' + side ] ) ).pixels( el ) + ( PIE.getLength( cs[ 'border' + side + 'Width' ] ) ).pixels( el ) + ( PIE.ieVersion !== 8 && i % 2 ? 1 : 0 ); //needs an extra horizontal pixel to counteract the extra "inner border" going away } rs.borderWidth = 0; } else if( isIE6 ) { // Wrap all the element's children in a custom element, set the element to visiblity:hidden, // and set the wrapper element to visiblity:visible. This hides the outer element's decorations // (background and border) but displays all the contents. // TODO find a better way to do this that doesn't mess up the DOM parent-child relationship, // as this can interfere with other author scripts which add/modify/delete children. Also, this // won't work for elements which cannot take children, e.g. input/button/textarea/img/etc. Look into // using a compositor filter or some other filter which masks the border. if( el.childNodes.length !== 1 || el.firstChild.tagName !== 'ie6-mask' ) { var cont = doc.createElement( 'ie6-mask' ), s = cont.style, child; s.visibility = 'visible'; s.zoom = 1; while( child = el.firstChild ) { cont.appendChild( child ); } el.appendChild( cont ); rs.visibility = 'hidden'; } } else { rs.borderColor = 'transparent'; } }, unhideBorder: function() { }, /** * Destroy the rendered objects. This is a base implementation which handles common renderer * structures, but individual renderers may override as necessary. */ destroy: function() { this.parent.removeLayer( this.boxZIndex ); delete this._shapes; delete this._layers; } }; /** * Root renderer; creates the outermost container element and handles keeping it aligned * with the target element's size and position. * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.RootRenderer = PIE.RendererBase.newRenderer( { isActive: function() { var children = this.childRenderers; for( var i in children ) { if( children.hasOwnProperty( i ) && children[ i ].isActive() ) { return true; } } return false; }, needsUpdate: function() { return this.styleInfos.visibilityInfo.changed(); }, updatePos: function() { if( this.isActive() ) { var el = this.getPositioningElement(), par = el, docEl, parRect, tgtCS = el.currentStyle, tgtPos = tgtCS.position, boxPos, s = this.getBox().style, cs, x = 0, y = 0, elBounds = this.boundsInfo.getBounds(), logicalZoomRatio = elBounds.logicalZoomRatio; if( tgtPos === 'fixed' && PIE.ieVersion > 6 ) { x = elBounds.x * logicalZoomRatio; y = elBounds.y * logicalZoomRatio; boxPos = tgtPos; } else { // Get the element's offsets from its nearest positioned ancestor. Uses // getBoundingClientRect for accuracy and speed. do { par = par.offsetParent; } while( par && ( par.currentStyle.position === 'static' ) ); if( par ) { parRect = par.getBoundingClientRect(); cs = par.currentStyle; x = ( elBounds.x - parRect.left ) * logicalZoomRatio - ( parseFloat(cs.borderLeftWidth) || 0 ); y = ( elBounds.y - parRect.top ) * logicalZoomRatio - ( parseFloat(cs.borderTopWidth) || 0 ); } else { docEl = doc.documentElement; x = ( elBounds.x + docEl.scrollLeft - docEl.clientLeft ) * logicalZoomRatio; y = ( elBounds.y + docEl.scrollTop - docEl.clientTop ) * logicalZoomRatio; } boxPos = 'absolute'; } s.position = boxPos; s.left = x; s.top = y; s.zIndex = tgtPos === 'static' ? -1 : tgtCS.zIndex; this.isPositioned = true; } }, updateSize: PIE.emptyFn, updateVisibility: function() { var vis = this.styleInfos.visibilityInfo.getProps(); this.getBox().style.display = ( vis.visible && vis.displayed ) ? '' : 'none'; }, updateProps: function() { if( this.isActive() ) { this.updateVisibility(); } else { this.destroy(); } }, getPositioningElement: function() { var el = this.targetElement; return el.tagName in PIE.tableCellTags ? el.offsetParent : el; }, getBox: function() { var box = this._box, el; if( !box ) { el = this.getPositioningElement(); box = this._box = doc.createElement( 'css3-container' ); box.style['direction'] = 'ltr'; //fix positioning bug in rtl environments this.updateVisibility(); el.parentNode.insertBefore( box, el ); } return box; }, finishUpdate: PIE.emptyFn, destroy: function() { var box = this._box, par; if( box && ( par = box.parentNode ) ) { par.removeChild( box ); } delete this._box; delete this._layers; } } ); /** * Renderer for element backgrounds. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BackgroundRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 2, boxName: 'background', needsUpdate: function() { var si = this.styleInfos; return si.backgroundInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderImageInfo.isActive() || si.borderRadiusInfo.isActive() || si.backgroundInfo.isActive() || ( si.boxShadowInfo.isActive() && si.boxShadowInfo.getProps().inset ); }, /** * Draw the shapes */ draw: function() { var bounds = this.boundsInfo.getBounds(); if( bounds.w && bounds.h ) { this.drawBgColor(); this.drawBgImages(); } }, /** * Draw the background color shape */ drawBgColor: function() { var props = this.styleInfos.backgroundInfo.getProps(), bounds = this.boundsInfo.getBounds(), el = this.targetElement, color = props && props.color, shape, w, h, s, alpha; if( color && color.alpha() > 0 ) { this.hideBackground(); shape = this.getShape( 'bgColor', 'fill', this.getBox(), 1 ); w = bounds.w; h = bounds.h; shape.stroked = false; shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = this.getBoxPath( null, 2 ); s = shape.style; s.width = w; s.height = h; shape.fill.color = color.colorValue( el ); alpha = color.alpha(); if( alpha < 1 ) { shape.fill.opacity = alpha; } } else { this.deleteShape( 'bgColor' ); } }, /** * Draw all the background image layers */ drawBgImages: function() { var props = this.styleInfos.backgroundInfo.getProps(), bounds = this.boundsInfo.getBounds(), images = props && props.bgImages, img, shape, w, h, s, i; if( images ) { this.hideBackground(); w = bounds.w; h = bounds.h; i = images.length; while( i-- ) { img = images[i]; shape = this.getShape( 'bgImage' + i, 'fill', this.getBox(), 2 ); shape.stroked = false; shape.fill.type = 'tile'; shape.fillcolor = 'none'; shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = this.getBoxPath( 0, 2 ); s = shape.style; s.width = w; s.height = h; if( img.imgType === 'linear-gradient' ) { this.addLinearGradient( shape, img ); } else { shape.fill.src = img.imgUrl; this.positionBgImage( shape, i ); } } } // Delete any bgImage shapes previously created which weren't used above i = images ? images.length : 0; while( this.deleteShape( 'bgImage' + i++ ) ) {} }, /** * Set the position and clipping of the background image for a layer * @param {Element} shape * @param {number} index */ positionBgImage: function( shape, index ) { var me = this; PIE.Util.withImageSize( shape.fill.src, function( size ) { var el = me.targetElement, bounds = me.boundsInfo.getBounds(), elW = bounds.w, elH = bounds.h; // It's possible that the element dimensions are zero now but weren't when the original // update executed, make sure that's not the case to avoid divide-by-zero error if( elW && elH ) { var fill = shape.fill, si = me.styleInfos, border = si.borderInfo.getProps(), bw = border && border.widths, bwT = bw ? bw['t'].pixels( el ) : 0, bwR = bw ? bw['r'].pixels( el ) : 0, bwB = bw ? bw['b'].pixels( el ) : 0, bwL = bw ? bw['l'].pixels( el ) : 0, bg = si.backgroundInfo.getProps().bgImages[ index ], bgPos = bg.bgPosition ? bg.bgPosition.coords( el, elW - size.w - bwL - bwR, elH - size.h - bwT - bwB ) : { x:0, y:0 }, repeat = bg.imgRepeat, pxX, pxY, clipT = 0, clipL = 0, clipR = elW + 1, clipB = elH + 1, //make sure the default clip region is not inside the box (by a subpixel) clipAdjust = PIE.ieVersion === 8 ? 0 : 1; //prior to IE8 requires 1 extra pixel in the image clip region // Positioning - find the pixel offset from the top/left and convert to a ratio // The position is shifted by half a pixel, to adjust for the half-pixel coordorigin shift which is // needed to fix antialiasing but makes the bg image fuzzy. pxX = Math.round( bgPos.x ) + bwL + 0.5; pxY = Math.round( bgPos.y ) + bwT + 0.5; fill.position = ( pxX / elW ) + ',' + ( pxY / elH ); // Set the size of the image. We have to actually set it to px values otherwise it will not honor // the user's browser zoom level and always display at its natural screen size. fill['size']['x'] = 1; //Can be any value, just has to be set to "prime" it so the next line works. Weird! fill['size'] = size.w + 'px,' + size.h + 'px'; // Repeating - clip the image shape if( repeat && repeat !== 'repeat' ) { if( repeat === 'repeat-x' || repeat === 'no-repeat' ) { clipT = pxY + 1; clipB = pxY + size.h + clipAdjust; } if( repeat === 'repeat-y' || repeat === 'no-repeat' ) { clipL = pxX + 1; clipR = pxX + size.w + clipAdjust; } shape.style.clip = 'rect(' + clipT + 'px,' + clipR + 'px,' + clipB + 'px,' + clipL + 'px)'; } } } ); }, /** * Draw the linear gradient for a gradient layer * @param {Element} shape * @param {Object} info The object holding the information about the gradient */ addLinearGradient: function( shape, info ) { var el = this.targetElement, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, fill = shape.fill, stops = info.stops, stopCount = stops.length, PI = Math.PI, GradientUtil = PIE.GradientUtil, perpendicularIntersect = GradientUtil.perpendicularIntersect, distance = GradientUtil.distance, metrics = GradientUtil.getGradientMetrics( el, w, h, info ), angle = metrics.angle, startX = metrics.startX, startY = metrics.startY, startCornerX = metrics.startCornerX, startCornerY = metrics.startCornerY, endCornerX = metrics.endCornerX, endCornerY = metrics.endCornerY, deltaX = metrics.deltaX, deltaY = metrics.deltaY, lineLength = metrics.lineLength, vmlAngle, vmlGradientLength, vmlColors, stopPx, vmlOffsetPct, p, i, j, before, after; // In VML land, the angle of the rendered gradient depends on the aspect ratio of the shape's // bounding box; for example specifying a 45 deg angle actually results in a gradient // drawn diagonally from one corner to its opposite corner, which will only appear to the // viewer as 45 degrees if the shape is equilateral. We adjust for this by taking the x/y deltas // between the start and end points, multiply one of them by the shape's aspect ratio, // and get their arctangent, resulting in an appropriate VML angle. If the angle is perfectly // horizontal or vertical then we don't need to do this conversion. vmlAngle = ( angle % 90 ) ? Math.atan2( deltaX * w / h, deltaY ) / PI * 180 : ( angle + 90 ); // VML angles are 180 degrees offset from CSS angles vmlAngle += 180; vmlAngle = vmlAngle % 360; // Add all the stops to the VML 'colors' list, including the first and last stops. // For each, we find its pixel offset along the gradient-line; if the offset of a stop is less // than that of its predecessor we increase it to be equal. We then map that pixel offset to a // percentage along the VML gradient-line, which runs from shape corner to corner. p = perpendicularIntersect( startCornerX, startCornerY, angle, endCornerX, endCornerY ); vmlGradientLength = distance( startCornerX, startCornerY, p[0], p[1] ); vmlColors = []; p = perpendicularIntersect( startX, startY, angle, startCornerX, startCornerY ); vmlOffsetPct = distance( startX, startY, p[0], p[1] ) / vmlGradientLength * 100; // Find the pixel offsets along the CSS3 gradient-line for each stop. stopPx = []; for( i = 0; i < stopCount; i++ ) { stopPx.push( stops[i].offset ? stops[i].offset.pixels( el, lineLength ) : i === 0 ? 0 : i === stopCount - 1 ? lineLength : null ); } // Fill in gaps with evenly-spaced offsets for( i = 1; i < stopCount; i++ ) { if( stopPx[ i ] === null ) { before = stopPx[ i - 1 ]; j = i; do { after = stopPx[ ++j ]; } while( after === null ); stopPx[ i ] = before + ( after - before ) / ( j - i + 1 ); } // Make sure each stop's offset is no less than the one before it stopPx[ i ] = Math.max( stopPx[ i ], stopPx[ i - 1 ] ); } // Convert to percentage along the VML gradient line and add to the VML 'colors' value for( i = 0; i < stopCount; i++ ) { vmlColors.push( ( vmlOffsetPct + ( stopPx[ i ] / vmlGradientLength * 100 ) ) + '% ' + stops[i].color.colorValue( el ) ); } // Now, finally, we're ready to render the gradient fill. Set the start and end colors to // the first and last stop colors; this just sets outer bounds for the gradient. fill['angle'] = vmlAngle; fill['type'] = 'gradient'; fill['method'] = 'sigma'; fill['color'] = stops[0].color.colorValue( el ); fill['color2'] = stops[stopCount - 1].color.colorValue( el ); if( fill['colors'] ) { //sometimes the colors object isn't initialized so we have to assign it directly (?) fill['colors'].value = vmlColors.join( ',' ); } else { fill['colors'] = vmlColors.join( ',' ); } }, /** * Hide the actual background image and color of the element. */ hideBackground: function() { var rs = this.targetElement.runtimeStyle; rs.backgroundImage = 'url(about:blank)'; //ensures the background area reacts to mouse events rs.backgroundColor = 'transparent'; }, destroy: function() { PIE.RendererBase.destroy.call( this ); var rs = this.targetElement.runtimeStyle; rs.backgroundImage = rs.backgroundColor = ''; } } ); /** * Renderer for element borders. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BorderRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 4, boxName: 'border', needsUpdate: function() { var si = this.styleInfos; return si.borderInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderRadiusInfo.isActive() && !si.borderImageInfo.isActive() && si.borderInfo.isActive(); //check BorderStyleInfo last because it's the most expensive }, /** * Draw the border shape(s) */ draw: function() { var el = this.targetElement, props = this.styleInfos.borderInfo.getProps(), bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, shape, stroke, s, segments, seg, i, len; if( props ) { this.hideBorder(); segments = this.getBorderSegments( 2 ); for( i = 0, len = segments.length; i < len; i++) { seg = segments[i]; shape = this.getShape( 'borderPiece' + i, seg.stroke ? 'stroke' : 'fill', this.getBox() ); shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = seg.path; s = shape.style; s.width = w; s.height = h; shape.filled = !!seg.fill; shape.stroked = !!seg.stroke; if( seg.stroke ) { stroke = shape.stroke; stroke['weight'] = seg.weight + 'px'; stroke.color = seg.color.colorValue( el ); stroke['dashstyle'] = seg.stroke === 'dashed' ? '2 2' : seg.stroke === 'dotted' ? '1 1' : 'solid'; stroke['linestyle'] = seg.stroke === 'double' && seg.weight > 2 ? 'ThinThin' : 'Single'; } else { shape.fill.color = seg.fill.colorValue( el ); } } // remove any previously-created border shapes which didn't get used above while( this.deleteShape( 'borderPiece' + i++ ) ) {} } }, /** * Get the VML path definitions for the border segment(s). * @param {number=} mult If specified, all coordinates will be multiplied by this number * @return {Array.<string>} */ getBorderSegments: function( mult ) { var el = this.targetElement, bounds, elW, elH, borderInfo = this.styleInfos.borderInfo, segments = [], floor, ceil, wT, wR, wB, wL, round = Math.round, borderProps, radiusInfo, radii, widths, styles, colors; if( borderInfo.isActive() ) { borderProps = borderInfo.getProps(); widths = borderProps.widths; styles = borderProps.styles; colors = borderProps.colors; if( borderProps.widthsSame && borderProps.stylesSame && borderProps.colorsSame ) { if( colors['t'].alpha() > 0 ) { // shortcut for identical border on all sides - only need 1 stroked shape wT = widths['t'].pixels( el ); //thickness wR = wT / 2; //shrink segments.push( { path: this.getBoxPath( { t: wR, r: wR, b: wR, l: wR }, mult ), stroke: styles['t'], color: colors['t'], weight: wT } ); } } else { mult = mult || 1; bounds = this.boundsInfo.getBounds(); elW = bounds.w; elH = bounds.h; wT = round( widths['t'].pixels( el ) ); wR = round( widths['r'].pixels( el ) ); wB = round( widths['b'].pixels( el ) ); wL = round( widths['l'].pixels( el ) ); var pxWidths = { 't': wT, 'r': wR, 'b': wB, 'l': wL }; radiusInfo = this.styleInfos.borderRadiusInfo; if( radiusInfo.isActive() ) { radii = this.getRadiiPixels( radiusInfo.getProps() ); } floor = Math.floor; ceil = Math.ceil; function radius( xy, corner ) { return radii ? radii[ xy ][ corner ] : 0; } function curve( corner, shrinkX, shrinkY, startAngle, ccw, doMove ) { var rx = radius( 'x', corner), ry = radius( 'y', corner), deg = 65535, isRight = corner.charAt( 1 ) === 'r', isBottom = corner.charAt( 0 ) === 'b'; return ( rx > 0 && ry > 0 ) ? ( doMove ? 'al' : 'ae' ) + ( isRight ? ceil( elW - rx ) : floor( rx ) ) * mult + ',' + // center x ( isBottom ? ceil( elH - ry ) : floor( ry ) ) * mult + ',' + // center y ( floor( rx ) - shrinkX ) * mult + ',' + // width ( floor( ry ) - shrinkY ) * mult + ',' + // height ( startAngle * deg ) + ',' + // start angle ( 45 * deg * ( ccw ? 1 : -1 ) // angle change ) : ( ( doMove ? 'm' : 'l' ) + ( isRight ? elW - shrinkX : shrinkX ) * mult + ',' + ( isBottom ? elH - shrinkY : shrinkY ) * mult ); } function line( side, shrink, ccw, doMove ) { var start = ( side === 't' ? floor( radius( 'x', 'tl') ) * mult + ',' + ceil( shrink ) * mult : side === 'r' ? ceil( elW - shrink ) * mult + ',' + floor( radius( 'y', 'tr') ) * mult : side === 'b' ? ceil( elW - radius( 'x', 'br') ) * mult + ',' + floor( elH - shrink ) * mult : // side === 'l' ? floor( shrink ) * mult + ',' + ceil( elH - radius( 'y', 'bl') ) * mult ), end = ( side === 't' ? ceil( elW - radius( 'x', 'tr') ) * mult + ',' + ceil( shrink ) * mult : side === 'r' ? ceil( elW - shrink ) * mult + ',' + ceil( elH - radius( 'y', 'br') ) * mult : side === 'b' ? floor( radius( 'x', 'bl') ) * mult + ',' + floor( elH - shrink ) * mult : // side === 'l' ? floor( shrink ) * mult + ',' + floor( radius( 'y', 'tl') ) * mult ); return ccw ? ( doMove ? 'm' + end : '' ) + 'l' + start : ( doMove ? 'm' + start : '' ) + 'l' + end; } function addSide( side, sideBefore, sideAfter, cornerBefore, cornerAfter, baseAngle ) { var vert = side === 'l' || side === 'r', sideW = pxWidths[ side ], beforeX, beforeY, afterX, afterY; if( sideW > 0 && styles[ side ] !== 'none' && colors[ side ].alpha() > 0 ) { beforeX = pxWidths[ vert ? side : sideBefore ]; beforeY = pxWidths[ vert ? sideBefore : side ]; afterX = pxWidths[ vert ? side : sideAfter ]; afterY = pxWidths[ vert ? sideAfter : side ]; if( styles[ side ] === 'dashed' || styles[ side ] === 'dotted' ) { segments.push( { path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) + curve( cornerBefore, 0, 0, baseAngle, 1, 0 ), fill: colors[ side ] } ); segments.push( { path: line( side, sideW / 2, 0, 1 ), stroke: styles[ side ], weight: sideW, color: colors[ side ] } ); segments.push( { path: curve( cornerAfter, afterX, afterY, baseAngle, 0, 1 ) + curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ), fill: colors[ side ] } ); } else { segments.push( { path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) + line( side, sideW, 0, 0 ) + curve( cornerAfter, afterX, afterY, baseAngle, 0, 0 ) + ( styles[ side ] === 'double' && sideW > 2 ? curve( cornerAfter, afterX - floor( afterX / 3 ), afterY - floor( afterY / 3 ), baseAngle - 45, 1, 0 ) + line( side, ceil( sideW / 3 * 2 ), 1, 0 ) + curve( cornerBefore, beforeX - floor( beforeX / 3 ), beforeY - floor( beforeY / 3 ), baseAngle, 1, 0 ) + 'x ' + curve( cornerBefore, floor( beforeX / 3 ), floor( beforeY / 3 ), baseAngle + 45, 0, 1 ) + line( side, floor( sideW / 3 ), 1, 0 ) + curve( cornerAfter, floor( afterX / 3 ), floor( afterY / 3 ), baseAngle, 0, 0 ) : '' ) + curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ) + line( side, 0, 1, 0 ) + curve( cornerBefore, 0, 0, baseAngle, 1, 0 ), fill: colors[ side ] } ); } } } addSide( 't', 'l', 'r', 'tl', 'tr', 90 ); addSide( 'r', 't', 'b', 'tr', 'br', 0 ); addSide( 'b', 'r', 'l', 'br', 'bl', -90 ); addSide( 'l', 'b', 't', 'bl', 'tl', -180 ); } } return segments; }, destroy: function() { var me = this; if (me.finalized || !me.styleInfos.borderImageInfo.isActive()) { me.targetElement.runtimeStyle.borderColor = ''; } PIE.RendererBase.destroy.call( me ); } } ); /** * Renderer for border-image * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BorderImageRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 5, pieceNames: [ 't', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl', 'c' ], needsUpdate: function() { return this.styleInfos.borderImageInfo.changed(); }, isActive: function() { return this.styleInfos.borderImageInfo.isActive(); }, draw: function() { this.getBox(); //make sure pieces are created var props = this.styleInfos.borderImageInfo.getProps(), borderProps = this.styleInfos.borderInfo.getProps(), bounds = this.boundsInfo.getBounds(), el = this.targetElement, pieces = this.pieces; PIE.Util.withImageSize( props.src, function( imgSize ) { var elW = bounds.w, elH = bounds.h, zero = PIE.getLength( '0' ), widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ), widthT = widths['t'].pixels( el ), widthR = widths['r'].pixels( el ), widthB = widths['b'].pixels( el ), widthL = widths['l'].pixels( el ), slices = props.slice, sliceT = slices['t'].pixels( el ), sliceR = slices['r'].pixels( el ), sliceB = slices['b'].pixels( el ), sliceL = slices['l'].pixels( el ); // Piece positions and sizes function setSizeAndPos( piece, w, h, x, y ) { var s = pieces[piece].style, max = Math.max; s.width = max(w, 0); s.height = max(h, 0); s.left = x; s.top = y; } setSizeAndPos( 'tl', widthL, widthT, 0, 0 ); setSizeAndPos( 't', elW - widthL - widthR, widthT, widthL, 0 ); setSizeAndPos( 'tr', widthR, widthT, elW - widthR, 0 ); setSizeAndPos( 'r', widthR, elH - widthT - widthB, elW - widthR, widthT ); setSizeAndPos( 'br', widthR, widthB, elW - widthR, elH - widthB ); setSizeAndPos( 'b', elW - widthL - widthR, widthB, widthL, elH - widthB ); setSizeAndPos( 'bl', widthL, widthB, 0, elH - widthB ); setSizeAndPos( 'l', widthL, elH - widthT - widthB, 0, widthT ); setSizeAndPos( 'c', elW - widthL - widthR, elH - widthT - widthB, widthL, widthT ); // image croppings function setCrops( sides, crop, val ) { for( var i=0, len=sides.length; i < len; i++ ) { pieces[ sides[i] ]['imagedata'][ crop ] = val; } } // corners setCrops( [ 'tl', 't', 'tr' ], 'cropBottom', ( imgSize.h - sliceT ) / imgSize.h ); setCrops( [ 'tl', 'l', 'bl' ], 'cropRight', ( imgSize.w - sliceL ) / imgSize.w ); setCrops( [ 'bl', 'b', 'br' ], 'cropTop', ( imgSize.h - sliceB ) / imgSize.h ); setCrops( [ 'tr', 'r', 'br' ], 'cropLeft', ( imgSize.w - sliceR ) / imgSize.w ); // edges and center // TODO right now this treats everything like 'stretch', need to support other schemes //if( props.repeat.v === 'stretch' ) { setCrops( [ 'l', 'r', 'c' ], 'cropTop', sliceT / imgSize.h ); setCrops( [ 'l', 'r', 'c' ], 'cropBottom', sliceB / imgSize.h ); //} //if( props.repeat.h === 'stretch' ) { setCrops( [ 't', 'b', 'c' ], 'cropLeft', sliceL / imgSize.w ); setCrops( [ 't', 'b', 'c' ], 'cropRight', sliceR / imgSize.w ); //} // center fill pieces['c'].style.display = props.fill ? '' : 'none'; }, this ); }, getBox: function() { var box = this.parent.getLayer( this.boxZIndex ), s, piece, i, pieceNames = this.pieceNames, len = pieceNames.length; if( !box ) { box = doc.createElement( 'border-image' ); s = box.style; s.position = 'absolute'; this.pieces = {}; for( i = 0; i < len; i++ ) { piece = this.pieces[ pieceNames[i] ] = PIE.Util.createVmlElement( 'rect' ); piece.appendChild( PIE.Util.createVmlElement( 'imagedata' ) ); s = piece.style; s['behavior'] = 'url(#default#VML)'; s.position = "absolute"; s.top = s.left = 0; piece['imagedata'].src = this.styleInfos.borderImageInfo.getProps().src; piece.stroked = false; piece.filled = false; box.appendChild( piece ); } this.parent.addLayer( this.boxZIndex, box ); } return box; }, prepareUpdate: function() { if (this.isActive()) { var me = this, el = me.targetElement, rs = el.runtimeStyle, widths = me.styleInfos.borderImageInfo.getProps().widths; // Force border-style to solid so it doesn't collapse rs.borderStyle = 'solid'; // If widths specified in border-image shorthand, override border-width // NOTE px units needed here as this gets used by the IE9 renderer too if ( widths ) { rs.borderTopWidth = widths['t'].pixels( el ) + 'px'; rs.borderRightWidth = widths['r'].pixels( el ) + 'px'; rs.borderBottomWidth = widths['b'].pixels( el ) + 'px'; rs.borderLeftWidth = widths['l'].pixels( el ) + 'px'; } // Make the border transparent me.hideBorder(); } }, destroy: function() { var me = this, rs = me.targetElement.runtimeStyle; rs.borderStyle = ''; if (me.finalized || !me.styleInfos.borderInfo.isActive()) { rs.borderColor = rs.borderWidth = ''; } PIE.RendererBase.destroy.call( this ); } } ); /** * Renderer for outset box-shadows * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BoxShadowOutsetRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 1, boxName: 'outset-box-shadow', needsUpdate: function() { var si = this.styleInfos; return si.boxShadowInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var boxShadowInfo = this.styleInfos.boxShadowInfo; return boxShadowInfo.isActive() && boxShadowInfo.getProps().outset[0]; }, draw: function() { var me = this, el = this.targetElement, box = this.getBox(), styleInfos = this.styleInfos, shadowInfos = styleInfos.boxShadowInfo.getProps().outset, radii = styleInfos.borderRadiusInfo.getProps(), len = shadowInfos.length, i = len, j, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, clipAdjust = PIE.ieVersion === 8 ? 1 : 0, //workaround for IE8 bug where VML leaks out top/left of clip region by 1px corners = [ 'tl', 'tr', 'br', 'bl' ], corner, shadowInfo, shape, fill, ss, xOff, yOff, spread, blur, shrink, color, alpha, path, totalW, totalH, focusX, focusY, isBottom, isRight; function getShadowShape( index, corner, xOff, yOff, color, blur, path ) { var shape = me.getShape( 'shadow' + index + corner, 'fill', box, len - index ), fill = shape.fill; // Position and size shape['coordsize'] = w * 2 + ',' + h * 2; shape['coordorigin'] = '1,1'; // Color and opacity shape['stroked'] = false; shape['filled'] = true; fill.color = color.colorValue( el ); if( blur ) { fill['type'] = 'gradienttitle'; //makes the VML gradient follow the shape's outline - hooray for undocumented features?!?! fill['color2'] = fill.color; fill['opacity'] = 0; } // Path shape.path = path; // This needs to go last for some reason, to prevent rendering at incorrect size ss = shape.style; ss.left = xOff; ss.top = yOff; ss.width = w; ss.height = h; return shape; } while( i-- ) { shadowInfo = shadowInfos[ i ]; xOff = shadowInfo.xOffset.pixels( el ); yOff = shadowInfo.yOffset.pixels( el ); spread = shadowInfo.spread.pixels( el ); blur = shadowInfo.blur.pixels( el ); color = shadowInfo.color; // Shape path shrink = -spread - blur; if( !radii && blur ) { // If blurring, use a non-null border radius info object so that getBoxPath will // round the corners of the expanded shadow shape rather than squaring them off. radii = PIE.BorderRadiusStyleInfo.ALL_ZERO; } path = this.getBoxPath( { t: shrink, r: shrink, b: shrink, l: shrink }, 2, radii ); if( blur ) { totalW = ( spread + blur ) * 2 + w; totalH = ( spread + blur ) * 2 + h; focusX = totalW ? blur * 2 / totalW : 0; focusY = totalH ? blur * 2 / totalH : 0; if( blur - spread > w / 2 || blur - spread > h / 2 ) { // If the blur is larger than half the element's narrowest dimension, we cannot do // this with a single shape gradient, because its focussize would have to be less than // zero which results in ugly artifacts. Instead we create four shapes, each with its // gradient focus past center, and then clip them so each only shows the quadrant // opposite the focus. for( j = 4; j--; ) { corner = corners[j]; isBottom = corner.charAt( 0 ) === 'b'; isRight = corner.charAt( 1 ) === 'r'; shape = getShadowShape( i, corner, xOff, yOff, color, blur, path ); fill = shape.fill; fill['focusposition'] = ( isRight ? 1 - focusX : focusX ) + ',' + ( isBottom ? 1 - focusY : focusY ); fill['focussize'] = '0,0'; // Clip to show only the appropriate quadrant. Add 1px to the top/left clip values // in IE8 to prevent a bug where IE8 displays one pixel outside the clip region. shape.style.clip = 'rect(' + ( ( isBottom ? totalH / 2 : 0 ) + clipAdjust ) + 'px,' + ( isRight ? totalW : totalW / 2 ) + 'px,' + ( isBottom ? totalH : totalH / 2 ) + 'px,' + ( ( isRight ? totalW / 2 : 0 ) + clipAdjust ) + 'px)'; } } else { // TODO delete old quadrant shapes if resizing expands past the barrier shape = getShadowShape( i, '', xOff, yOff, color, blur, path ); fill = shape.fill; fill['focusposition'] = focusX + ',' + focusY; fill['focussize'] = ( 1 - focusX * 2 ) + ',' + ( 1 - focusY * 2 ); } } else { shape = getShadowShape( i, '', xOff, yOff, color, blur, path ); alpha = color.alpha(); if( alpha < 1 ) { // shape.style.filter = 'alpha(opacity=' + ( alpha * 100 ) + ')'; // ss.filter = 'progid:DXImageTransform.Microsoft.BasicImage(opacity=' + ( alpha ) + ')'; shape.fill.opacity = alpha; } } } } } ); /** * Renderer for re-rendering img elements using VML. Kicks in if the img has * a border-radius applied, or if the -pie-png-fix flag is set. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.ImgRenderer = PIE.RendererBase.newRenderer( { boxZIndex: 6, boxName: 'imgEl', needsUpdate: function() { var si = this.styleInfos; return this.targetElement.src !== this._lastSrc || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderRadiusInfo.isActive() || si.backgroundInfo.isPngFix(); }, draw: function() { this._lastSrc = src; this.hideActualImg(); var shape = this.getShape( 'img', 'fill', this.getBox() ), fill = shape.fill, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, borderProps = this.styleInfos.borderInfo.getProps(), borderWidths = borderProps && borderProps.widths, el = this.targetElement, src = el.src, round = Math.round, cs = el.currentStyle, getLength = PIE.getLength, s, zero; // In IE6, the BorderRenderer will have hidden the border by moving the border-width to // the padding; therefore we want to pretend the borders have no width so they aren't doubled // when adding in the current padding value below. if( !borderWidths || PIE.ieVersion < 7 ) { zero = PIE.getLength( '0' ); borderWidths = { 't': zero, 'r': zero, 'b': zero, 'l': zero }; } shape.stroked = false; fill.type = 'frame'; fill.src = src; fill.position = (w ? 0.5 / w : 0) + ',' + (h ? 0.5 / h : 0); shape.coordsize = w * 2 + ',' + h * 2; shape.coordorigin = '1,1'; shape.path = this.getBoxPath( { t: round( borderWidths['t'].pixels( el ) + getLength( cs.paddingTop ).pixels( el ) ), r: round( borderWidths['r'].pixels( el ) + getLength( cs.paddingRight ).pixels( el ) ), b: round( borderWidths['b'].pixels( el ) + getLength( cs.paddingBottom ).pixels( el ) ), l: round( borderWidths['l'].pixels( el ) + getLength( cs.paddingLeft ).pixels( el ) ) }, 2 ); s = shape.style; s.width = w; s.height = h; }, hideActualImg: function() { this.targetElement.runtimeStyle.filter = 'alpha(opacity=0)'; }, destroy: function() { PIE.RendererBase.destroy.call( this ); this.targetElement.runtimeStyle.filter = ''; } } ); /** * Root renderer for IE9; manages the rendering layers in the element's background * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.IE9RootRenderer = PIE.RendererBase.newRenderer( { updatePos: PIE.emptyFn, updateSize: PIE.emptyFn, updateVisibility: PIE.emptyFn, updateProps: PIE.emptyFn, outerCommasRE: /^,+|,+$/g, innerCommasRE: /,+/g, setBackgroundLayer: function(zIndex, bg) { var me = this, bgLayers = me._bgLayers || ( me._bgLayers = [] ), undef; bgLayers[zIndex] = bg || undef; }, finishUpdate: function() { var me = this, bgLayers = me._bgLayers, bg; if( bgLayers && ( bg = bgLayers.join( ',' ).replace( me.outerCommasRE, '' ).replace( me.innerCommasRE, ',' ) ) !== me._lastBg ) { me._lastBg = me.targetElement.runtimeStyle.background = bg; } }, destroy: function() { this.targetElement.runtimeStyle.background = ''; delete this._bgLayers; } } ); /** * Renderer for element backgrounds, specific for IE9. Only handles translating CSS3 gradients * to an equivalent SVG data URI. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.IE9BackgroundRenderer = PIE.RendererBase.newRenderer( { bgLayerZIndex: 1, needsUpdate: function() { var si = this.styleInfos; return si.backgroundInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.backgroundInfo.isActive() || si.borderImageInfo.isActive(); }, draw: function() { var me = this, props = me.styleInfos.backgroundInfo.getProps(), bg, images, i = 0, img, bgAreaSize, bgSize; if ( props ) { bg = []; images = props.bgImages; if ( images ) { while( img = images[ i++ ] ) { if (img.imgType === 'linear-gradient' ) { bgAreaSize = me.getBgAreaSize( img.bgOrigin ); bgSize = ( img.bgSize || PIE.BgSize.DEFAULT ).pixels( me.targetElement, bgAreaSize.w, bgAreaSize.h, bgAreaSize.w, bgAreaSize.h ), bg.push( 'url(data:image/svg+xml,' + escape( me.getGradientSvg( img, bgSize.w, bgSize.h ) ) + ') ' + me.bgPositionToString( img.bgPosition ) + ' / ' + bgSize.w + 'px ' + bgSize.h + 'px ' + ( img.bgAttachment || '' ) + ' ' + ( img.bgOrigin || '' ) + ' ' + ( img.bgClip || '' ) ); } else { bg.push( img.origString ); } } } if ( props.color ) { bg.push( props.color.val ); } me.parent.setBackgroundLayer(me.bgLayerZIndex, bg.join(',')); } }, bgPositionToString: function( bgPosition ) { return bgPosition ? bgPosition.tokens.map(function(token) { return token.tokenValue; }).join(' ') : '0 0'; }, getBgAreaSize: function( bgOrigin ) { var me = this, el = me.targetElement, bounds = me.boundsInfo.getBounds(), elW = bounds.w, elH = bounds.h, w = elW, h = elH, borders, getLength, cs; if( bgOrigin !== 'border-box' ) { borders = me.styleInfos.borderInfo.getProps(); if( borders && ( borders = borders.widths ) ) { w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el ); h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el ); } } if ( bgOrigin === 'content-box' ) { getLength = PIE.getLength; cs = el.currentStyle; w -= getLength( cs.paddingLeft ).pixels( el ) + getLength( cs.paddingRight ).pixels( el ); h -= getLength( cs.paddingTop ).pixels( el ) + getLength( cs.paddingBottom ).pixels( el ); } return { w: w, h: h }; }, getGradientSvg: function( info, bgWidth, bgHeight ) { var el = this.targetElement, stopsInfo = info.stops, stopCount = stopsInfo.length, metrics = PIE.GradientUtil.getGradientMetrics( el, bgWidth, bgHeight, info ), startX = metrics.startX, startY = metrics.startY, endX = metrics.endX, endY = metrics.endY, lineLength = metrics.lineLength, stopPx, i, j, before, after, svg; // Find the pixel offsets along the CSS3 gradient-line for each stop. stopPx = []; for( i = 0; i < stopCount; i++ ) { stopPx.push( stopsInfo[i].offset ? stopsInfo[i].offset.pixels( el, lineLength ) : i === 0 ? 0 : i === stopCount - 1 ? lineLength : null ); } // Fill in gaps with evenly-spaced offsets for( i = 1; i < stopCount; i++ ) { if( stopPx[ i ] === null ) { before = stopPx[ i - 1 ]; j = i; do { after = stopPx[ ++j ]; } while( after === null ); stopPx[ i ] = before + ( after - before ) / ( j - i + 1 ); } } svg = [ '<svg width="' + bgWidth + '" height="' + bgHeight + '" xmlns="http://www.w3.org/2000/svg">' + '<defs>' + '<linearGradient id="g" gradientUnits="userSpaceOnUse"' + ' x1="' + ( startX / bgWidth * 100 ) + '%" y1="' + ( startY / bgHeight * 100 ) + '%" x2="' + ( endX / bgWidth * 100 ) + '%" y2="' + ( endY / bgHeight * 100 ) + '%">' ]; // Convert to percentage along the SVG gradient line and add to the stops list for( i = 0; i < stopCount; i++ ) { svg.push( '<stop offset="' + ( stopPx[ i ] / lineLength ) + '" stop-color="' + stopsInfo[i].color.colorValue( el ) + '" stop-opacity="' + stopsInfo[i].color.alpha() + '"/>' ); } svg.push( '</linearGradient>' + '</defs>' + '<rect width="100%" height="100%" fill="url(#g)"/>' + '</svg>' ); return svg.join( '' ); }, destroy: function() { this.parent.setBackgroundLayer( this.bgLayerZIndex ); } } ); /** * Renderer for border-image * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.IE9BorderImageRenderer = PIE.RendererBase.newRenderer( { REPEAT: 'repeat', STRETCH: 'stretch', ROUND: 'round', bgLayerZIndex: 0, needsUpdate: function() { return this.styleInfos.borderImageInfo.changed(); }, isActive: function() { return this.styleInfos.borderImageInfo.isActive(); }, draw: function() { var me = this, props = me.styleInfos.borderImageInfo.getProps(), borderProps = me.styleInfos.borderInfo.getProps(), bounds = me.boundsInfo.getBounds(), repeat = props.repeat, repeatH = repeat.h, repeatV = repeat.v, el = me.targetElement, isAsync = 0; PIE.Util.withImageSize( props.src, function( imgSize ) { var elW = bounds.w, elH = bounds.h, imgW = imgSize.w, imgH = imgSize.h, // The image cannot be referenced as a URL directly in the SVG because IE9 throws a strange // security exception (perhaps due to cross-origin policy within data URIs?) Therefore we // work around this by converting the image data into a data URI itself using a transient // canvas. This unfortunately requires the border-image src to be within the same domain, // which isn't a limitation in true border-image, so we need to try and find a better fix. imgSrc = me.imageToDataURI( props.src, imgW, imgH ), REPEAT = me.REPEAT, STRETCH = me.STRETCH, ROUND = me.ROUND, ceil = Math.ceil, zero = PIE.getLength( '0' ), widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ), widthT = widths['t'].pixels( el ), widthR = widths['r'].pixels( el ), widthB = widths['b'].pixels( el ), widthL = widths['l'].pixels( el ), slices = props.slice, sliceT = slices['t'].pixels( el ), sliceR = slices['r'].pixels( el ), sliceB = slices['b'].pixels( el ), sliceL = slices['l'].pixels( el ), centerW = elW - widthL - widthR, middleH = elH - widthT - widthB, imgCenterW = imgW - sliceL - sliceR, imgMiddleH = imgH - sliceT - sliceB, // Determine the size of each tile - 'round' is handled below tileSizeT = repeatH === STRETCH ? centerW : imgCenterW * widthT / sliceT, tileSizeR = repeatV === STRETCH ? middleH : imgMiddleH * widthR / sliceR, tileSizeB = repeatH === STRETCH ? centerW : imgCenterW * widthB / sliceB, tileSizeL = repeatV === STRETCH ? middleH : imgMiddleH * widthL / sliceL, svg, patterns = [], rects = [], i = 0; // For 'round', subtract from each tile's size enough so that they fill the space a whole number of times if (repeatH === ROUND) { tileSizeT -= (tileSizeT - (centerW % tileSizeT || tileSizeT)) / ceil(centerW / tileSizeT); tileSizeB -= (tileSizeB - (centerW % tileSizeB || tileSizeB)) / ceil(centerW / tileSizeB); } if (repeatV === ROUND) { tileSizeR -= (tileSizeR - (middleH % tileSizeR || tileSizeR)) / ceil(middleH / tileSizeR); tileSizeL -= (tileSizeL - (middleH % tileSizeL || tileSizeL)) / ceil(middleH / tileSizeL); } // Build the SVG for the border-image rendering. Add each piece as a pattern, which is then stretched // or repeated as the fill of a rect of appropriate size. svg = [ '<svg width="' + elW + '" height="' + elH + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' ]; function addImage( x, y, w, h, cropX, cropY, cropW, cropH, tileW, tileH ) { patterns.push( '<pattern patternUnits="userSpaceOnUse" id="pattern' + i + '" ' + 'x="' + (repeatH === REPEAT ? x + w / 2 - tileW / 2 : x) + '" ' + 'y="' + (repeatV === REPEAT ? y + h / 2 - tileH / 2 : y) + '" ' + 'width="' + tileW + '" height="' + tileH + '">' + '<svg width="' + tileW + '" height="' + tileH + '" viewBox="' + cropX + ' ' + cropY + ' ' + cropW + ' ' + cropH + '" preserveAspectRatio="none">' + '<image xlink:href="' + imgSrc + '" x="0" y="0" width="' + imgW + '" height="' + imgH + '" />' + '</svg>' + '</pattern>' ); rects.push( '<rect x="' + x + '" y="' + y + '" width="' + w + '" height="' + h + '" fill="url(#pattern' + i + ')" />' ); i++; } addImage( 0, 0, widthL, widthT, 0, 0, sliceL, sliceT, widthL, widthT ); // top left addImage( widthL, 0, centerW, widthT, sliceL, 0, imgCenterW, sliceT, tileSizeT, widthT ); // top center addImage( elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT, widthR, widthT ); // top right addImage( 0, widthT, widthL, middleH, 0, sliceT, sliceL, imgMiddleH, widthL, tileSizeL ); // middle left if ( props.fill ) { // center fill addImage( widthL, widthT, centerW, middleH, sliceL, sliceT, imgCenterW, imgMiddleH, tileSizeT || tileSizeB || imgCenterW, tileSizeL || tileSizeR || imgMiddleH ); } addImage( elW - widthR, widthT, widthR, middleH, imgW - sliceR, sliceT, sliceR, imgMiddleH, widthR, tileSizeR ); // middle right addImage( 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB, widthL, widthB ); // bottom left addImage( widthL, elH - widthB, centerW, widthB, sliceL, imgH - sliceB, imgCenterW, sliceB, tileSizeB, widthB ); // bottom center addImage( elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB, widthR, widthB ); // bottom right svg.push( '<defs>' + patterns.join('\n') + '</defs>' + rects.join('\n') + '</svg>' ); me.parent.setBackgroundLayer( me.bgLayerZIndex, 'url(data:image/svg+xml,' + escape( svg.join( '' ) ) + ') no-repeat border-box border-box' ); // If the border-image's src wasn't immediately available, the SVG for its background layer // will have been created asynchronously after the main element's update has finished; we'll // therefore need to force the root renderer to sync to the final background once finished. if( isAsync ) { me.parent.finishUpdate(); } }, me ); isAsync = 1; }, /** * Convert a given image to a data URI */ imageToDataURI: (function() { var uris = {}; return function( src, width, height ) { var uri = uris[ src ], image, canvas; if ( !uri ) { image = new Image(); canvas = doc.createElement( 'canvas' ); image.src = src; canvas.width = width; canvas.height = height; canvas.getContext( '2d' ).drawImage( image, 0, 0 ); uri = uris[ src ] = canvas.toDataURL(); } return uri; } })(), prepareUpdate: PIE.BorderImageRenderer.prototype.prepareUpdate, destroy: function() { var me = this, rs = me.targetElement.runtimeStyle; me.parent.setBackgroundLayer( me.bgLayerZIndex ); rs.borderColor = rs.borderStyle = rs.borderWidth = ''; } } ); PIE.Element = (function() { var wrappers = {}, lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init', pollCssProp = PIE.CSS_PREFIX + 'poll', trackActiveCssProp = PIE.CSS_PREFIX + 'track-active', trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover', hoverClass = PIE.CLASS_PREFIX + 'hover', activeClass = PIE.CLASS_PREFIX + 'active', focusClass = PIE.CLASS_PREFIX + 'focus', firstChildClass = PIE.CLASS_PREFIX + 'first-child', ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 }, classNameRegExes = {}, dummyArray = []; function addClass( el, className ) { el.className += ' ' + className; } function removeClass( el, className ) { var re = classNameRegExes[ className ] || ( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) ); el.className = el.className.replace( re, '' ); } function delayAddClass( el, className /*, className2*/ ) { var classes = dummyArray.slice.call( arguments, 1 ), i = classes.length; setTimeout( function() { if( el ) { while( i-- ) { addClass( el, classes[ i ] ); } } }, 0 ); } function delayRemoveClass( el, className /*, className2*/ ) { var classes = dummyArray.slice.call( arguments, 1 ), i = classes.length; setTimeout( function() { if( el ) { while( i-- ) { removeClass( el, classes[ i ] ); } } }, 0 ); } function Element( el ) { var renderers, rootRenderer, boundsInfo = new PIE.BoundsInfo( el ), styleInfos, styleInfosArr, initializing, initialized, eventsAttached, eventListeners = [], delayed, destroyed, poll; /** * Initialize PIE for this element. */ function init() { if( !initialized ) { var docEl, bounds, ieDocMode = PIE.ieDocMode, cs = el.currentStyle, lazy = cs.getAttribute( lazyInitCssProp ) === 'true', trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false', trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false', childRenderers; // Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll poll = cs.getAttribute( pollCssProp ); poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true'; // Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes // after load, but make sure it only gets called the first time through to avoid recursive calls to init(). if( !initializing ) { initializing = 1; el.runtimeStyle.zoom = 1; initFirstChildPseudoClass(); } boundsInfo.lock(); // If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) && ( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) { if( !delayed ) { delayed = 1; PIE.OnScroll.observe( init ); } } else { initialized = 1; delayed = initializing = 0; PIE.OnScroll.unobserve( init ); // Create the style infos and renderers if ( ieDocMode === 9 ) { styleInfos = { backgroundInfo: new PIE.BackgroundStyleInfo( el ), borderImageInfo: new PIE.BorderImageStyleInfo( el ), borderInfo: new PIE.BorderStyleInfo( el ) }; styleInfosArr = [ styleInfos.backgroundInfo, styleInfos.borderImageInfo ]; rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos ); childRenderers = [ new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer ) ]; } else { styleInfos = { backgroundInfo: new PIE.BackgroundStyleInfo( el ), borderInfo: new PIE.BorderStyleInfo( el ), borderImageInfo: new PIE.BorderImageStyleInfo( el ), borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ), boxShadowInfo: new PIE.BoxShadowStyleInfo( el ), visibilityInfo: new PIE.VisibilityStyleInfo( el ) }; styleInfosArr = [ styleInfos.backgroundInfo, styleInfos.borderInfo, styleInfos.borderImageInfo, styleInfos.borderRadiusInfo, styleInfos.boxShadowInfo, styleInfos.visibilityInfo ]; rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos ); childRenderers = [ new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ), //new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer ) ]; if( el.tagName === 'IMG' ) { childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) ); } rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way? } renderers = [ rootRenderer ].concat( childRenderers ); // Add property change listeners to ancestors if requested initAncestorEventListeners(); // Add to list of polled elements in IE8 if( poll ) { PIE.Heartbeat.observe( update ); PIE.Heartbeat.run(); } // Trigger rendering update( 1 ); } if( !eventsAttached ) { eventsAttached = 1; if( ieDocMode < 9 ) { addListener( el, 'onmove', handleMoveOrResize ); } addListener( el, 'onresize', handleMoveOrResize ); addListener( el, 'onpropertychange', propChanged ); if( trackHover ) { addListener( el, 'onmouseenter', mouseEntered ); } if( trackHover || trackActive ) { addListener( el, 'onmouseleave', mouseLeft ); } if( trackActive ) { addListener( el, 'onmousedown', mousePressed ); } if( el.tagName in PIE.focusableElements ) { addListener( el, 'onfocus', focused ); addListener( el, 'onblur', blurred ); } PIE.OnResize.observe( handleMoveOrResize ); PIE.OnUnload.observe( removeEventListeners ); } boundsInfo.unlock(); } } /** * Event handler for onmove and onresize events. Invokes update() only if the element's * bounds have previously been calculated, to prevent multiple runs during page load when * the element has no initial CSS3 properties. */ function handleMoveOrResize() { if( boundsInfo && boundsInfo.hasBeenQueried() ) { update(); } } /** * Update position and/or size as necessary. Both move and resize events call * this rather than the updatePos/Size functions because sometimes, particularly * during page load, one will fire but the other won't. */ function update( force ) { if( !destroyed ) { if( initialized ) { var i, len = renderers.length; lockAll(); for( i = 0; i < len; i++ ) { renderers[i].prepareUpdate(); } if( force || boundsInfo.positionChanged() ) { /* TODO just using getBoundingClientRect (used internally by BoundsInfo) for detecting position changes may not always be accurate; it's possible that an element will actually move relative to its positioning parent, but its position relative to the viewport will stay the same. Need to come up with a better way to track movement. The most accurate would be the same logic used in RootRenderer.updatePos() but that is a more expensive operation since it does some DOM walking, and we want this check to be as fast as possible. */ for( i = 0; i < len; i++ ) { renderers[i].updatePos(); } } if( force || boundsInfo.sizeChanged() ) { for( i = 0; i < len; i++ ) { renderers[i].updateSize(); } } rootRenderer.finishUpdate(); unlockAll(); } else if( !initializing ) { init(); } } } /** * Handle property changes to trigger update when appropriate. */ function propChanged() { var i, len = renderers.length, renderer, e = event; // Some elements like <table> fire onpropertychange events for old-school background properties // ('background', 'bgColor') when runtimeStyle background properties are changed, which // results in an infinite loop; therefore we filter out those property names. Also, 'display' // is ignored because size calculations don't work correctly immediately when its onpropertychange // event fires, and because it will trigger an onresize event anyway. if( !destroyed && !( e && e.propertyName in ignorePropertyNames ) ) { if( initialized ) { lockAll(); for( i = 0; i < len; i++ ) { renderers[i].prepareUpdate(); } for( i = 0; i < len; i++ ) { renderer = renderers[i]; // Make sure position is synced if the element hasn't already been rendered. // TODO this feels sloppy - look into merging propChanged and update functions if( !renderer.isPositioned ) { renderer.updatePos(); } if( renderer.needsUpdate() ) { renderer.updateProps(); } } rootRenderer.finishUpdate(); unlockAll(); } else if( !initializing ) { init(); } } } /** * Handle mouseenter events. Adds a custom class to the element to allow IE6 to add * hover styles to non-link elements, and to trigger a propertychange update. */ function mouseEntered() { //must delay this because the mouseenter event fires before the :hover styles are added. delayAddClass( el, hoverClass ); } /** * Handle mouseleave events */ function mouseLeft() { //must delay this because the mouseleave event fires before the :hover styles are removed. delayRemoveClass( el, hoverClass, activeClass ); } /** * Handle mousedown events. Adds a custom class to the element to allow IE6 to add * active styles to non-link elements, and to trigger a propertychange update. */ function mousePressed() { //must delay this because the mousedown event fires before the :active styles are added. delayAddClass( el, activeClass ); // listen for mouseups on the document; can't just be on the element because the user might // have dragged out of the element while the mouse button was held down PIE.OnMouseup.observe( mouseReleased ); } /** * Handle mouseup events */ function mouseReleased() { //must delay this because the mouseup event fires before the :active styles are removed. delayRemoveClass( el, activeClass ); PIE.OnMouseup.unobserve( mouseReleased ); } /** * Handle focus events. Adds a custom class to the element to trigger a propertychange update. */ function focused() { //must delay this because the focus event fires before the :focus styles are added. delayAddClass( el, focusClass ); } /** * Handle blur events */ function blurred() { //must delay this because the blur event fires before the :focus styles are removed. delayRemoveClass( el, focusClass ); } /** * Handle property changes on ancestors of the element; see initAncestorEventListeners() * which adds these listeners as requested with the -pie-watch-ancestors CSS property. */ function ancestorPropChanged() { var name = event.propertyName; if( name === 'className' || name === 'id' ) { propChanged(); } } function lockAll() { boundsInfo.lock(); for( var i = styleInfosArr.length; i--; ) { styleInfosArr[i].lock(); } } function unlockAll() { for( var i = styleInfosArr.length; i--; ) { styleInfosArr[i].unlock(); } boundsInfo.unlock(); } function addListener( targetEl, type, handler ) { targetEl.attachEvent( type, handler ); eventListeners.push( [ targetEl, type, handler ] ); } /** * Remove all event listeners from the element and any monitored ancestors. */ function removeEventListeners() { if (eventsAttached) { var i = eventListeners.length, listener; while( i-- ) { listener = eventListeners[ i ]; listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] ); } PIE.OnUnload.unobserve( removeEventListeners ); eventsAttached = 0; eventListeners = []; } } /** * Clean everything up when the behavior is removed from the element, or the element * is manually destroyed. */ function destroy() { if( !destroyed ) { var i, len; removeEventListeners(); destroyed = 1; // destroy any active renderers if( renderers ) { for( i = 0, len = renderers.length; i < len; i++ ) { renderers[i].finalized = 1; renderers[i].destroy(); } } // Remove from list of polled elements in IE8 if( poll ) { PIE.Heartbeat.unobserve( update ); } // Stop onresize listening PIE.OnResize.unobserve( update ); // Kill references renderers = boundsInfo = styleInfos = styleInfosArr = el = null; } } /** * If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and * other event listeners to ancestor(s) of the element so we can pick up style changes * based on CSS rules using descendant selectors. */ function initAncestorEventListeners() { var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ), i, a; if( watch ) { watch = parseInt( watch, 10 ); i = 0; a = el.parentNode; while( a && ( watch === 'NaN' || i++ < watch ) ) { addListener( a, 'onpropertychange', ancestorPropChanged ); addListener( a, 'onmouseenter', mouseEntered ); addListener( a, 'onmouseleave', mouseLeft ); addListener( a, 'onmousedown', mousePressed ); if( a.tagName in PIE.focusableElements ) { addListener( a, 'onfocus', focused ); addListener( a, 'onblur', blurred ); } a = a.parentNode; } } } /** * If the target element is a first child, add a pie_first-child class to it. This allows using * the added class as a workaround for the fact that PIE's rendering element breaks the :first-child * pseudo-class selector. */ function initFirstChildPseudoClass() { var tmpEl = el, isFirst = 1; while( tmpEl = tmpEl.previousSibling ) { if( tmpEl.nodeType === 1 ) { isFirst = 0; break; } } if( isFirst ) { addClass( el, firstChildClass ); } } // These methods are all already bound to this instance so there's no need to wrap them // in a closure to maintain the 'this' scope object when calling them. this.init = init; this.update = update; this.destroy = destroy; this.el = el; } Element.getInstance = function( el ) { var id = PIE.Util.getUID( el ); return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) ); }; Element.destroy = function( el ) { var id = PIE.Util.getUID( el ), wrapper = wrappers[ id ]; if( wrapper ) { wrapper.destroy(); delete wrappers[ id ]; } }; Element.destroyAll = function() { var els = [], wrapper; if( wrappers ) { for( var w in wrappers ) { if( wrappers.hasOwnProperty( w ) ) { wrapper = wrappers[ w ]; els.push( wrapper.el ); wrapper.destroy(); } } wrappers = {}; } return els; }; return Element; })(); /* * This file exposes the public API for invoking PIE. */ /** * @property supportsVML * True if the current IE browser environment has a functioning VML engine. Should be true * in most IEs, but in rare cases may be false. If false, PIE will exit immediately when * attached to an element; this property may be used for debugging or by external scripts * to perform some special action when VML support is absent. * @type {boolean} */ PIE[ 'supportsVML' ] = PIE.supportsVML; /** * Programatically attach PIE to a single element. * @param {Element} el */ PIE[ 'attach' ] = function( el ) { if (PIE.ieDocMode < 10 && PIE.supportsVML) { PIE.Element.getInstance( el ).init(); } }; /** * Programatically detach PIE from a single element. * @param {Element} el */ PIE[ 'detach' ] = function( el ) { PIE.Element.destroy( el ); }; } // if( !PIE ) })();
JavaScript
/* PIE: CSS3 rendering for IE Version 2.0beta1 http://css3pie.com Dual-licensed for use under the Apache License Version 2.0 or the General Public License (GPL) Version 2. */ (function( win, doc ) { var PIE = win[ 'PIE' ] || ( win[ 'PIE' ] = {} ); /** * Simple utility for merging objects * @param {Object} obj1 The main object into which all others will be merged * @param {...Object} var_args Other objects which will be merged into the first, in order */ PIE.merge = function( obj1 ) { var i, len, p, objN, args = arguments; for( i = 1, len = args.length; i < len; i++ ) { objN = args[i]; for( p in objN ) { if( objN.hasOwnProperty( p ) ) { obj1[ p ] = objN[ p ]; } } } return obj1; }; PIE.merge(PIE, { // Constants CSS_PREFIX: '-pie-', STYLE_PREFIX: 'Pie', CLASS_PREFIX: 'pie_', tableCellTags: { 'TD': 1, 'TH': 1 }, /** * Lookup table of elements which cannot take custom children. */ childlessElements: { 'TABLE':1, 'THEAD':1, 'TBODY':1, 'TFOOT':1, 'TR':1, 'INPUT':1, 'TEXTAREA':1, 'SELECT':1, 'OPTION':1, 'IMG':1, 'HR':1 }, /** * Elements that can receive user focus */ focusableElements: { 'A':1, 'INPUT':1, 'TEXTAREA':1, 'SELECT':1, 'BUTTON':1 }, /** * Values of the type attribute for input elements displayed as buttons */ inputButtonTypes: { 'submit':1, 'button':1, 'reset':1 }, emptyFn: function() {} }); // Force the background cache to be used. No reason it shouldn't be. try { doc.execCommand( 'BackgroundImageCache', false, true ); } catch(e) {} (function() { /* * IE version detection approach by James Padolsey, with modifications -- from * http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/ */ var ieVersion = 4, div = doc.createElement('div'), all = div.getElementsByTagName('i'), shape; while ( div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->', all[0] ) {} PIE.ieVersion = ieVersion; // Detect IE6 if( ieVersion === 6 ) { // IE6 can't access properties with leading dash, but can without it. PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' ); } PIE.ieDocMode = doc.documentMode || PIE.ieVersion; // Detect VML support (a small number of IE installs don't have a working VML engine) div.innerHTML = '<v:shape adj="1"/>'; shape = div.firstChild; shape.style['behavior'] = 'url(#default#VML)'; PIE.supportsVML = (typeof shape['adj'] === "object"); })(); /** * Utility functions */ (function() { var idNum = 0, imageSizes = {}; PIE.Util = { /** * Generate and return a unique ID for a given object. The generated ID is stored * as a property of the object for future reuse. For DOM Elements, don't use this * but use the IE-native uniqueID property instead. * @param {Object} obj */ getUID: function( obj ) { return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + idNum++ ); }, /** * Execute a callback function, passing it the dimensions of a given image once * they are known. * @param {string} src The source URL of the image * @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known * @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function */ withImageSize: function( src, func, ctx ) { var size = imageSizes[ src ], img, queue; if( size ) { // If we have a queue, add to it if( Object.prototype.toString.call( size ) === '[object Array]' ) { size.push( [ func, ctx ] ); } // Already have the size cached, call func right away else { func.call( ctx, size ); } } else { queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue img = new Image(); img.onload = function() { size = imageSizes[ src ] = { w: img.width, h: img.height }; for( var i = 0, len = queue.length; i < len; i++ ) { queue[ i ][ 0 ].call( queue[ i ][ 1 ], size ); } img.onload = null; }; img.src = src; } } }; })();/** * Utility functions for handling gradients */ PIE.GradientUtil = { toSideAngles: { 'top': 0, 'right': 90, 'bottom': 180, 'left': 270 }, getGradientMetrics: function( el, width, height, gradientInfo ) { var angle = gradientInfo.angle, toPos = gradientInfo.gradientTo, dX, dY, endPoint, startX, startY, endX, endY; // If an angle was specified, just use it if (angle) { angle = angle.degrees(); } // If a to-position was specified, find the appropriate angle for it else if (toPos) { // To a corner; find the adjacent corners and use the angle perpendicular to them if (toPos[1]) { dX = ( toPos[0] == 'top' || toPos[1] == 'top' ) ? width : -width; dY = ( toPos[0] == 'left' || toPos[1] == 'left' ) ? -height : height; angle = Math.atan2(dY, dX) * 180 / Math.PI; } // To a side; map to a vertical/horizontal angle else { angle = this.toSideAngles[toPos[0]]; } } // Neither specified; default is top to bottom else { angle = 180; } // Normalize the angle to a value between [0, 360) while( angle < 0 ) { angle += 360; } angle = angle % 360; // Find the end point of the gradient line, extending the angle from the center point // to where it intersects the perpendicular line passing through the nearest corner. endPoint = PIE.GradientUtil.perpendicularIntersect(width / 2, height / 2, angle, ( angle >= 180 ? 0 : width ), ( angle < 90 || angle > 270 ? 0 : height ) ); endX = endPoint[0]; endY = endPoint[1]; startX = width - endX; startY = height - endY; return { angle: angle, endX: endX, endY: endY, startX: startX, startY: startY, lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY ) }; }, /** * Find the point along a given line (defined by a starting point and an angle), at which * that line is intersected by a perpendicular line extending through another point. * @param x1 - x coord of the starting point * @param y1 - y coord of the starting point * @param angle - angle of the line extending from the starting point (in degrees) * @param x2 - x coord of point along the perpendicular line * @param y2 - y coord of point along the perpendicular line * @return [ x, y ] */ perpendicularIntersect: function( x1, y1, angle, x2, y2 ) { // Handle straight vertical and horizontal angles, for performance and to avoid // divide-by-zero errors. if( angle === 0 || angle === 180 ) { return [ x1, y2 ]; } else if( angle === 90 || angle === 270 ) { return [ x2, y1 ]; } else { // General approach: determine the Ax+By=C formula for each line (the slope of the second // line is the negative inverse of the first) and then solve for where both formulas have // the same x/y values. var a1 = Math.tan( ( angle - 90 ) * Math.PI / 180 ), c1 = a1 * x1 - y1, a2 = -1 / a1, c2 = a2 * x2 - y2, d = a2 - a1, endX = ( c2 - c1 ) / d, endY = ( a1 * c2 - a2 * c1 ) / d; return [ endX, endY ]; } }, /** * Find the distance between two points * @param {Number} p1x * @param {Number} p1y * @param {Number} p2x * @param {Number} p2y * @return {Number} the distance */ distance: function( p1x, p1y, p2x, p2y ) { var dx = p2x - p1x, dy = p2y - p1y; return Math.abs( dx === 0 ? dy : dy === 0 ? dx : Math.sqrt( dx * dx + dy * dy ) ); } };/** * */ PIE.Observable = function() { /** * List of registered observer functions */ this.observers = []; /** * Hash of function ids to their position in the observers list, for fast lookup */ this.indexes = {}; }; PIE.Observable.prototype = { observe: function( fn ) { var id = PIE.Util.getUID( fn ), indexes = this.indexes, observers = this.observers; if( !( id in indexes ) ) { indexes[ id ] = observers.length; observers.push( fn ); } }, unobserve: function( fn ) { var id = PIE.Util.getUID( fn ), indexes = this.indexes; if( id && id in indexes ) { delete this.observers[ indexes[ id ] ]; delete indexes[ id ]; } }, fire: function() { var o = this.observers, i = o.length; while( i-- ) { o[ i ] && o[ i ](); } } };/* * Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not * always firing the onmove and onresize events when elements are moved or resized. We check a few * times every second to make sure the elements have the correct position and size. See Element.js * which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9 * and false elsewhere. */ PIE.Heartbeat = new PIE.Observable(); PIE.Heartbeat.run = function() { var me = this, interval; if( !me.running ) { interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250; (function beat() { me.fire(); setTimeout(beat, interval); })(); me.running = 1; } }; /** * Create an observable listener for the onunload event */ (function() { PIE.OnUnload = new PIE.Observable(); function handleUnload() { PIE.OnUnload.fire(); win.detachEvent( 'onunload', handleUnload ); win[ 'PIE' ] = null; } win.attachEvent( 'onunload', handleUnload ); /** * Attach an event which automatically gets detached onunload */ PIE.OnUnload.attachManagedEvent = function( target, name, handler ) { target.attachEvent( name, handler ); this.observe( function() { target.detachEvent( name, handler ); } ); }; })()/** * Create a single observable listener for window resize events. */ PIE.OnResize = new PIE.Observable(); PIE.OnUnload.attachManagedEvent( win, 'onresize', function() { PIE.OnResize.fire(); } ); /** * Create a single observable listener for scroll events. Used for lazy loading based * on the viewport, and for fixed position backgrounds. */ (function() { PIE.OnScroll = new PIE.Observable(); function scrolled() { PIE.OnScroll.fire(); } PIE.OnUnload.attachManagedEvent( win, 'onscroll', scrolled ); PIE.OnResize.observe( scrolled ); })(); /** * Create a single observable listener for document mouseup events. */ PIE.OnMouseup = new PIE.Observable(); PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } ); /** * Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique * value is returned from PIE.getLength() - always use that instead of instantiating directly. * @constructor * @param {string} val The CSS string representing the length. It is assumed that this will already have * been validated as a valid length or percentage syntax. */ PIE.Length = (function() { var lengthCalcEl = doc.createElement( 'length-calc' ), parent = doc.body || doc.documentElement, s = lengthCalcEl.style, conversions = {}, units = [ 'mm', 'cm', 'in', 'pt', 'pc' ], i = units.length, instances = {}; s.position = 'absolute'; s.top = s.left = '-9999px'; parent.appendChild( lengthCalcEl ); while( i-- ) { s.width = '100' + units[i]; conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100; } parent.removeChild( lengthCalcEl ); // All calcs from here on will use 1em s.width = '1em'; function Length( val ) { this.val = val; } Length.prototype = { /** * Regular expression for matching the length unit * @private */ unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/, /** * Get the numeric value of the length * @return {number} The value */ getNumber: function() { var num = this.num, UNDEF; if( num === UNDEF ) { num = this.num = parseFloat( this.val ); } return num; }, /** * Get the unit of the length * @return {string} The unit */ getUnit: function() { var unit = this.unit, m; if( !unit ) { m = this.val.match( this.unitRE ); unit = this.unit = ( m && m[0] ) || 'px'; } return unit; }, /** * Determine whether this is a percentage length value * @return {boolean} */ isPercentage: function() { return this.getUnit() === '%'; }, /** * Resolve this length into a number of pixels. * @param {Element} el - the context element, used to resolve font-relative values * @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a * function which will be called to return the number. */ pixels: function( el, pct100 ) { var num = this.getNumber(), unit = this.getUnit(); switch( unit ) { case "px": return num; case "%": return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100; case "em": return num * this.getEmPixels( el ); case "ex": return num * this.getEmPixels( el ) / 2; default: return num * conversions[ unit ]; } }, /** * The em and ex units are relative to the font-size of the current element, * however if the font-size is set using non-pixel units then we get that value * rather than a pixel conversion. To get around this, we keep a floating element * with width:1em which we insert into the target element and then read its offsetWidth. * For elements that won't accept a child we insert into the parent node and perform * additional calculation. If the font-size *is* specified in pixels, then we use that * directly to avoid the expensive DOM manipulation. * @param {Element} el * @return {number} */ getEmPixels: function( el ) { var fs = el.currentStyle.fontSize, px, parent, me; if( fs.indexOf( 'px' ) > 0 ) { return parseFloat( fs ); } else if( el.tagName in PIE.childlessElements ) { me = this; parent = el.parentNode; return PIE.getLength( fs ).pixels( parent, function() { return me.getEmPixels( parent ); } ); } else { el.appendChild( lengthCalcEl ); px = lengthCalcEl.offsetWidth; if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is el.removeChild( lengthCalcEl ); } return px; } } }; /** * Convert a pixel length into a point length */ Length.pxToPt = function( px ) { return px / conversions[ 'pt' ]; }; /** * Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value. * @param {string} val The CSS string representing the length. It is assumed that this will already have * been validated as a valid length or percentage syntax. */ PIE.getLength = function( val ) { return instances[ val ] || ( instances[ val ] = new Length( val ) ); }; return Length; })(); /** * Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages. * @constructor * @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value. */ PIE.BgPosition = (function() { var length_fifty = PIE.getLength( '50%' ), vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 }, horiz_idents = { 'left': 1, 'center': 1, 'right': 1 }; function BgPosition( tokens ) { this.tokens = tokens; } BgPosition.prototype = { /** * Normalize the values into the form: * [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ] * where: xOffsetSide is either 'left' or 'right', * yOffsetSide is either 'top' or 'bottom', * and x/yOffsetLength are both PIE.Length objects. * @return {Array} */ getValues: function() { if( !this._values ) { var tokens = this.tokens, len = tokens.length, Tokenizer = PIE.Tokenizer, identType = Tokenizer.Type, length_zero = PIE.getLength( '0' ), type_ident = identType.IDENT, type_length = identType.LENGTH, type_percent = identType.PERCENT, type, value, vals = [ 'left', length_zero, 'top', length_zero ]; // If only one value, the second is assumed to be 'center' if( len === 1 ) { tokens.push( new Tokenizer.Token( type_ident, 'center' ) ); len++; } // Two values - CSS2 if( len === 2 ) { // If both idents, they can appear in either order, so switch them if needed if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) && tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) { tokens.push( tokens.shift() ); } if( tokens[0].tokenType & type_ident ) { if( tokens[0].tokenValue === 'center' ) { vals[1] = length_fifty; } else { vals[0] = tokens[0].tokenValue; } } else if( tokens[0].isLengthOrPercent() ) { vals[1] = PIE.getLength( tokens[0].tokenValue ); } if( tokens[1].tokenType & type_ident ) { if( tokens[1].tokenValue === 'center' ) { vals[3] = length_fifty; } else { vals[2] = tokens[1].tokenValue; } } else if( tokens[1].isLengthOrPercent() ) { vals[3] = PIE.getLength( tokens[1].tokenValue ); } } // Three or four values - CSS3 else { // TODO } this._values = vals; } return this._values; }, /** * Find the coordinates of the background image from the upper-left corner of the background area. * Note that these coordinate values are not rounded. * @param {Element} el * @param {number} width - the width for percentages (background area width minus image width) * @param {number} height - the height for percentages (background area height minus image height) * @return {Object} { x: Number, y: Number } */ coords: function( el, width, height ) { var vals = this.getValues(), pxX = vals[1].pixels( el, width ), pxY = vals[3].pixels( el, height ); return { x: vals[0] === 'right' ? width - pxX : pxX, y: vals[2] === 'bottom' ? height - pxY : pxY }; } }; return BgPosition; })(); /** * Wrapper for a CSS3 background-size value. * @constructor * @param {String|PIE.Length} w The width parameter * @param {String|PIE.Length} h The height parameter, if any */ PIE.BgSize = (function() { var CONTAIN = 'contain', COVER = 'cover', AUTO = 'auto'; function BgSize( w, h ) { this.w = w; this.h = h; } BgSize.prototype = { pixels: function( el, areaW, areaH, imgW, imgH ) { var me = this, w = me.w, h = me.h, areaRatio = areaW / areaH, imgRatio = imgW / imgH; if ( w === CONTAIN ) { w = imgRatio > areaRatio ? areaW : areaH * imgRatio; h = imgRatio > areaRatio ? areaW / imgRatio : areaH; } else if ( w === COVER ) { w = imgRatio < areaRatio ? areaW : areaH * imgRatio; h = imgRatio < areaRatio ? areaW / imgRatio : areaH; } else if ( w === AUTO ) { h = ( h === AUTO ? imgH : h.pixels( el, areaH ) ); w = h * imgRatio; } else { w = w.pixels( el, areaW ); h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) ); } return { w: w, h: h }; } }; BgSize.DEFAULT = new BgSize( AUTO, AUTO ); return BgSize; })(); /** * Wrapper for angle values; handles conversion to degrees from all allowed angle units * @constructor * @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated. */ PIE.Angle = (function() { function Angle( val ) { this.val = val; } Angle.prototype = { unitRE: /[a-z]+$/i, /** * @return {string} The unit of the angle value */ getUnit: function() { return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() ); }, /** * Get the numeric value of the angle in degrees. * @return {number} The degrees value */ degrees: function() { var deg = this._deg, u, n; if( deg === undefined ) { u = this.getUnit(); n = parseFloat( this.val, 10 ); deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 ); } return deg; } }; return Angle; })();/** * Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique * value is returned from PIE.getColor() - always use that instead of instantiating directly. * @constructor * @param {string} val The raw CSS string value for the color */ PIE.Color = (function() { /* * hsl2rgb from http://codingforums.com/showthread.php?t=11156 * code by Jason Karl Davis (http://www.jasonkarldavis.com) * swiped from cssSandpaper by Zoltan Hawryluk (http://www.useragentman.com/blog/csssandpaper-a-css3-javascript-library/) * modified for formatting and size optimizations */ function hsl2rgb( h, s, l ) { var m1, m2, r, g, b, round = Math.round; s /= 100; l /= 100; if ( !s ) { r = g = b = l * 255; } else { if ( l <= 0.5 ) { m2 = l * ( s + 1 ); } else { m2 = l + s - l * s; } m1 = l * 2 - m2; h = ( h % 360 ) / 360; r = hueToRgb( m1, m2, h + 1/3 ); g = hueToRgb( m1, m2, h ); b = hueToRgb( m1, m2, h - 1/3 ); } return { r: round( r ), g: round( g ), b: round( b ) }; } function hueToRgb( m1, m2, hue ) { var v; if ( hue < 0 ) { hue += 1; } else if ( hue > 1 ) { hue -= 1; } if ( 6 * hue < 1 ) { v = m1 + ( m2 - m1 ) * hue * 6; } else if ( 2 * hue < 1 ) { v = m2; } else if ( 3 * hue < 2 ) { v = m1 + ( m2 - m1 ) * ( 2/3 - hue ) * 6; } else { v = m1; } return 255 * v; } var instances = {}; function Color( val ) { this.val = val; } /** * Regular expression for matching rgba colors and extracting their components * @type {RegExp} */ Color.rgbOrRgbaRE = /\s*rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(\d+|\d*\.\d+))?\s*\)\s*/; Color.hslOrHslaRE = /\s*hsla?\(\s*(\d*\.?\d+)\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*(,\s*(\d+|\d*\.\d+))?\s*\)\s*/; /** * Hash of color keyword names to their corresponding hex values. Encoded for * small size and expanded into a hash on startup. */ Color.names = {}; var names = 'black|0|navy|3k|darkblue|b|mediumblue|1u|blue|1e|darkgreen|jk1|green|5j4|teal|3k|darkcyan|26j|deepskyblue|ad0|darkturquoise|2xe|mediumspringgreen|8nd|lime|va|springgreen|3j|aqua|3k|cyan|0|midnightblue|xunl|dodgerblue|7ogf|lightseagreen|2zsb|forestgreen|2lbs|seagreen|guut|darkslategray|12pk|limegreen|4wkj|mediumseagreen|dwlb|turquoise|5v8f|royalblue|r2p|steelblue|75qr|darkslateblue|2fh3|mediumturquoise|ta9|indigo|32d2|darkolivegreen|emr1|cadetblue|ebu9|cornflowerblue|6z4d|mediumaquamarine|3459|dimgray|3nwf|slateblue|1bok|olivedrab|1opi|slategray|6y5p|lightslategray|9vk9|mediumslateblue|5g0l|lawngreen|27ma|chartreuse|48ao|aquamarine|5w|maroon|18|purple|3k|olive|p6o|gray|3k|lightslateblue|5j7j|skyblue|4q98|lightskyblue|f|blueviolet|3bhk|darkred|15we|darkmagenta|3v|saddlebrown|djc|darkseagreen|69vg|lightgreen|1og1|mediumpurple|3ivc|darkviolet|sfv|palegreen|6zt1|darkorchid|awk|yellowgreen|292e|sienna|7r3v|brown|6sxp|darkgray|6bgf|lightblue|5vlp|greenyellow|7k9|paleturquoise|2pxb|lightsteelblue|169c|powderblue|5jc|firebrick|1rgc|darkgoldenrod|8z55|mediumorchid|2jm0|rosybrown|34jg|darkkhaki|1mfw|silver|49jp|mediumvioletred|8w5h|indianred|8tef|peru|82r|violetred|3ntd|feldspar|212d|chocolate|16eh|tan|ewe|lightgrey|1kqv|palevioletred|6h8g|metle|fnp|orchid|2dj2|goldenrod|abu|crimson|20ik|gainsboro|13mo|plum|12pt|burlywood|1j8q|lightcyan|3794|lavender|8agr|darksalmon|3rsw|violet|6wz8|palegoldenrod|k3g|lightcoral|28k6|khaki|k5o|aliceblue|3n7|honeydew|1dd|azure|f|sandybrown|5469|wheat|1q37|beige|4kp|whitesmoke|p|mintcream|1z9|ghostwhite|46bp|salmon|25bn|antiquewhite|l7p|linen|zz|lightgoldenrodyellow|1yk|oldlace|46qc|red|1gka|magenta|73|fuchsia|0|deeppink|3v8|orangered|9kd|tomato|5zb|hotpink|19p|coral|49o|darkorange|2i8|lightsalmon|41m|orange|w6|lightpink|3i9|pink|1ze|gold|4dx|peachpuff|qh|navajowhite|s4|moccasin|16w|bisque|f|mistyrose|t|blanchedalmond|1d8|papayawhip|so|lavenderblush|80|seashell|zd|cornsilk|ku|lemonchiffon|dt|floralwhite|z|snow|a|yellow|sm|lightyellow|68|ivory|g|white|f'.split('|'), i = 0, len = names.length, color = 0, hexColor; for(; i < len; i += 2) { color += parseInt(names[i + 1], 36); hexColor = color.toString(16); Color.names[names[i]] = '#000000'.slice(0, -hexColor.length) + hexColor; } Color.prototype = { /** * @private */ parse: function() { if( !this._color ) { var me = this, color = me.val, alpha, vLower, m, rgb; // RGB or RGBA colors if( m = color.match( Color.rgbOrRgbaRE ) ) { color = me.rgbToHex( +m[1], +m[2], +m[3] ); alpha = m[5] ? +m[5] : 1; } // HSL or HSLA colors else if( m = color.match( Color.hslOrHslaRE ) ) { rgb = hsl2rgb( m[1], m[2], m[3] ); color = me.rgbToHex( rgb.r, rgb.g, rgb.b ); alpha = m[5] ? +m[5] : 1; } else { if( Color.names.hasOwnProperty( vLower = color.toLowerCase() ) ) { color = Color.names[vLower]; } alpha = ( color === 'transparent' ? 0 : 1 ); } me._color = color; me._alpha = alpha; } }, /** * Converts RGB color channels to a hex value string */ rgbToHex: function( r, g, b ) { return '#' + ( r < 16 ? '0' : '' ) + r.toString( 16 ) + ( g < 16 ? '0' : '' ) + g.toString( 16 ) + ( b < 16 ? '0' : '' ) + b.toString( 16 ); }, /** * Retrieve the value of the color in a format usable by IE natively. This will be the same as * the raw input value, except for rgb(a) and hsl(a) values which will be converted to a hex value. * @param {Element} el The context element, used to get 'currentColor' keyword value. * @return {string} Color value */ colorValue: function( el ) { this.parse(); return this._color === 'currentColor' ? PIE.getColor( el.currentStyle.color ).colorValue( el ) : this._color; }, /** * Retrieve the value of the color in a normalized six-digit hex format. * @param el */ hexValue: function( el ) { var color = this.colorValue( el ); // At this point the color should be either a 3- or 6-digit hex value, or the string "transparent". function ch( i ) { return color.charAt( i ); } // Fudge transparent to black - should be ignored anyway since its alpha will be 0 if( color === 'transparent' ) { color = '#000'; } // Expand 3-digit to 6-digit hex if( ch(0) === '#' && color.length === 4 ) { color = '#' + ch(1) + ch(1) + ch(2) + ch(2) + ch(3) + ch(3); } return color; }, /** * Retrieve the alpha value of the color. Will be 1 for all values except for rgba values * with an alpha component. * @return {number} The alpha value, from 0 to 1. */ alpha: function() { this.parse(); return this._alpha; } }; /** * Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value. * @param {string} val The CSS string representing the color. It is assumed that this will already have * been validated as a valid color syntax. */ PIE.getColor = function(val) { return instances[ val ] || ( instances[ val ] = new Color( val ) ); }; return Color; })();/** * A tokenizer for CSS value strings. * @constructor * @param {string} css The CSS value string */ PIE.Tokenizer = (function() { function Tokenizer( css ) { this.css = css; this.ch = 0; this.tokens = []; this.tokenIndex = 0; } /** * Enumeration of token type constants. * @enum {number} */ var Type = Tokenizer.Type = { ANGLE: 1, CHARACTER: 2, COLOR: 4, DIMEN: 8, FUNCTION: 16, IDENT: 32, LENGTH: 64, NUMBER: 128, OPERATOR: 256, PERCENT: 512, STRING: 1024, URL: 2048 }; /** * A single token * @constructor * @param {number} type The type of the token - see PIE.Tokenizer.Type * @param {string} value The value of the token */ Tokenizer.Token = function( type, value ) { this.tokenType = type; this.tokenValue = value; }; Tokenizer.Token.prototype = { isLength: function() { return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' ); }, isLengthOrPercent: function() { return this.isLength() || this.tokenType & Type.PERCENT; } }; Tokenizer.prototype = { whitespace: /\s/, number: /^[\+\-]?(\d*\.)?\d+/, url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i, ident: /^\-?[_a-z][\w-]*/i, string: /^("([^"]*)"|'([^']*)')/, operator: /^[\/,]/, hash: /^#[\w]+/, hashColor: /^#([\da-f]{6}|[\da-f]{3})/i, unitTypes: { 'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH, 'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH, 'pt': Type.LENGTH, 'pc': Type.LENGTH, 'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE }, colorFunctions: { 'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1 }, /** * Advance to and return the next token in the CSS string. If the end of the CSS string has * been reached, null will be returned. * @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev(). * @return {PIE.Tokenizer.Token} */ next: function( forget ) { var css, ch, firstChar, match, val, me = this; function newToken( type, value ) { var tok = new Tokenizer.Token( type, value ); if( !forget ) { me.tokens.push( tok ); me.tokenIndex++; } return tok; } function failure() { me.tokenIndex++; return null; } // In case we previously backed up, return the stored token in the next slot if( this.tokenIndex < this.tokens.length ) { return this.tokens[ this.tokenIndex++ ]; } // Move past leading whitespace characters while( this.whitespace.test( this.css.charAt( this.ch ) ) ) { this.ch++; } if( this.ch >= this.css.length ) { return failure(); } ch = this.ch; css = this.css.substring( this.ch ); firstChar = css.charAt( 0 ); switch( firstChar ) { case '#': if( match = css.match( this.hashColor ) ) { this.ch += match[0].length; return newToken( Type.COLOR, match[0] ); } break; case '"': case "'": if( match = css.match( this.string ) ) { this.ch += match[0].length; return newToken( Type.STRING, match[2] || match[3] || '' ); } break; case "/": case ",": this.ch++; return newToken( Type.OPERATOR, firstChar ); case 'u': if( match = css.match( this.url ) ) { this.ch += match[0].length; return newToken( Type.URL, match[2] || match[3] || match[4] || '' ); } } // Numbers and values starting with numbers if( match = css.match( this.number ) ) { val = match[0]; this.ch += val.length; // Check if it is followed by a unit if( css.charAt( val.length ) === '%' ) { this.ch++; return newToken( Type.PERCENT, val + '%' ); } if( match = css.substring( val.length ).match( this.ident ) ) { val += match[0]; this.ch += match[0].length; return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val ); } // Plain ol' number return newToken( Type.NUMBER, val ); } // Identifiers if( match = css.match( this.ident ) ) { val = match[0]; this.ch += val.length; // Named colors if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) { return newToken( Type.COLOR, val ); } // Functions if( css.charAt( val.length ) === '(' ) { this.ch++; // Color values in function format: rgb, rgba, hsl, hsla if( val.toLowerCase() in this.colorFunctions ) { function isNum( tok ) { return tok && tok.tokenType & Type.NUMBER; } function isNumOrPct( tok ) { return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) ); } function isValue( tok, val ) { return tok && tok.tokenValue === val; } function next() { return me.next( 1 ); } if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) && isValue( next(), ',' ) && isNumOrPct( next() ) && isValue( next(), ',' ) && isNumOrPct( next() ) && ( val === 'rgb' || val === 'hsa' || ( isValue( next(), ',' ) && isNum( next() ) ) ) && isValue( next(), ')' ) ) { return newToken( Type.COLOR, this.css.substring( ch, this.ch ) ); } return failure(); } return newToken( Type.FUNCTION, val ); } // Other identifier return newToken( Type.IDENT, val ); } // Standalone character this.ch++; return newToken( Type.CHARACTER, firstChar ); }, /** * Determine whether there is another token * @return {boolean} */ hasNext: function() { var next = this.next(); this.prev(); return !!next; }, /** * Back up and return the previous token * @return {PIE.Tokenizer.Token} */ prev: function() { return this.tokens[ this.tokenIndex-- - 2 ]; }, /** * Retrieve all the tokens in the CSS string * @return {Array.<PIE.Tokenizer.Token>} */ all: function() { while( this.next() ) {} return this.tokens; }, /** * Return a list of tokens from the current position until the given function returns * true. The final token will not be included in the list. * @param {function():boolean} func - test function * @param {boolean} require - if true, then if the end of the CSS string is reached * before the test function returns true, null will be returned instead of the * tokens that have been found so far. * @return {Array.<PIE.Tokenizer.Token>} */ until: function( func, require ) { var list = [], t, hit; while( t = this.next() ) { if( func( t ) ) { hit = true; this.prev(); break; } list.push( t ); } return require && !hit ? null : list; } }; return Tokenizer; })();/** * Handles calculating, caching, and detecting changes to size and position of the element. * @constructor * @param {Element} el the target element */ PIE.BoundsInfo = function( el ) { this.targetElement = el; }; PIE.BoundsInfo.prototype = { _locked: 0, /** * Determines if the element's position has changed since the last update. * TODO this does a simple getBoundingClientRect comparison for detecting the * changes in position, which may not always be accurate; it's possible that * an element will actually move relative to its positioning parent, but its position * relative to the viewport will stay the same. Need to come up with a better way to * track movement. The most accurate would be the same logic used in RootRenderer.updatePos() * but that is a more expensive operation since it performs DOM walking, and we want this * check to be as fast as possible. Perhaps introduce a -pie-* flag to trigger the slower * but more accurate method? */ positionChanged: function() { var last = this._lastBounds, bounds; return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) ); }, sizeChanged: function() { var last = this._lastBounds, bounds; return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) ); }, getLiveBounds: function() { var el = this.targetElement, rect = el.getBoundingClientRect(), isIE9 = PIE.ieDocMode === 9, isIE7 = PIE.ieVersion === 7, width = rect.right - rect.left; return { x: rect.left, y: rect.top, // In some cases scrolling the page will cause IE9 to report incorrect dimensions // in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height // instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements // so we must calculate the ratio and use it in certain places as a position adjustment. w: isIE9 || isIE7 ? el.offsetWidth : width, h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top, logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1 }; }, getBounds: function() { return this._locked ? ( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) : this.getLiveBounds(); }, hasBeenQueried: function() { return !!this._lastBounds; }, lock: function() { ++this._locked; }, unlock: function() { if( !--this._locked ) { if( this._lockedBounds ) this._lastBounds = this._lockedBounds; this._lockedBounds = null; } } }; (function() { function cacheWhenLocked( fn ) { var uid = PIE.Util.getUID( fn ); return function() { if( this._locked ) { var cache = this._lockedValues || ( this._lockedValues = {} ); return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) ); } else { return fn.call( this ); } } } PIE.StyleInfoBase = { _locked: 0, /** * Create a new StyleInfo class, with the standard constructor, and augmented by * the StyleInfoBase's members. * @param proto */ newStyleInfo: function( proto ) { function StyleInfo( el ) { this.targetElement = el; this._lastCss = this.getCss(); } PIE.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto ); StyleInfo._propsCache = {}; return StyleInfo; }, /** * Get an object representation of the target CSS style, caching it for each unique * CSS value string. * @return {Object} */ getProps: function() { var css = this.getCss(), cache = this.constructor._propsCache; return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null; }, /** * Get the raw CSS value for the target style * @return {string} */ getCss: cacheWhenLocked( function() { var el = this.targetElement, ctor = this.constructor, s = el.style, cs = el.currentStyle, cssProp = this.cssProperty, styleProp = this.styleProperty, prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ), prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) ); return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp ); } ), /** * Determine whether the target CSS style is active. * @return {boolean} */ isActive: cacheWhenLocked( function() { return !!this.getProps(); } ), /** * Determine whether the target CSS style has changed since the last time it was used. * @return {boolean} */ changed: cacheWhenLocked( function() { var currentCss = this.getCss(), changed = currentCss !== this._lastCss; this._lastCss = currentCss; return changed; } ), cacheWhenLocked: cacheWhenLocked, lock: function() { ++this._locked; }, unlock: function() { if( !--this._locked ) { delete this._lockedValues; } } }; })();/** * Handles parsing, caching, and detecting changes to background (and -pie-background) CSS * @constructor * @param {Element} el the target element */ PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: PIE.CSS_PREFIX + 'background', styleProperty: PIE.STYLE_PREFIX + 'Background', attachIdents: { 'scroll':1, 'fixed':1, 'local':1 }, repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 }, originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 }, positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 }, sizeIdents: { 'contain':1, 'cover':1 }, tbIdents: { 'top': 1, 'bottom': 1 }, lrIdents: { 'left': 1, 'right': 1 }, propertyNames: { CLIP: 'backgroundClip', COLOR: 'backgroundColor', IMAGE: 'backgroundImage', ORIGIN: 'backgroundOrigin', POSITION: 'backgroundPosition', REPEAT: 'backgroundRepeat', SIZE: 'backgroundSize' }, /** * For background styles, we support the -pie-background property but fall back to the standard * backround* properties. The reason we have to use the prefixed version is that IE natively * parses the standard properties and if it sees something it doesn't know how to parse, for example * multiple values or gradient definitions, it will throw that away and not make it available through * currentStyle. * * Format of return object: * { * color: <PIE.Color>, * colorClip: <'border-box' | 'padding-box'>, * bgImages: [ * { * imgType: 'image', * imgUrl: 'image.png', * imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>, * bgPosition: <PIE.BgPosition>, * bgAttachment: <'scroll' | 'fixed' | 'local'>, * bgOrigin: <'border-box' | 'padding-box' | 'content-box'>, * bgClip: <'border-box' | 'padding-box'>, * bgSize: <PIE.BgSize>, * origString: 'url(img.png) no-repeat top left' * }, * { * imgType: 'linear-gradient', * gradientTo: [<'top' | 'bottom'>, <'left' | 'right'>?], * angle: <PIE.Angle>, * stops: [ * { color: <PIE.Color>, offset: <PIE.Length> }, * { color: <PIE.Color>, offset: <PIE.Length> }, ... * ] * } * ] * } * @param {String} css * @override */ parseCss: function( css ) { var el = this.targetElement, cs = el.currentStyle, tokenizer, token, image, tok_type = PIE.Tokenizer.Type, type_operator = tok_type.OPERATOR, type_ident = tok_type.IDENT, type_color = tok_type.COLOR, tokType, tokVal, beginCharIndex = 0, positionIdents = this.positionIdents, gradient, stop, width, height, gradientTo, len, tbIdents, lrIdents, props = { bgImages: [] }; function isBgPosToken( token ) { return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents ); } function sizeToken( token ) { return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) ); } // If the CSS3-specific -pie-background property is present, parse it if( this.getCss3() ) { tokenizer = new PIE.Tokenizer( css ); image = {}; while( token = tokenizer.next() ) { tokType = token.tokenType; tokVal = token.tokenValue; if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) { gradient = { stops: [], imgType: tokVal }; stop = {}; while( token = tokenizer.next() ) { tokType = token.tokenType; tokVal = token.tokenValue; // If we reached the end of the function and had at least 2 stops, flush the info if( tokType & tok_type.CHARACTER && tokVal === ')' ) { if( stop.color ) { gradient.stops.push( stop ); } if( gradient.stops.length > 1 ) { PIE.merge( image, gradient ); } break; } // Color stop - must start with color if( tokType & type_color ) { // if we already have an angle/position, make sure that the previous token was a comma if( gradient.angle || gradient.gradientTo ) { token = tokenizer.prev(); if( token.tokenType !== type_operator ) { break; //fail } tokenizer.next(); } stop = { color: PIE.getColor( tokVal ) }; // check for offset following color token = tokenizer.next(); if( token.isLengthOrPercent() ) { stop.offset = PIE.getLength( token.tokenValue ); } else { tokenizer.prev(); } } // Angle - can only appear in first spot else if( tokType & tok_type.ANGLE && !gradient.angle && !gradient.gradientTo && !stop.color && !gradient.stops.length ) { gradient.angle = new PIE.Angle( token.tokenValue ); } // "to <side-or-corner>" - can only appear in first spot else if( tokType & tok_type.IDENT && tokVal === 'to' && !gradient.gradientTo && !gradient.angle && !stop.color && !gradient.stops.length ) { tbIdents = this.tbIdents; lrIdents = this.lrIdents; gradientTo = tokenizer.until( function( t ) { return !(t && t.tokenType & tok_type.IDENT && ( t.tokenValue in tbIdents || t.tokenValue in lrIdents )); } ); len = gradientTo.length; gradientTo = [ gradientTo[0] && gradientTo[0].tokenValue, gradientTo[1] && gradientTo[1].tokenValue ]; // bail unless there are 1 or 2 values, or if the 2 values are from the same pair of sides if ( len < 1 || len > 2 || ( len > 1 && ( ( gradientTo[0] in tbIdents && gradientTo[1] in tbIdents ) || ( gradientTo[0] in lrIdents && gradientTo[1] in lrIdents ) ) ) ) { break; } gradient.gradientTo = gradientTo; } else if( tokType & type_operator && tokVal === ',' ) { if( stop.color ) { gradient.stops.push( stop ); stop = {}; } } else { // Found something we didn't recognize; fail without adding image break; } } } else if( !image.imgType && tokType & tok_type.URL ) { image.imgUrl = tokVal; image.imgType = 'image'; } else if( isBgPosToken( token ) && !image.bgPosition ) { tokenizer.prev(); image.bgPosition = new PIE.BgPosition( tokenizer.until( function( t ) { return !isBgPosToken( t ); }, false ) ); } else if( tokType & type_ident ) { if( tokVal in this.repeatIdents && !image.imgRepeat ) { image.imgRepeat = tokVal; } else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) { image.bgOrigin = tokVal; if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) && token.tokenValue in this.originAndClipIdents ) { image.bgClip = token.tokenValue; } else { image.bgClip = tokVal; tokenizer.prev(); } } else if( tokVal in this.attachIdents && !image.bgAttachment ) { image.bgAttachment = tokVal; } else { return null; } } else if( tokType & type_color && !props.color ) { props.color = PIE.getColor( tokVal ); } else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) { // background size token = tokenizer.next(); if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) { image.bgSize = new PIE.BgSize( token.tokenValue ); } else if( width = sizeToken( token ) ) { height = sizeToken( tokenizer.next() ); if ( !height ) { height = width; tokenizer.prev(); } image.bgSize = new PIE.BgSize( width, height ); } else { return null; } } // new layer else if( tokType & type_operator && tokVal === ',' && image.imgType ) { image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 ); beginCharIndex = tokenizer.ch; props.bgImages.push( image ); image = {}; } else { // Found something unrecognized; chuck everything return null; } } // leftovers if( image.imgType ) { image.origString = css.substring( beginCharIndex ); props.bgImages.push( image ); } props.colorClip = image.bgClip; } // Otherwise, use the standard background properties; let IE give us the values rather than parsing them else { this.withActualBg( PIE.ieDocMode < 9 ? function() { var propNames = this.propertyNames, posX = cs[propNames.POSITION + 'X'], posY = cs[propNames.POSITION + 'Y'], img = cs[propNames.IMAGE], color = cs[propNames.COLOR]; if( color !== 'transparent' ) { props.color = PIE.getColor( color ) } if( img !== 'none' ) { props.bgImages = [ { imgType: 'image', imgUrl: new PIE.Tokenizer( img ).next().tokenValue, imgRepeat: cs[propNames.REPEAT], bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() ) } ]; } } : function() { var propNames = this.propertyNames, splitter = /\s*,\s*/, images = cs[propNames.IMAGE].split( splitter ), color = cs[propNames.COLOR], repeats, positions, origins, clips, sizes, i, len, image, sizeParts; if( color !== 'transparent' ) { props.color = PIE.getColor( color ) } len = images.length; if( len && images[0] !== 'none' ) { repeats = cs[propNames.REPEAT].split( splitter ); positions = cs[propNames.POSITION].split( splitter ); origins = cs[propNames.ORIGIN].split( splitter ); clips = cs[propNames.CLIP].split( splitter ); sizes = cs[propNames.SIZE].split( splitter ); props.bgImages = []; for( i = 0; i < len; i++ ) { image = images[ i ]; if( image && image !== 'none' ) { sizeParts = sizes[i].split( ' ' ); props.bgImages.push( { origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' + origins[ i ] + ' ' + clips[ i ], imgType: 'image', imgUrl: new PIE.Tokenizer( image ).next().tokenValue, imgRepeat: repeats[ i ], bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ), bgOrigin: origins[ i ], bgClip: clips[ i ], bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] ) } ); } } } } ); } return ( props.color || props.bgImages[0] ) ? props : null; }, /** * Execute a function with the actual background styles (not overridden with runtimeStyle * properties set by the renderers) available via currentStyle. * @param fn */ withActualBg: function( fn ) { var isIE9 = PIE.ieDocMode > 8, propNames = this.propertyNames, rs = this.targetElement.runtimeStyle, rsImage = rs[propNames.IMAGE], rsColor = rs[propNames.COLOR], rsRepeat = rs[propNames.REPEAT], rsClip, rsOrigin, rsSize, rsPosition, ret; if( rsImage ) rs[propNames.IMAGE] = ''; if( rsColor ) rs[propNames.COLOR] = ''; if( rsRepeat ) rs[propNames.REPEAT] = ''; if( isIE9 ) { rsClip = rs[propNames.CLIP]; rsOrigin = rs[propNames.ORIGIN]; rsPosition = rs[propNames.POSITION]; rsSize = rs[propNames.SIZE]; if( rsClip ) rs[propNames.CLIP] = ''; if( rsOrigin ) rs[propNames.ORIGIN] = ''; if( rsPosition ) rs[propNames.POSITION] = ''; if( rsSize ) rs[propNames.SIZE] = ''; } ret = fn.call( this ); if( rsImage ) rs[propNames.IMAGE] = rsImage; if( rsColor ) rs[propNames.COLOR] = rsColor; if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat; if( isIE9 ) { if( rsClip ) rs[propNames.CLIP] = rsClip; if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin; if( rsPosition ) rs[propNames.POSITION] = rsPosition; if( rsSize ) rs[propNames.SIZE] = rsSize; } return ret; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { return this.getCss3() || this.withActualBg( function() { var cs = this.targetElement.currentStyle, propNames = this.propertyNames; return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' + cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y']; } ); } ), getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement; return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty ); } ), /** * For a given background-origin value, return the dimensions of the background area. * @param {String} bgOrigin * @param {PIE.BoundsInfo} boundsInfo * @param {PIE.BorderStyleInfo} borderInfo */ getBgAreaSize: function( bgOrigin, boundsInfo, borderInfo, paddingInfo ) { var el = this.targetElement, bounds = boundsInfo.getBounds(), w = bounds.w, h = bounds.h, borders, paddings; if( bgOrigin !== 'border-box' ) { borders = borderInfo.getProps(); if( borders && ( borders = borders.widths ) ) { w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el ); h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el ); } } if ( bgOrigin === 'content-box' ) { paddings = paddingInfo.getProps(); if ( paddings ) { w -= paddings[ 'l' ].pixels( el ) + paddings[ 'l' ].pixels( el ); h -= paddings[ 't' ].pixels( el ) + paddings[ 'b' ].pixels( el ); } } return { w: w, h: h }; }, /** * Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6. */ isPngFix: function() { var val = 0, el; if( PIE.ieVersion < 7 ) { el = this.targetElement; val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' ); } return val; }, /** * The isActive logic is slightly different, because getProps() always returns an object * even if it is just falling back to the native background properties. But we only want * to report is as being "active" if either the -pie-background override property is present * and parses successfully or '-pie-png-fix' is set to true in IE6. */ isActive: PIE.StyleInfoBase.cacheWhenLocked( function() { return (this.getCss3() || this.isPngFix()) && !!this.getProps(); } ) } );/** * Handles parsing, caching, and detecting changes to border CSS * @constructor * @param {Element} el the target element */ PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( { sides: [ 'Top', 'Right', 'Bottom', 'Left' ], namedWidths: { 'thin': '1px', 'medium': '3px', 'thick': '5px' }, parseCss: function( css ) { var w = {}, s = {}, c = {}, active = false, colorsSame = true, stylesSame = true, widthsSame = true; this.withActualBorder( function() { var el = this.targetElement, cs = el.currentStyle, i = 0, style, color, width, lastStyle, lastColor, lastWidth, side, ltr; for( ; i < 4; i++ ) { side = this.sides[ i ]; ltr = side.charAt(0).toLowerCase(); style = s[ ltr ] = cs[ 'border' + side + 'Style' ]; color = cs[ 'border' + side + 'Color' ]; width = cs[ 'border' + side + 'Width' ]; if( i > 0 ) { if( style !== lastStyle ) { stylesSame = false; } if( color !== lastColor ) { colorsSame = false; } if( width !== lastWidth ) { widthsSame = false; } } lastStyle = style; lastColor = color; lastWidth = width; c[ ltr ] = PIE.getColor( color ); width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) ); if( width.pixels( this.targetElement ) > 0 ) { active = true; } } } ); return active ? { widths: w, styles: s, colors: c, widthsSame: widthsSame, colorsSame: colorsSame, stylesSame: stylesSame } : null; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement, cs = el.currentStyle, css; // Don't redraw or hide borders for cells in border-collapse:collapse tables if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) { this.withActualBorder( function() { css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor; } ); } return css; } ), /** * Execute a function with the actual border styles (not overridden with runtimeStyle * properties set by the renderers) available via currentStyle. * @param fn */ withActualBorder: function( fn ) { var rs = this.targetElement.runtimeStyle, rsWidth = rs.borderWidth, rsColor = rs.borderColor, ret; if( rsWidth ) rs.borderWidth = ''; if( rsColor ) rs.borderColor = ''; ret = fn.call( this ); if( rsWidth ) rs.borderWidth = rsWidth; if( rsColor ) rs.borderColor = rsColor; return ret; } } ); /** * Handles parsing, caching, and detecting changes to border-image CSS * @constructor * @param {Element} el the target element */ PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'border-image', styleProperty: 'borderImage', repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 }, parseCss: function( css ) { var p = null, tokenizer, token, type, value, slices, widths, outsets, slashCount = 0, Type = PIE.Tokenizer.Type, IDENT = Type.IDENT, NUMBER = Type.NUMBER, PERCENT = Type.PERCENT; if( css ) { tokenizer = new PIE.Tokenizer( css ); p = {}; function isSlash( token ) { return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' ); } function isFillIdent( token ) { return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' ); } function collectSlicesEtc() { slices = tokenizer.until( function( tok ) { return !( tok.tokenType & ( NUMBER | PERCENT ) ); } ); if( isFillIdent( tokenizer.next() ) && !p.fill ) { p.fill = true; } else { tokenizer.prev(); } if( isSlash( tokenizer.next() ) ) { slashCount++; widths = tokenizer.until( function( token ) { return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' ); } ); if( isSlash( tokenizer.next() ) ) { slashCount++; outsets = tokenizer.until( function( token ) { return !token.isLength(); } ); } } else { tokenizer.prev(); } } while( token = tokenizer.next() ) { type = token.tokenType; value = token.tokenValue; // Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values if( type & ( NUMBER | PERCENT ) && !slices ) { tokenizer.prev(); collectSlicesEtc(); } else if( isFillIdent( token ) && !p.fill ) { p.fill = true; collectSlicesEtc(); } // Idents: one or values for 'repeat' else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) { p.repeat = { h: value }; if( token = tokenizer.next() ) { if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) { p.repeat.v = token.tokenValue; } else { tokenizer.prev(); } } } // URL of the image else if( ( type & Type.URL ) && !p.src ) { p.src = value; } // Found something unrecognized; exit. else { return null; } } // Validate what we collected if( !p.src || !slices || slices.length < 1 || slices.length > 4 || ( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) || ( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) { return null; } // Fill in missing values if( !p.repeat ) { p.repeat = { h: 'stretch' }; } if( !p.repeat.v ) { p.repeat.v = p.repeat.h; } function distributeSides( tokens, convertFn ) { return { 't': convertFn( tokens[0] ), 'r': convertFn( tokens[1] || tokens[0] ), 'b': convertFn( tokens[2] || tokens[0] ), 'l': convertFn( tokens[3] || tokens[1] || tokens[0] ) }; } p.slice = distributeSides( slices, function( tok ) { return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue ); } ); if( widths && widths[0] ) { p.widths = distributeSides( widths, function( tok ) { return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue; } ); } if( outsets && outsets[0] ) { p.outset = distributeSides( outsets, function( tok ) { return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue; } ); } } return p; } } );/** * Handles parsing, caching, and detecting changes to padding CSS * @constructor * @param {Element} el the target element */ PIE.PaddingStyleInfo = PIE.StyleInfoBase.newStyleInfo( { parseCss: function( css ) { var tokenizer = new PIE.Tokenizer( css ), arr = [], token; while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) { arr.push( PIE.getLength( token.tokenValue ) ); } return arr.length > 0 && arr.length < 5 ? { 't': arr[0], 'r': arr[1] || arr[0], 'b': arr[2] || arr[0], 'l': arr[3] || arr[1] || arr[0] } : null; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement, rs = el.runtimeStyle, rsPadding = rs.padding, padding; if( rsPadding ) rs.padding = ''; padding = el.currentStyle.padding; if( rsPadding ) rs.padding = rsPadding; return padding; } ) } ); PIE.RendererBase = { /** * Create a new Renderer class, with the standard constructor, and augmented by * the RendererBase's members. * @param proto */ newRenderer: function( proto ) { function Renderer( el, boundsInfo, styleInfos, parent ) { this.targetElement = el; this.boundsInfo = boundsInfo; this.styleInfos = styleInfos; this.parent = parent; } PIE.merge( Renderer.prototype, PIE.RendererBase, proto ); return Renderer; }, /** * Determine if the renderer needs to be updated * @return {boolean} */ needsUpdate: function() { return false; }, /** * Run any preparation logic that would affect the main update logic of this * renderer or any of the other renderers, e.g. things that might affect the * element's size or style properties. */ prepareUpdate: PIE.emptyFn, /** * Tell the renderer to update based on modified properties or element dimensions */ updateRendering: function() { if( this.isActive() ) { this.draw(); } else { this.destroy(); } }, /** * Hide the target element's border */ hideBorder: function() { this.targetElement.runtimeStyle.borderColor = 'transparent'; }, /** * Destroy the rendered objects. This is a base implementation which handles common renderer * structures, but individual renderers may override as necessary. */ destroy: function() { } }; /** * Root renderer for IE9; manages the rendering layers in the element's background * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.IE9RootRenderer = PIE.RendererBase.newRenderer( { outerCommasRE: /^,+|,+$/g, innerCommasRE: /,+/g, setBackgroundLayer: function(zIndex, bg) { var me = this, bgLayers = me._bgLayers || ( me._bgLayers = [] ), undef; bgLayers[zIndex] = bg || undef; }, updateRendering: function() { var me = this, bgLayers = me._bgLayers, bg; if( bgLayers && ( bg = bgLayers.join( ',' ).replace( me.outerCommasRE, '' ).replace( me.innerCommasRE, ',' ) ) !== me._lastBg ) { me._lastBg = me.targetElement.runtimeStyle.background = bg; } }, destroy: function() { this.targetElement.runtimeStyle.background = ''; delete this._bgLayers; } } ); /** * Renderer for element backgrounds, specific for IE9. Only handles translating CSS3 gradients * to an equivalent SVG data URI. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.IE9BackgroundRenderer = PIE.RendererBase.newRenderer( { drawingCanvas: doc.createElement( 'canvas' ), bgLayerZIndex: 1, needsUpdate: function() { var si = this.styleInfos; return si.backgroundInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.backgroundInfo.isActive() || si.borderImageInfo.isActive(); }, draw: function() { var me = this, styleInfos = me.styleInfos, bgInfo = styleInfos.backgroundInfo, props = bgInfo.getProps(), bg, images, i = 0, img, bgAreaSize, bgSize; if ( props ) { bg = []; images = props.bgImages; if ( images ) { while( img = images[ i++ ] ) { if (img.imgType === 'linear-gradient' ) { bgAreaSize = bgInfo.getBgAreaSize( bg.bgOrigin, me.boundsInfo, styleInfos.borderInfo, styleInfos.paddingInfo ); bgSize = ( img.bgSize || PIE.BgSize.DEFAULT ).pixels( me.targetElement, bgAreaSize.w, bgAreaSize.h, bgAreaSize.w, bgAreaSize.h ); bg.push( 'url(' + me.getGradientImgData( img, bgSize.w, bgSize.h ) + ') ' + me.bgPositionToString( img.bgPosition ) + ' / ' + bgSize.w + 'px ' + bgSize.h + 'px ' + ( img.bgAttachment || '' ) + ' ' + ( img.bgOrigin || '' ) + ' ' + ( img.bgClip || '' ) ); } else { bg.push( img.origString ); } } } if ( props.color ) { bg.push( props.color.val + ' ' + ( props.colorClip || '' ) ); } me.parent.setBackgroundLayer(me.bgLayerZIndex, bg.join(',')); } }, bgPositionToString: function( bgPosition ) { return bgPosition ? bgPosition.tokens.map(function(token) { return token.tokenValue; }).join(' ') : '0 0'; }, getGradientImgData: function( info, bgWidth, bgHeight ) { var me = this, el = me.targetElement, stopsInfo = info.stops, stopCount = stopsInfo.length, metrics = PIE.GradientUtil.getGradientMetrics( el, bgWidth, bgHeight, info ), lineLength = metrics.lineLength, canvas = me.drawingCanvas, context = canvas.getContext( '2d' ), gradient = context.createLinearGradient( metrics.startX, metrics.startY, metrics.endX, metrics.endY ), stopPx = [], i, j, before, after; // Find the pixel offsets along the CSS3 gradient-line for each stop. for( i = 0; i < stopCount; i++ ) { stopPx.push( stopsInfo[i].offset ? stopsInfo[i].offset.pixels( el, lineLength ) : i === 0 ? 0 : i === stopCount - 1 ? lineLength : null ); } // Fill in gaps with evenly-spaced offsets for( i = 1; i < stopCount; i++ ) { if( stopPx[ i ] === null ) { before = stopPx[ i - 1 ]; j = i; do { after = stopPx[ ++j ]; } while( after === null ); stopPx[ i ] = before + ( after - before ) / ( j - i + 1 ); } } // Convert stops to percentages along the gradient line and add a stop for each for( i = 0; i < stopCount; i++ ) { gradient.addColorStop( stopPx[ i ] / lineLength, stopsInfo[ i ].color.val ); } canvas.width = bgWidth; canvas.height = bgHeight; context.fillStyle = gradient; context.fillRect( 0, 0, bgWidth, bgHeight ); return canvas.toDataURL(); }, destroy: function() { this.parent.setBackgroundLayer( this.bgLayerZIndex ); } } ); /** * Renderer for border-image * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.IE9BorderImageRenderer = PIE.RendererBase.newRenderer( { REPEAT: 'repeat', STRETCH: 'stretch', ROUND: 'round', bgLayerZIndex: 0, needsUpdate: function() { return this.styleInfos.borderImageInfo.changed(); }, isActive: function() { return this.styleInfos.borderImageInfo.isActive(); }, draw: function() { var me = this, props = me.styleInfos.borderImageInfo.getProps(), borderProps = me.styleInfos.borderInfo.getProps(), bounds = me.boundsInfo.getBounds(), repeat = props.repeat, repeatH = repeat.h, repeatV = repeat.v, el = me.targetElement, isAsync = 0; PIE.Util.withImageSize( props.src, function( imgSize ) { var elW = bounds.w, elH = bounds.h, imgW = imgSize.w, imgH = imgSize.h, // The image cannot be referenced as a URL directly in the SVG because IE9 throws a strange // security exception (perhaps due to cross-origin policy within data URIs?) Therefore we // work around this by converting the image data into a data URI itself using a transient // canvas. This unfortunately requires the border-image src to be within the same domain, // which isn't a limitation in true border-image, so we need to try and find a better fix. imgSrc = me.imageToDataURI( props.src, imgW, imgH ), REPEAT = me.REPEAT, STRETCH = me.STRETCH, ROUND = me.ROUND, ceil = Math.ceil, zero = PIE.getLength( '0' ), widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ), widthT = widths['t'].pixels( el ), widthR = widths['r'].pixels( el ), widthB = widths['b'].pixels( el ), widthL = widths['l'].pixels( el ), slices = props.slice, sliceT = slices['t'].pixels( el ), sliceR = slices['r'].pixels( el ), sliceB = slices['b'].pixels( el ), sliceL = slices['l'].pixels( el ), centerW = elW - widthL - widthR, middleH = elH - widthT - widthB, imgCenterW = imgW - sliceL - sliceR, imgMiddleH = imgH - sliceT - sliceB, // Determine the size of each tile - 'round' is handled below tileSizeT = repeatH === STRETCH ? centerW : imgCenterW * widthT / sliceT, tileSizeR = repeatV === STRETCH ? middleH : imgMiddleH * widthR / sliceR, tileSizeB = repeatH === STRETCH ? centerW : imgCenterW * widthB / sliceB, tileSizeL = repeatV === STRETCH ? middleH : imgMiddleH * widthL / sliceL, svg, patterns = [], rects = [], i = 0; // For 'round', subtract from each tile's size enough so that they fill the space a whole number of times if (repeatH === ROUND) { tileSizeT -= (tileSizeT - (centerW % tileSizeT || tileSizeT)) / ceil(centerW / tileSizeT); tileSizeB -= (tileSizeB - (centerW % tileSizeB || tileSizeB)) / ceil(centerW / tileSizeB); } if (repeatV === ROUND) { tileSizeR -= (tileSizeR - (middleH % tileSizeR || tileSizeR)) / ceil(middleH / tileSizeR); tileSizeL -= (tileSizeL - (middleH % tileSizeL || tileSizeL)) / ceil(middleH / tileSizeL); } // Build the SVG for the border-image rendering. Add each piece as a pattern, which is then stretched // or repeated as the fill of a rect of appropriate size. svg = [ '<svg width="' + elW + '" height="' + elH + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' ]; function addImage( x, y, w, h, cropX, cropY, cropW, cropH, tileW, tileH ) { patterns.push( '<pattern patternUnits="userSpaceOnUse" id="pattern' + i + '" ' + 'x="' + (repeatH === REPEAT ? x + w / 2 - tileW / 2 : x) + '" ' + 'y="' + (repeatV === REPEAT ? y + h / 2 - tileH / 2 : y) + '" ' + 'width="' + tileW + '" height="' + tileH + '">' + '<svg width="' + tileW + '" height="' + tileH + '" viewBox="' + cropX + ' ' + cropY + ' ' + cropW + ' ' + cropH + '" preserveAspectRatio="none">' + '<image xlink:href="' + imgSrc + '" x="0" y="0" width="' + imgW + '" height="' + imgH + '" />' + '</svg>' + '</pattern>' ); rects.push( '<rect x="' + x + '" y="' + y + '" width="' + w + '" height="' + h + '" fill="url(#pattern' + i + ')" />' ); i++; } addImage( 0, 0, widthL, widthT, 0, 0, sliceL, sliceT, widthL, widthT ); // top left addImage( widthL, 0, centerW, widthT, sliceL, 0, imgCenterW, sliceT, tileSizeT, widthT ); // top center addImage( elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT, widthR, widthT ); // top right addImage( 0, widthT, widthL, middleH, 0, sliceT, sliceL, imgMiddleH, widthL, tileSizeL ); // middle left if ( props.fill ) { // center fill addImage( widthL, widthT, centerW, middleH, sliceL, sliceT, imgCenterW, imgMiddleH, tileSizeT || tileSizeB || imgCenterW, tileSizeL || tileSizeR || imgMiddleH ); } addImage( elW - widthR, widthT, widthR, middleH, imgW - sliceR, sliceT, sliceR, imgMiddleH, widthR, tileSizeR ); // middle right addImage( 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB, widthL, widthB ); // bottom left addImage( widthL, elH - widthB, centerW, widthB, sliceL, imgH - sliceB, imgCenterW, sliceB, tileSizeB, widthB ); // bottom center addImage( elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB, widthR, widthB ); // bottom right svg.push( '<defs>' + patterns.join('\n') + '</defs>' + rects.join('\n') + '</svg>' ); me.parent.setBackgroundLayer( me.bgLayerZIndex, 'url(data:image/svg+xml,' + escape( svg.join( '' ) ) + ') no-repeat border-box border-box' ); // If the border-image's src wasn't immediately available, the SVG for its background layer // will have been created asynchronously after the main element's update has finished; we'll // therefore need to force the root renderer to sync to the final background once finished. if( isAsync ) { me.parent.updateRendering(); } }, me ); isAsync = 1; }, /** * Convert a given image to a data URI */ imageToDataURI: (function() { var uris = {}; return function( src, width, height ) { var uri = uris[ src ], image, canvas; if ( !uri ) { image = new Image(); canvas = doc.createElement( 'canvas' ); image.src = src; canvas.width = width; canvas.height = height; canvas.getContext( '2d' ).drawImage( image, 0, 0 ); uri = uris[ src ] = canvas.toDataURL(); } return uri; } })(), prepareUpdate: function() { if (this.isActive()) { var me = this, el = me.targetElement, rs = el.runtimeStyle, widths = me.styleInfos.borderImageInfo.getProps().widths; // Force border-style to solid so it doesn't collapse rs.borderStyle = 'solid'; // If widths specified in border-image shorthand, override border-width if ( widths ) { rs.borderTopWidth = widths['t'].pixels( el ) + 'px'; rs.borderRightWidth = widths['r'].pixels( el ) + 'px'; rs.borderBottomWidth = widths['b'].pixels( el ) + 'px'; rs.borderLeftWidth = widths['l'].pixels( el ) + 'px'; } // Make the border transparent me.hideBorder(); } }, destroy: function() { var me = this, rs = me.targetElement.runtimeStyle; me.parent.setBackgroundLayer( me.bgLayerZIndex ); rs.borderColor = rs.borderStyle = rs.borderWidth = ''; } } ); PIE.Element = (function() { var wrappers = {}, lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init', pollCssProp = PIE.CSS_PREFIX + 'poll', trackActiveCssProp = PIE.CSS_PREFIX + 'track-active', trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover', hoverClass = PIE.CLASS_PREFIX + 'hover', activeClass = PIE.CLASS_PREFIX + 'active', focusClass = PIE.CLASS_PREFIX + 'focus', firstChildClass = PIE.CLASS_PREFIX + 'first-child', ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 }, classNameRegExes = {}, dummyArray = []; function addClass( el, className ) { el.className += ' ' + className; } function removeClass( el, className ) { var re = classNameRegExes[ className ] || ( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) ); el.className = el.className.replace( re, '' ); } function delayAddClass( el, className /*, className2*/ ) { var classes = dummyArray.slice.call( arguments, 1 ), i = classes.length; setTimeout( function() { if( el ) { while( i-- ) { addClass( el, classes[ i ] ); } } }, 0 ); } function delayRemoveClass( el, className /*, className2*/ ) { var classes = dummyArray.slice.call( arguments, 1 ), i = classes.length; setTimeout( function() { if( el ) { while( i-- ) { removeClass( el, classes[ i ] ); } } }, 0 ); } function Element( el ) { var me = this, childRenderers, rootRenderer, boundsInfo = new PIE.BoundsInfo( el ), styleInfos, styleInfosArr, initializing, initialized, eventsAttached, eventListeners = [], delayed, destroyed, poll; me.el = el; /** * Initialize PIE for this element. */ function init() { if( !initialized ) { var docEl, bounds, ieDocMode = PIE.ieDocMode, cs = el.currentStyle, lazy = cs.getAttribute( lazyInitCssProp ) === 'true', trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false', trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false'; // Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll poll = cs.getAttribute( pollCssProp ); poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true'; // Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes // after load, but make sure it only gets called the first time through to avoid recursive calls to init(). if( !initializing ) { initializing = 1; el.runtimeStyle.zoom = 1; initFirstChildPseudoClass(); } boundsInfo.lock(); // If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) && ( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) { if( !delayed ) { delayed = 1; PIE.OnScroll.observe( init ); } } else { initialized = 1; delayed = initializing = 0; PIE.OnScroll.unobserve( init ); // Create the style infos and renderers if ( ieDocMode === 9 ) { styleInfos = { backgroundInfo: new PIE.BackgroundStyleInfo( el ), borderImageInfo: new PIE.BorderImageStyleInfo( el ), borderInfo: new PIE.BorderStyleInfo( el ), paddingInfo: new PIE.PaddingStyleInfo( el ) }; styleInfosArr = [ styleInfos.backgroundInfo, styleInfos.borderInfo, styleInfos.borderImageInfo, styleInfos.paddingInfo ]; rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos ); childRenderers = [ new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer ) ]; } else { styleInfos = { backgroundInfo: new PIE.BackgroundStyleInfo( el ), borderInfo: new PIE.BorderStyleInfo( el ), borderImageInfo: new PIE.BorderImageStyleInfo( el ), borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ), boxShadowInfo: new PIE.BoxShadowStyleInfo( el ), paddingInfo: new PIE.PaddingStyleInfo( el ), visibilityInfo: new PIE.VisibilityStyleInfo( el ) }; styleInfosArr = [ styleInfos.backgroundInfo, styleInfos.borderInfo, styleInfos.borderImageInfo, styleInfos.borderRadiusInfo, styleInfos.boxShadowInfo, styleInfos.paddingInfo, styleInfos.visibilityInfo ]; rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos ); childRenderers = [ new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ), //new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer ) ]; if( el.tagName === 'IMG' ) { childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) ); } rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way? } // Add property change listeners to ancestors if requested initAncestorEventListeners(); // Add to list of polled elements when -pie-poll:true if( poll ) { PIE.Heartbeat.observe( update ); PIE.Heartbeat.run(); } // Trigger rendering update( 0, 1 ); } if( !eventsAttached ) { eventsAttached = 1; if( ieDocMode < 9 ) { addListener( el, 'onmove', handleMoveOrResize ); } addListener( el, 'onresize', handleMoveOrResize ); addListener( el, 'onpropertychange', propChanged ); if( trackHover ) { addListener( el, 'onmouseenter', mouseEntered ); } if( trackHover || trackActive ) { addListener( el, 'onmouseleave', mouseLeft ); } if( trackActive ) { addListener( el, 'onmousedown', mousePressed ); } if( el.tagName in PIE.focusableElements ) { addListener( el, 'onfocus', focused ); addListener( el, 'onblur', blurred ); } PIE.OnResize.observe( handleMoveOrResize ); PIE.OnUnload.observe( removeEventListeners ); } boundsInfo.unlock(); } } /** * Event handler for onmove and onresize events. Invokes update() only if the element's * bounds have previously been calculated, to prevent multiple runs during page load when * the element has no initial CSS3 properties. */ function handleMoveOrResize() { if( boundsInfo && boundsInfo.hasBeenQueried() ) { update(); } } /** * Update position and/or size as necessary. Both move and resize events call * this rather than the updatePos/Size functions because sometimes, particularly * during page load, one will fire but the other won't. */ function update( isPropChange, force ) { if( !destroyed ) { if( initialized ) { lockAll(); var i = 0, len = childRenderers.length, sizeChanged = boundsInfo.sizeChanged(); for( ; i < len; i++ ) { childRenderers[i].prepareUpdate(); } for( i = 0; i < len; i++ ) { if( force || sizeChanged || ( isPropChange && childRenderers[i].needsUpdate() ) ) { childRenderers[i].updateRendering(); } } if( force || sizeChanged || isPropChange || boundsInfo.positionChanged() ) { rootRenderer.updateRendering(); } unlockAll(); } else if( !initializing ) { init(); } } } /** * Handle property changes to trigger update when appropriate. */ function propChanged() { // Some elements like <table> fire onpropertychange events for old-school background properties // ('background', 'bgColor') when runtimeStyle background properties are changed, which // results in an infinite loop; therefore we filter out those property names. Also, 'display' // is ignored because size calculations don't work correctly immediately when its onpropertychange // event fires, and because it will trigger an onresize event anyway. if( initialized && !( event && event.propertyName in ignorePropertyNames ) ) { update( 1 ); } } /** * Handle mouseenter events. Adds a custom class to the element to allow IE6 to add * hover styles to non-link elements, and to trigger a propertychange update. */ function mouseEntered() { //must delay this because the mouseenter event fires before the :hover styles are added. delayAddClass( el, hoverClass ); } /** * Handle mouseleave events */ function mouseLeft() { //must delay this because the mouseleave event fires before the :hover styles are removed. delayRemoveClass( el, hoverClass, activeClass ); } /** * Handle mousedown events. Adds a custom class to the element to allow IE6 to add * active styles to non-link elements, and to trigger a propertychange update. */ function mousePressed() { //must delay this because the mousedown event fires before the :active styles are added. delayAddClass( el, activeClass ); // listen for mouseups on the document; can't just be on the element because the user might // have dragged out of the element while the mouse button was held down PIE.OnMouseup.observe( mouseReleased ); } /** * Handle mouseup events */ function mouseReleased() { //must delay this because the mouseup event fires before the :active styles are removed. delayRemoveClass( el, activeClass ); PIE.OnMouseup.unobserve( mouseReleased ); } /** * Handle focus events. Adds a custom class to the element to trigger a propertychange update. */ function focused() { //must delay this because the focus event fires before the :focus styles are added. delayAddClass( el, focusClass ); } /** * Handle blur events */ function blurred() { //must delay this because the blur event fires before the :focus styles are removed. delayRemoveClass( el, focusClass ); } /** * Handle property changes on ancestors of the element; see initAncestorEventListeners() * which adds these listeners as requested with the -pie-watch-ancestors CSS property. */ function ancestorPropChanged() { var name = event.propertyName; if( name === 'className' || name === 'id' || name.indexOf( 'style.' ) === 0 ) { propChanged(); } } function lockAll() { boundsInfo.lock(); for( var i = styleInfosArr.length; i--; ) { styleInfosArr[i].lock(); } } function unlockAll() { for( var i = styleInfosArr.length; i--; ) { styleInfosArr[i].unlock(); } boundsInfo.unlock(); } function addListener( targetEl, type, handler ) { targetEl.attachEvent( type, handler ); eventListeners.push( [ targetEl, type, handler ] ); } /** * Remove all event listeners from the element and any monitored ancestors. */ function removeEventListeners() { if (eventsAttached) { var i = eventListeners.length, listener; while( i-- ) { listener = eventListeners[ i ]; listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] ); } PIE.OnUnload.unobserve( removeEventListeners ); eventsAttached = 0; eventListeners = []; } } /** * Clean everything up when the behavior is removed from the element, or the element * is manually destroyed. */ function destroy() { if( !destroyed ) { var i, len; removeEventListeners(); destroyed = 1; // destroy any active renderers if( childRenderers ) { for( i = 0, len = childRenderers.length; i < len; i++ ) { childRenderers[i].finalized = 1; childRenderers[i].destroy(); } } rootRenderer.destroy(); // Remove from list of polled elements in IE8 if( poll ) { PIE.Heartbeat.unobserve( update ); } // Stop onresize listening PIE.OnResize.unobserve( update ); // Kill references childRenderers = rootRenderer = boundsInfo = styleInfos = styleInfosArr = el = null; me.el = me = 0; } } /** * If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and * other event listeners to ancestor(s) of the element so we can pick up style changes * based on CSS rules using descendant selectors. */ function initAncestorEventListeners() { var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ), i, a; if( watch ) { watch = parseInt( watch, 10 ); i = 0; a = el.parentNode; while( a && ( watch === 'NaN' || i++ < watch ) ) { addListener( a, 'onpropertychange', ancestorPropChanged ); addListener( a, 'onmouseenter', mouseEntered ); addListener( a, 'onmouseleave', mouseLeft ); addListener( a, 'onmousedown', mousePressed ); if( a.tagName in PIE.focusableElements ) { addListener( a, 'onfocus', focused ); addListener( a, 'onblur', blurred ); } a = a.parentNode; } } } /** * If the target element is a first child, add a pie_first-child class to it. This allows using * the added class as a workaround for the fact that PIE's rendering element breaks the :first-child * pseudo-class selector. */ function initFirstChildPseudoClass() { var tmpEl = el, isFirst = 1; while( tmpEl = tmpEl.previousSibling ) { if( tmpEl.nodeType === 1 ) { isFirst = 0; break; } } if( isFirst ) { addClass( el, firstChildClass ); } } // These methods are all already bound to this instance so there's no need to wrap them // in a closure to maintain the 'this' scope object when calling them. me.init = init; me.destroy = destroy; } Element.getInstance = function( el ) { var id = el[ 'uniqueID' ]; return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) ); }; Element.destroy = function( el ) { var id = el[ 'uniqueID' ], wrapper = wrappers[ id ]; if( wrapper ) { wrapper.destroy(); delete wrappers[ id ]; } }; Element.destroyAll = function() { var els = [], wrapper; if( wrappers ) { for( var w in wrappers ) { if( wrappers.hasOwnProperty( w ) ) { wrapper = wrappers[ w ]; els.push( wrapper.el ); wrapper.destroy(); } } wrappers = {}; } return els; }; return Element; })(); /* * This file exposes the public API for invoking PIE. */ /** * The version number of this PIE build. */ PIE[ 'version' ] = '2.0beta1'; /** * @property supportsVML * True if the current IE browser environment has a functioning VML engine. Should be true * in most IEs, but in rare cases may be false. If false, PIE will exit immediately when * attached to an element (for IE<9) to prevent errors; this property may also be used for * debugging or by external scripts to perform some special action when VML support is absent. * @type {boolean} */ PIE[ 'supportsVML' ] = PIE.supportsVML; /** * Programatically attach PIE to a single element. * @param {Element} el */ PIE[ 'attach' ] = function( el ) { if ( PIE.ieDocMode === 9 || ( PIE.ieDocMode < 9 && PIE.supportsVML ) ) { PIE.Element.getInstance( el ).init(); } }; /** * Programatically detach PIE from a single element. * @param {Element} el */ PIE[ 'detach' ] = function( el ) { PIE.Element.destroy( el ); }; })( window, document );
JavaScript
/* PIE: CSS3 rendering for IE Version 2.0beta1 http://css3pie.com Dual-licensed for use under the Apache License Version 2.0 or the General Public License (GPL) Version 2. */ (function( win, doc ) { var PIE = win[ 'PIE' ] || ( win[ 'PIE' ] = {} ); /** * Simple utility for merging objects * @param {Object} obj1 The main object into which all others will be merged * @param {...Object} var_args Other objects which will be merged into the first, in order */ PIE.merge = function( obj1 ) { var i, len, p, objN, args = arguments; for( i = 1, len = args.length; i < len; i++ ) { objN = args[i]; for( p in objN ) { if( objN.hasOwnProperty( p ) ) { obj1[ p ] = objN[ p ]; } } } return obj1; }; PIE.merge(PIE, { // Constants CSS_PREFIX: '-pie-', STYLE_PREFIX: 'Pie', CLASS_PREFIX: 'pie_', tableCellTags: { 'TD': 1, 'TH': 1 }, /** * Lookup table of elements which cannot take custom children. */ childlessElements: { 'TABLE':1, 'THEAD':1, 'TBODY':1, 'TFOOT':1, 'TR':1, 'INPUT':1, 'TEXTAREA':1, 'SELECT':1, 'OPTION':1, 'IMG':1, 'HR':1 }, /** * Elements that can receive user focus */ focusableElements: { 'A':1, 'INPUT':1, 'TEXTAREA':1, 'SELECT':1, 'BUTTON':1 }, /** * Values of the type attribute for input elements displayed as buttons */ inputButtonTypes: { 'submit':1, 'button':1, 'reset':1 }, emptyFn: function() {} }); // Force the background cache to be used. No reason it shouldn't be. try { doc.execCommand( 'BackgroundImageCache', false, true ); } catch(e) {} (function() { /* * IE version detection approach by James Padolsey, with modifications -- from * http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/ */ var ieVersion = 4, div = doc.createElement('div'), all = div.getElementsByTagName('i'), shape; while ( div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->', all[0] ) {} PIE.ieVersion = ieVersion; // Detect IE6 if( ieVersion === 6 ) { // IE6 can't access properties with leading dash, but can without it. PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' ); } PIE.ieDocMode = doc.documentMode || PIE.ieVersion; // Detect VML support (a small number of IE installs don't have a working VML engine) div.innerHTML = '<v:shape adj="1"/>'; shape = div.firstChild; shape.style['behavior'] = 'url(#default#VML)'; PIE.supportsVML = (typeof shape['adj'] === "object"); })(); /** * Utility functions */ (function() { var idNum = 0, imageSizes = {}; PIE.Util = { /** * Generate and return a unique ID for a given object. The generated ID is stored * as a property of the object for future reuse. For DOM Elements, don't use this * but use the IE-native uniqueID property instead. * @param {Object} obj */ getUID: function( obj ) { return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + idNum++ ); }, /** * Execute a callback function, passing it the dimensions of a given image once * they are known. * @param {string} src The source URL of the image * @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known * @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function */ withImageSize: function( src, func, ctx ) { var size = imageSizes[ src ], img, queue; if( size ) { // If we have a queue, add to it if( Object.prototype.toString.call( size ) === '[object Array]' ) { size.push( [ func, ctx ] ); } // Already have the size cached, call func right away else { func.call( ctx, size ); } } else { queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue img = new Image(); img.onload = function() { size = imageSizes[ src ] = { w: img.width, h: img.height }; for( var i = 0, len = queue.length; i < len; i++ ) { queue[ i ][ 0 ].call( queue[ i ][ 1 ], size ); } img.onload = null; }; img.src = src; } } }; })();/** * Utility functions for handling gradients */ PIE.GradientUtil = { toSideAngles: { 'top': 0, 'right': 90, 'bottom': 180, 'left': 270 }, getGradientMetrics: function( el, width, height, gradientInfo ) { var angle = gradientInfo.angle, toPos = gradientInfo.gradientTo, dX, dY, endPoint, startX, startY, endX, endY; // If an angle was specified, just use it if (angle) { angle = angle.degrees(); } // If a to-position was specified, find the appropriate angle for it else if (toPos) { // To a corner; find the adjacent corners and use the angle perpendicular to them if (toPos[1]) { dX = ( toPos[0] == 'top' || toPos[1] == 'top' ) ? width : -width; dY = ( toPos[0] == 'left' || toPos[1] == 'left' ) ? -height : height; angle = Math.atan2(dY, dX) * 180 / Math.PI; } // To a side; map to a vertical/horizontal angle else { angle = this.toSideAngles[toPos[0]]; } } // Neither specified; default is top to bottom else { angle = 180; } // Normalize the angle to a value between [0, 360) while( angle < 0 ) { angle += 360; } angle = angle % 360; // Find the end point of the gradient line, extending the angle from the center point // to where it intersects the perpendicular line passing through the nearest corner. endPoint = PIE.GradientUtil.perpendicularIntersect(width / 2, height / 2, angle, ( angle >= 180 ? 0 : width ), ( angle < 90 || angle > 270 ? 0 : height ) ); endX = endPoint[0]; endY = endPoint[1]; startX = width - endX; startY = height - endY; return { angle: angle, endX: endX, endY: endY, startX: startX, startY: startY, lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY ) }; }, /** * Find the point along a given line (defined by a starting point and an angle), at which * that line is intersected by a perpendicular line extending through another point. * @param x1 - x coord of the starting point * @param y1 - y coord of the starting point * @param angle - angle of the line extending from the starting point (in degrees) * @param x2 - x coord of point along the perpendicular line * @param y2 - y coord of point along the perpendicular line * @return [ x, y ] */ perpendicularIntersect: function( x1, y1, angle, x2, y2 ) { // Handle straight vertical and horizontal angles, for performance and to avoid // divide-by-zero errors. if( angle === 0 || angle === 180 ) { return [ x1, y2 ]; } else if( angle === 90 || angle === 270 ) { return [ x2, y1 ]; } else { // General approach: determine the Ax+By=C formula for each line (the slope of the second // line is the negative inverse of the first) and then solve for where both formulas have // the same x/y values. var a1 = Math.tan( ( angle - 90 ) * Math.PI / 180 ), c1 = a1 * x1 - y1, a2 = -1 / a1, c2 = a2 * x2 - y2, d = a2 - a1, endX = ( c2 - c1 ) / d, endY = ( a1 * c2 - a2 * c1 ) / d; return [ endX, endY ]; } }, /** * Find the distance between two points * @param {Number} p1x * @param {Number} p1y * @param {Number} p2x * @param {Number} p2y * @return {Number} the distance */ distance: function( p1x, p1y, p2x, p2y ) { var dx = p2x - p1x, dy = p2y - p1y; return Math.abs( dx === 0 ? dy : dy === 0 ? dx : Math.sqrt( dx * dx + dy * dy ) ); } };/** * */ PIE.Observable = function() { /** * List of registered observer functions */ this.observers = []; /** * Hash of function ids to their position in the observers list, for fast lookup */ this.indexes = {}; }; PIE.Observable.prototype = { observe: function( fn ) { var id = PIE.Util.getUID( fn ), indexes = this.indexes, observers = this.observers; if( !( id in indexes ) ) { indexes[ id ] = observers.length; observers.push( fn ); } }, unobserve: function( fn ) { var id = PIE.Util.getUID( fn ), indexes = this.indexes; if( id && id in indexes ) { delete this.observers[ indexes[ id ] ]; delete indexes[ id ]; } }, fire: function() { var o = this.observers, i = o.length; while( i-- ) { o[ i ] && o[ i ](); } } };/* * Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not * always firing the onmove and onresize events when elements are moved or resized. We check a few * times every second to make sure the elements have the correct position and size. See Element.js * which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9 * and false elsewhere. */ PIE.Heartbeat = new PIE.Observable(); PIE.Heartbeat.run = function() { var me = this, interval; if( !me.running ) { interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250; (function beat() { me.fire(); setTimeout(beat, interval); })(); me.running = 1; } }; /** * Create an observable listener for the onunload event */ (function() { PIE.OnUnload = new PIE.Observable(); function handleUnload() { PIE.OnUnload.fire(); win.detachEvent( 'onunload', handleUnload ); win[ 'PIE' ] = null; } win.attachEvent( 'onunload', handleUnload ); /** * Attach an event which automatically gets detached onunload */ PIE.OnUnload.attachManagedEvent = function( target, name, handler ) { target.attachEvent( name, handler ); this.observe( function() { target.detachEvent( name, handler ); } ); }; })()/** * Create a single observable listener for window resize events. */ PIE.OnResize = new PIE.Observable(); PIE.OnUnload.attachManagedEvent( win, 'onresize', function() { PIE.OnResize.fire(); } ); /** * Create a single observable listener for scroll events. Used for lazy loading based * on the viewport, and for fixed position backgrounds. */ (function() { PIE.OnScroll = new PIE.Observable(); function scrolled() { PIE.OnScroll.fire(); } PIE.OnUnload.attachManagedEvent( win, 'onscroll', scrolled ); PIE.OnResize.observe( scrolled ); })(); /** * Listen for printing events, destroy all active PIE instances when printing, and * restore them afterward. */ (function() { var elements; function beforePrint() { elements = PIE.Element.destroyAll(); } function afterPrint() { if( elements ) { for( var i = 0, len = elements.length; i < len; i++ ) { PIE[ 'attach' ]( elements[i] ); } elements = 0; } } PIE.OnUnload.attachManagedEvent( win, 'onbeforeprint', beforePrint ); PIE.OnUnload.attachManagedEvent( win, 'onafterprint', afterPrint ); })();/** * Create a single observable listener for document mouseup events. */ PIE.OnMouseup = new PIE.Observable(); PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } ); /** * Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique * value is returned from PIE.getLength() - always use that instead of instantiating directly. * @constructor * @param {string} val The CSS string representing the length. It is assumed that this will already have * been validated as a valid length or percentage syntax. */ PIE.Length = (function() { var lengthCalcEl = doc.createElement( 'length-calc' ), parent = doc.body || doc.documentElement, s = lengthCalcEl.style, conversions = {}, units = [ 'mm', 'cm', 'in', 'pt', 'pc' ], i = units.length, instances = {}; s.position = 'absolute'; s.top = s.left = '-9999px'; parent.appendChild( lengthCalcEl ); while( i-- ) { s.width = '100' + units[i]; conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100; } parent.removeChild( lengthCalcEl ); // All calcs from here on will use 1em s.width = '1em'; function Length( val ) { this.val = val; } Length.prototype = { /** * Regular expression for matching the length unit * @private */ unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/, /** * Get the numeric value of the length * @return {number} The value */ getNumber: function() { var num = this.num, UNDEF; if( num === UNDEF ) { num = this.num = parseFloat( this.val ); } return num; }, /** * Get the unit of the length * @return {string} The unit */ getUnit: function() { var unit = this.unit, m; if( !unit ) { m = this.val.match( this.unitRE ); unit = this.unit = ( m && m[0] ) || 'px'; } return unit; }, /** * Determine whether this is a percentage length value * @return {boolean} */ isPercentage: function() { return this.getUnit() === '%'; }, /** * Resolve this length into a number of pixels. * @param {Element} el - the context element, used to resolve font-relative values * @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a * function which will be called to return the number. */ pixels: function( el, pct100 ) { var num = this.getNumber(), unit = this.getUnit(); switch( unit ) { case "px": return num; case "%": return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100; case "em": return num * this.getEmPixels( el ); case "ex": return num * this.getEmPixels( el ) / 2; default: return num * conversions[ unit ]; } }, /** * The em and ex units are relative to the font-size of the current element, * however if the font-size is set using non-pixel units then we get that value * rather than a pixel conversion. To get around this, we keep a floating element * with width:1em which we insert into the target element and then read its offsetWidth. * For elements that won't accept a child we insert into the parent node and perform * additional calculation. If the font-size *is* specified in pixels, then we use that * directly to avoid the expensive DOM manipulation. * @param {Element} el * @return {number} */ getEmPixels: function( el ) { var fs = el.currentStyle.fontSize, px, parent, me; if( fs.indexOf( 'px' ) > 0 ) { return parseFloat( fs ); } else if( el.tagName in PIE.childlessElements ) { me = this; parent = el.parentNode; return PIE.getLength( fs ).pixels( parent, function() { return me.getEmPixels( parent ); } ); } else { el.appendChild( lengthCalcEl ); px = lengthCalcEl.offsetWidth; if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is el.removeChild( lengthCalcEl ); } return px; } } }; /** * Convert a pixel length into a point length */ Length.pxToPt = function( px ) { return px / conversions[ 'pt' ]; }; /** * Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value. * @param {string} val The CSS string representing the length. It is assumed that this will already have * been validated as a valid length or percentage syntax. */ PIE.getLength = function( val ) { return instances[ val ] || ( instances[ val ] = new Length( val ) ); }; return Length; })(); /** * Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages. * @constructor * @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value. */ PIE.BgPosition = (function() { var length_fifty = PIE.getLength( '50%' ), vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 }, horiz_idents = { 'left': 1, 'center': 1, 'right': 1 }; function BgPosition( tokens ) { this.tokens = tokens; } BgPosition.prototype = { /** * Normalize the values into the form: * [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ] * where: xOffsetSide is either 'left' or 'right', * yOffsetSide is either 'top' or 'bottom', * and x/yOffsetLength are both PIE.Length objects. * @return {Array} */ getValues: function() { if( !this._values ) { var tokens = this.tokens, len = tokens.length, Tokenizer = PIE.Tokenizer, identType = Tokenizer.Type, length_zero = PIE.getLength( '0' ), type_ident = identType.IDENT, type_length = identType.LENGTH, type_percent = identType.PERCENT, type, value, vals = [ 'left', length_zero, 'top', length_zero ]; // If only one value, the second is assumed to be 'center' if( len === 1 ) { tokens.push( new Tokenizer.Token( type_ident, 'center' ) ); len++; } // Two values - CSS2 if( len === 2 ) { // If both idents, they can appear in either order, so switch them if needed if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) && tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) { tokens.push( tokens.shift() ); } if( tokens[0].tokenType & type_ident ) { if( tokens[0].tokenValue === 'center' ) { vals[1] = length_fifty; } else { vals[0] = tokens[0].tokenValue; } } else if( tokens[0].isLengthOrPercent() ) { vals[1] = PIE.getLength( tokens[0].tokenValue ); } if( tokens[1].tokenType & type_ident ) { if( tokens[1].tokenValue === 'center' ) { vals[3] = length_fifty; } else { vals[2] = tokens[1].tokenValue; } } else if( tokens[1].isLengthOrPercent() ) { vals[3] = PIE.getLength( tokens[1].tokenValue ); } } // Three or four values - CSS3 else { // TODO } this._values = vals; } return this._values; }, /** * Find the coordinates of the background image from the upper-left corner of the background area. * Note that these coordinate values are not rounded. * @param {Element} el * @param {number} width - the width for percentages (background area width minus image width) * @param {number} height - the height for percentages (background area height minus image height) * @return {Object} { x: Number, y: Number } */ coords: function( el, width, height ) { var vals = this.getValues(), pxX = vals[1].pixels( el, width ), pxY = vals[3].pixels( el, height ); return { x: vals[0] === 'right' ? width - pxX : pxX, y: vals[2] === 'bottom' ? height - pxY : pxY }; } }; return BgPosition; })(); /** * Wrapper for a CSS3 background-size value. * @constructor * @param {String|PIE.Length} w The width parameter * @param {String|PIE.Length} h The height parameter, if any */ PIE.BgSize = (function() { var CONTAIN = 'contain', COVER = 'cover', AUTO = 'auto'; function BgSize( w, h ) { this.w = w; this.h = h; } BgSize.prototype = { pixels: function( el, areaW, areaH, imgW, imgH ) { var me = this, w = me.w, h = me.h, areaRatio = areaW / areaH, imgRatio = imgW / imgH; if ( w === CONTAIN ) { w = imgRatio > areaRatio ? areaW : areaH * imgRatio; h = imgRatio > areaRatio ? areaW / imgRatio : areaH; } else if ( w === COVER ) { w = imgRatio < areaRatio ? areaW : areaH * imgRatio; h = imgRatio < areaRatio ? areaW / imgRatio : areaH; } else if ( w === AUTO ) { h = ( h === AUTO ? imgH : h.pixels( el, areaH ) ); w = h * imgRatio; } else { w = w.pixels( el, areaW ); h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) ); } return { w: w, h: h }; } }; BgSize.DEFAULT = new BgSize( AUTO, AUTO ); return BgSize; })(); /** * Wrapper for angle values; handles conversion to degrees from all allowed angle units * @constructor * @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated. */ PIE.Angle = (function() { function Angle( val ) { this.val = val; } Angle.prototype = { unitRE: /[a-z]+$/i, /** * @return {string} The unit of the angle value */ getUnit: function() { return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() ); }, /** * Get the numeric value of the angle in degrees. * @return {number} The degrees value */ degrees: function() { var deg = this._deg, u, n; if( deg === undefined ) { u = this.getUnit(); n = parseFloat( this.val, 10 ); deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 ); } return deg; } }; return Angle; })();/** * Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique * value is returned from PIE.getColor() - always use that instead of instantiating directly. * @constructor * @param {string} val The raw CSS string value for the color */ PIE.Color = (function() { /* * hsl2rgb from http://codingforums.com/showthread.php?t=11156 * code by Jason Karl Davis (http://www.jasonkarldavis.com) * swiped from cssSandpaper by Zoltan Hawryluk (http://www.useragentman.com/blog/csssandpaper-a-css3-javascript-library/) * modified for formatting and size optimizations */ function hsl2rgb( h, s, l ) { var m1, m2, r, g, b, round = Math.round; s /= 100; l /= 100; if ( !s ) { r = g = b = l * 255; } else { if ( l <= 0.5 ) { m2 = l * ( s + 1 ); } else { m2 = l + s - l * s; } m1 = l * 2 - m2; h = ( h % 360 ) / 360; r = hueToRgb( m1, m2, h + 1/3 ); g = hueToRgb( m1, m2, h ); b = hueToRgb( m1, m2, h - 1/3 ); } return { r: round( r ), g: round( g ), b: round( b ) }; } function hueToRgb( m1, m2, hue ) { var v; if ( hue < 0 ) { hue += 1; } else if ( hue > 1 ) { hue -= 1; } if ( 6 * hue < 1 ) { v = m1 + ( m2 - m1 ) * hue * 6; } else if ( 2 * hue < 1 ) { v = m2; } else if ( 3 * hue < 2 ) { v = m1 + ( m2 - m1 ) * ( 2/3 - hue ) * 6; } else { v = m1; } return 255 * v; } var instances = {}; function Color( val ) { this.val = val; } /** * Regular expression for matching rgba colors and extracting their components * @type {RegExp} */ Color.rgbOrRgbaRE = /\s*rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(\d+|\d*\.\d+))?\s*\)\s*/; Color.hslOrHslaRE = /\s*hsla?\(\s*(\d*\.?\d+)\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*(,\s*(\d+|\d*\.\d+))?\s*\)\s*/; /** * Hash of color keyword names to their corresponding hex values. Encoded for * small size and expanded into a hash on startup. */ Color.names = {}; var names = 'black|0|navy|3k|darkblue|b|mediumblue|1u|blue|1e|darkgreen|jk1|green|5j4|teal|3k|darkcyan|26j|deepskyblue|ad0|darkturquoise|2xe|mediumspringgreen|8nd|lime|va|springgreen|3j|aqua|3k|cyan|0|midnightblue|xunl|dodgerblue|7ogf|lightseagreen|2zsb|forestgreen|2lbs|seagreen|guut|darkslategray|12pk|limegreen|4wkj|mediumseagreen|dwlb|turquoise|5v8f|royalblue|r2p|steelblue|75qr|darkslateblue|2fh3|mediumturquoise|ta9|indigo|32d2|darkolivegreen|emr1|cadetblue|ebu9|cornflowerblue|6z4d|mediumaquamarine|3459|dimgray|3nwf|slateblue|1bok|olivedrab|1opi|slategray|6y5p|lightslategray|9vk9|mediumslateblue|5g0l|lawngreen|27ma|chartreuse|48ao|aquamarine|5w|maroon|18|purple|3k|olive|p6o|gray|3k|lightslateblue|5j7j|skyblue|4q98|lightskyblue|f|blueviolet|3bhk|darkred|15we|darkmagenta|3v|saddlebrown|djc|darkseagreen|69vg|lightgreen|1og1|mediumpurple|3ivc|darkviolet|sfv|palegreen|6zt1|darkorchid|awk|yellowgreen|292e|sienna|7r3v|brown|6sxp|darkgray|6bgf|lightblue|5vlp|greenyellow|7k9|paleturquoise|2pxb|lightsteelblue|169c|powderblue|5jc|firebrick|1rgc|darkgoldenrod|8z55|mediumorchid|2jm0|rosybrown|34jg|darkkhaki|1mfw|silver|49jp|mediumvioletred|8w5h|indianred|8tef|peru|82r|violetred|3ntd|feldspar|212d|chocolate|16eh|tan|ewe|lightgrey|1kqv|palevioletred|6h8g|metle|fnp|orchid|2dj2|goldenrod|abu|crimson|20ik|gainsboro|13mo|plum|12pt|burlywood|1j8q|lightcyan|3794|lavender|8agr|darksalmon|3rsw|violet|6wz8|palegoldenrod|k3g|lightcoral|28k6|khaki|k5o|aliceblue|3n7|honeydew|1dd|azure|f|sandybrown|5469|wheat|1q37|beige|4kp|whitesmoke|p|mintcream|1z9|ghostwhite|46bp|salmon|25bn|antiquewhite|l7p|linen|zz|lightgoldenrodyellow|1yk|oldlace|46qc|red|1gka|magenta|73|fuchsia|0|deeppink|3v8|orangered|9kd|tomato|5zb|hotpink|19p|coral|49o|darkorange|2i8|lightsalmon|41m|orange|w6|lightpink|3i9|pink|1ze|gold|4dx|peachpuff|qh|navajowhite|s4|moccasin|16w|bisque|f|mistyrose|t|blanchedalmond|1d8|papayawhip|so|lavenderblush|80|seashell|zd|cornsilk|ku|lemonchiffon|dt|floralwhite|z|snow|a|yellow|sm|lightyellow|68|ivory|g|white|f'.split('|'), i = 0, len = names.length, color = 0, hexColor; for(; i < len; i += 2) { color += parseInt(names[i + 1], 36); hexColor = color.toString(16); Color.names[names[i]] = '#000000'.slice(0, -hexColor.length) + hexColor; } Color.prototype = { /** * @private */ parse: function() { if( !this._color ) { var me = this, color = me.val, alpha, vLower, m, rgb; // RGB or RGBA colors if( m = color.match( Color.rgbOrRgbaRE ) ) { color = me.rgbToHex( +m[1], +m[2], +m[3] ); alpha = m[5] ? +m[5] : 1; } // HSL or HSLA colors else if( m = color.match( Color.hslOrHslaRE ) ) { rgb = hsl2rgb( m[1], m[2], m[3] ); color = me.rgbToHex( rgb.r, rgb.g, rgb.b ); alpha = m[5] ? +m[5] : 1; } else { if( Color.names.hasOwnProperty( vLower = color.toLowerCase() ) ) { color = Color.names[vLower]; } alpha = ( color === 'transparent' ? 0 : 1 ); } me._color = color; me._alpha = alpha; } }, /** * Converts RGB color channels to a hex value string */ rgbToHex: function( r, g, b ) { return '#' + ( r < 16 ? '0' : '' ) + r.toString( 16 ) + ( g < 16 ? '0' : '' ) + g.toString( 16 ) + ( b < 16 ? '0' : '' ) + b.toString( 16 ); }, /** * Retrieve the value of the color in a format usable by IE natively. This will be the same as * the raw input value, except for rgb(a) and hsl(a) values which will be converted to a hex value. * @param {Element} el The context element, used to get 'currentColor' keyword value. * @return {string} Color value */ colorValue: function( el ) { this.parse(); return this._color === 'currentColor' ? PIE.getColor( el.currentStyle.color ).colorValue( el ) : this._color; }, /** * Retrieve the value of the color in a normalized six-digit hex format. * @param el */ hexValue: function( el ) { var color = this.colorValue( el ); // At this point the color should be either a 3- or 6-digit hex value, or the string "transparent". function ch( i ) { return color.charAt( i ); } // Fudge transparent to black - should be ignored anyway since its alpha will be 0 if( color === 'transparent' ) { color = '#000'; } // Expand 3-digit to 6-digit hex if( ch(0) === '#' && color.length === 4 ) { color = '#' + ch(1) + ch(1) + ch(2) + ch(2) + ch(3) + ch(3); } return color; }, /** * Retrieve the alpha value of the color. Will be 1 for all values except for rgba values * with an alpha component. * @return {number} The alpha value, from 0 to 1. */ alpha: function() { this.parse(); return this._alpha; } }; /** * Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value. * @param {string} val The CSS string representing the color. It is assumed that this will already have * been validated as a valid color syntax. */ PIE.getColor = function(val) { return instances[ val ] || ( instances[ val ] = new Color( val ) ); }; return Color; })();/** * A tokenizer for CSS value strings. * @constructor * @param {string} css The CSS value string */ PIE.Tokenizer = (function() { function Tokenizer( css ) { this.css = css; this.ch = 0; this.tokens = []; this.tokenIndex = 0; } /** * Enumeration of token type constants. * @enum {number} */ var Type = Tokenizer.Type = { ANGLE: 1, CHARACTER: 2, COLOR: 4, DIMEN: 8, FUNCTION: 16, IDENT: 32, LENGTH: 64, NUMBER: 128, OPERATOR: 256, PERCENT: 512, STRING: 1024, URL: 2048 }; /** * A single token * @constructor * @param {number} type The type of the token - see PIE.Tokenizer.Type * @param {string} value The value of the token */ Tokenizer.Token = function( type, value ) { this.tokenType = type; this.tokenValue = value; }; Tokenizer.Token.prototype = { isLength: function() { return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' ); }, isLengthOrPercent: function() { return this.isLength() || this.tokenType & Type.PERCENT; } }; Tokenizer.prototype = { whitespace: /\s/, number: /^[\+\-]?(\d*\.)?\d+/, url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i, ident: /^\-?[_a-z][\w-]*/i, string: /^("([^"]*)"|'([^']*)')/, operator: /^[\/,]/, hash: /^#[\w]+/, hashColor: /^#([\da-f]{6}|[\da-f]{3})/i, unitTypes: { 'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH, 'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH, 'pt': Type.LENGTH, 'pc': Type.LENGTH, 'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE }, colorFunctions: { 'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1 }, /** * Advance to and return the next token in the CSS string. If the end of the CSS string has * been reached, null will be returned. * @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev(). * @return {PIE.Tokenizer.Token} */ next: function( forget ) { var css, ch, firstChar, match, val, me = this; function newToken( type, value ) { var tok = new Tokenizer.Token( type, value ); if( !forget ) { me.tokens.push( tok ); me.tokenIndex++; } return tok; } function failure() { me.tokenIndex++; return null; } // In case we previously backed up, return the stored token in the next slot if( this.tokenIndex < this.tokens.length ) { return this.tokens[ this.tokenIndex++ ]; } // Move past leading whitespace characters while( this.whitespace.test( this.css.charAt( this.ch ) ) ) { this.ch++; } if( this.ch >= this.css.length ) { return failure(); } ch = this.ch; css = this.css.substring( this.ch ); firstChar = css.charAt( 0 ); switch( firstChar ) { case '#': if( match = css.match( this.hashColor ) ) { this.ch += match[0].length; return newToken( Type.COLOR, match[0] ); } break; case '"': case "'": if( match = css.match( this.string ) ) { this.ch += match[0].length; return newToken( Type.STRING, match[2] || match[3] || '' ); } break; case "/": case ",": this.ch++; return newToken( Type.OPERATOR, firstChar ); case 'u': if( match = css.match( this.url ) ) { this.ch += match[0].length; return newToken( Type.URL, match[2] || match[3] || match[4] || '' ); } } // Numbers and values starting with numbers if( match = css.match( this.number ) ) { val = match[0]; this.ch += val.length; // Check if it is followed by a unit if( css.charAt( val.length ) === '%' ) { this.ch++; return newToken( Type.PERCENT, val + '%' ); } if( match = css.substring( val.length ).match( this.ident ) ) { val += match[0]; this.ch += match[0].length; return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val ); } // Plain ol' number return newToken( Type.NUMBER, val ); } // Identifiers if( match = css.match( this.ident ) ) { val = match[0]; this.ch += val.length; // Named colors if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) { return newToken( Type.COLOR, val ); } // Functions if( css.charAt( val.length ) === '(' ) { this.ch++; // Color values in function format: rgb, rgba, hsl, hsla if( val.toLowerCase() in this.colorFunctions ) { function isNum( tok ) { return tok && tok.tokenType & Type.NUMBER; } function isNumOrPct( tok ) { return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) ); } function isValue( tok, val ) { return tok && tok.tokenValue === val; } function next() { return me.next( 1 ); } if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) && isValue( next(), ',' ) && isNumOrPct( next() ) && isValue( next(), ',' ) && isNumOrPct( next() ) && ( val === 'rgb' || val === 'hsa' || ( isValue( next(), ',' ) && isNum( next() ) ) ) && isValue( next(), ')' ) ) { return newToken( Type.COLOR, this.css.substring( ch, this.ch ) ); } return failure(); } return newToken( Type.FUNCTION, val ); } // Other identifier return newToken( Type.IDENT, val ); } // Standalone character this.ch++; return newToken( Type.CHARACTER, firstChar ); }, /** * Determine whether there is another token * @return {boolean} */ hasNext: function() { var next = this.next(); this.prev(); return !!next; }, /** * Back up and return the previous token * @return {PIE.Tokenizer.Token} */ prev: function() { return this.tokens[ this.tokenIndex-- - 2 ]; }, /** * Retrieve all the tokens in the CSS string * @return {Array.<PIE.Tokenizer.Token>} */ all: function() { while( this.next() ) {} return this.tokens; }, /** * Return a list of tokens from the current position until the given function returns * true. The final token will not be included in the list. * @param {function():boolean} func - test function * @param {boolean} require - if true, then if the end of the CSS string is reached * before the test function returns true, null will be returned instead of the * tokens that have been found so far. * @return {Array.<PIE.Tokenizer.Token>} */ until: function( func, require ) { var list = [], t, hit; while( t = this.next() ) { if( func( t ) ) { hit = true; this.prev(); break; } list.push( t ); } return require && !hit ? null : list; } }; return Tokenizer; })();/** * Handles calculating, caching, and detecting changes to size and position of the element. * @constructor * @param {Element} el the target element */ PIE.BoundsInfo = function( el ) { this.targetElement = el; }; PIE.BoundsInfo.prototype = { _locked: 0, /** * Determines if the element's position has changed since the last update. * TODO this does a simple getBoundingClientRect comparison for detecting the * changes in position, which may not always be accurate; it's possible that * an element will actually move relative to its positioning parent, but its position * relative to the viewport will stay the same. Need to come up with a better way to * track movement. The most accurate would be the same logic used in RootRenderer.updatePos() * but that is a more expensive operation since it performs DOM walking, and we want this * check to be as fast as possible. Perhaps introduce a -pie-* flag to trigger the slower * but more accurate method? */ positionChanged: function() { var last = this._lastBounds, bounds; return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) ); }, sizeChanged: function() { var last = this._lastBounds, bounds; return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) ); }, getLiveBounds: function() { var el = this.targetElement, rect = el.getBoundingClientRect(), isIE9 = PIE.ieDocMode === 9, isIE7 = PIE.ieVersion === 7, width = rect.right - rect.left; return { x: rect.left, y: rect.top, // In some cases scrolling the page will cause IE9 to report incorrect dimensions // in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height // instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements // so we must calculate the ratio and use it in certain places as a position adjustment. w: isIE9 || isIE7 ? el.offsetWidth : width, h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top, logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1 }; }, getBounds: function() { return this._locked ? ( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) : this.getLiveBounds(); }, hasBeenQueried: function() { return !!this._lastBounds; }, lock: function() { ++this._locked; }, unlock: function() { if( !--this._locked ) { if( this._lockedBounds ) this._lastBounds = this._lockedBounds; this._lockedBounds = null; } } }; (function() { function cacheWhenLocked( fn ) { var uid = PIE.Util.getUID( fn ); return function() { if( this._locked ) { var cache = this._lockedValues || ( this._lockedValues = {} ); return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) ); } else { return fn.call( this ); } } } PIE.StyleInfoBase = { _locked: 0, /** * Create a new StyleInfo class, with the standard constructor, and augmented by * the StyleInfoBase's members. * @param proto */ newStyleInfo: function( proto ) { function StyleInfo( el ) { this.targetElement = el; this._lastCss = this.getCss(); } PIE.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto ); StyleInfo._propsCache = {}; return StyleInfo; }, /** * Get an object representation of the target CSS style, caching it for each unique * CSS value string. * @return {Object} */ getProps: function() { var css = this.getCss(), cache = this.constructor._propsCache; return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null; }, /** * Get the raw CSS value for the target style * @return {string} */ getCss: cacheWhenLocked( function() { var el = this.targetElement, ctor = this.constructor, s = el.style, cs = el.currentStyle, cssProp = this.cssProperty, styleProp = this.styleProperty, prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ), prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) ); return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp ); } ), /** * Determine whether the target CSS style is active. * @return {boolean} */ isActive: cacheWhenLocked( function() { return !!this.getProps(); } ), /** * Determine whether the target CSS style has changed since the last time it was used. * @return {boolean} */ changed: cacheWhenLocked( function() { var currentCss = this.getCss(), changed = currentCss !== this._lastCss; this._lastCss = currentCss; return changed; } ), cacheWhenLocked: cacheWhenLocked, lock: function() { ++this._locked; }, unlock: function() { if( !--this._locked ) { delete this._lockedValues; } } }; })();/** * Handles parsing, caching, and detecting changes to background (and -pie-background) CSS * @constructor * @param {Element} el the target element */ PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: PIE.CSS_PREFIX + 'background', styleProperty: PIE.STYLE_PREFIX + 'Background', attachIdents: { 'scroll':1, 'fixed':1, 'local':1 }, repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 }, originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 }, positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 }, sizeIdents: { 'contain':1, 'cover':1 }, tbIdents: { 'top': 1, 'bottom': 1 }, lrIdents: { 'left': 1, 'right': 1 }, propertyNames: { CLIP: 'backgroundClip', COLOR: 'backgroundColor', IMAGE: 'backgroundImage', ORIGIN: 'backgroundOrigin', POSITION: 'backgroundPosition', REPEAT: 'backgroundRepeat', SIZE: 'backgroundSize' }, /** * For background styles, we support the -pie-background property but fall back to the standard * backround* properties. The reason we have to use the prefixed version is that IE natively * parses the standard properties and if it sees something it doesn't know how to parse, for example * multiple values or gradient definitions, it will throw that away and not make it available through * currentStyle. * * Format of return object: * { * color: <PIE.Color>, * colorClip: <'border-box' | 'padding-box'>, * bgImages: [ * { * imgType: 'image', * imgUrl: 'image.png', * imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>, * bgPosition: <PIE.BgPosition>, * bgAttachment: <'scroll' | 'fixed' | 'local'>, * bgOrigin: <'border-box' | 'padding-box' | 'content-box'>, * bgClip: <'border-box' | 'padding-box'>, * bgSize: <PIE.BgSize>, * origString: 'url(img.png) no-repeat top left' * }, * { * imgType: 'linear-gradient', * gradientTo: [<'top' | 'bottom'>, <'left' | 'right'>?], * angle: <PIE.Angle>, * stops: [ * { color: <PIE.Color>, offset: <PIE.Length> }, * { color: <PIE.Color>, offset: <PIE.Length> }, ... * ] * } * ] * } * @param {String} css * @override */ parseCss: function( css ) { var el = this.targetElement, cs = el.currentStyle, tokenizer, token, image, tok_type = PIE.Tokenizer.Type, type_operator = tok_type.OPERATOR, type_ident = tok_type.IDENT, type_color = tok_type.COLOR, tokType, tokVal, beginCharIndex = 0, positionIdents = this.positionIdents, gradient, stop, width, height, gradientTo, len, tbIdents, lrIdents, props = { bgImages: [] }; function isBgPosToken( token ) { return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents ); } function sizeToken( token ) { return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) ); } // If the CSS3-specific -pie-background property is present, parse it if( this.getCss3() ) { tokenizer = new PIE.Tokenizer( css ); image = {}; while( token = tokenizer.next() ) { tokType = token.tokenType; tokVal = token.tokenValue; if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) { gradient = { stops: [], imgType: tokVal }; stop = {}; while( token = tokenizer.next() ) { tokType = token.tokenType; tokVal = token.tokenValue; // If we reached the end of the function and had at least 2 stops, flush the info if( tokType & tok_type.CHARACTER && tokVal === ')' ) { if( stop.color ) { gradient.stops.push( stop ); } if( gradient.stops.length > 1 ) { PIE.merge( image, gradient ); } break; } // Color stop - must start with color if( tokType & type_color ) { // if we already have an angle/position, make sure that the previous token was a comma if( gradient.angle || gradient.gradientTo ) { token = tokenizer.prev(); if( token.tokenType !== type_operator ) { break; //fail } tokenizer.next(); } stop = { color: PIE.getColor( tokVal ) }; // check for offset following color token = tokenizer.next(); if( token.isLengthOrPercent() ) { stop.offset = PIE.getLength( token.tokenValue ); } else { tokenizer.prev(); } } // Angle - can only appear in first spot else if( tokType & tok_type.ANGLE && !gradient.angle && !gradient.gradientTo && !stop.color && !gradient.stops.length ) { gradient.angle = new PIE.Angle( token.tokenValue ); } // "to <side-or-corner>" - can only appear in first spot else if( tokType & tok_type.IDENT && tokVal === 'to' && !gradient.gradientTo && !gradient.angle && !stop.color && !gradient.stops.length ) { tbIdents = this.tbIdents; lrIdents = this.lrIdents; gradientTo = tokenizer.until( function( t ) { return !(t && t.tokenType & tok_type.IDENT && ( t.tokenValue in tbIdents || t.tokenValue in lrIdents )); } ); len = gradientTo.length; gradientTo = [ gradientTo[0] && gradientTo[0].tokenValue, gradientTo[1] && gradientTo[1].tokenValue ]; // bail unless there are 1 or 2 values, or if the 2 values are from the same pair of sides if ( len < 1 || len > 2 || ( len > 1 && ( ( gradientTo[0] in tbIdents && gradientTo[1] in tbIdents ) || ( gradientTo[0] in lrIdents && gradientTo[1] in lrIdents ) ) ) ) { break; } gradient.gradientTo = gradientTo; } else if( tokType & type_operator && tokVal === ',' ) { if( stop.color ) { gradient.stops.push( stop ); stop = {}; } } else { // Found something we didn't recognize; fail without adding image break; } } } else if( !image.imgType && tokType & tok_type.URL ) { image.imgUrl = tokVal; image.imgType = 'image'; } else if( isBgPosToken( token ) && !image.bgPosition ) { tokenizer.prev(); image.bgPosition = new PIE.BgPosition( tokenizer.until( function( t ) { return !isBgPosToken( t ); }, false ) ); } else if( tokType & type_ident ) { if( tokVal in this.repeatIdents && !image.imgRepeat ) { image.imgRepeat = tokVal; } else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) { image.bgOrigin = tokVal; if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) && token.tokenValue in this.originAndClipIdents ) { image.bgClip = token.tokenValue; } else { image.bgClip = tokVal; tokenizer.prev(); } } else if( tokVal in this.attachIdents && !image.bgAttachment ) { image.bgAttachment = tokVal; } else { return null; } } else if( tokType & type_color && !props.color ) { props.color = PIE.getColor( tokVal ); } else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) { // background size token = tokenizer.next(); if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) { image.bgSize = new PIE.BgSize( token.tokenValue ); } else if( width = sizeToken( token ) ) { height = sizeToken( tokenizer.next() ); if ( !height ) { height = width; tokenizer.prev(); } image.bgSize = new PIE.BgSize( width, height ); } else { return null; } } // new layer else if( tokType & type_operator && tokVal === ',' && image.imgType ) { image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 ); beginCharIndex = tokenizer.ch; props.bgImages.push( image ); image = {}; } else { // Found something unrecognized; chuck everything return null; } } // leftovers if( image.imgType ) { image.origString = css.substring( beginCharIndex ); props.bgImages.push( image ); } props.colorClip = image.bgClip; } // Otherwise, use the standard background properties; let IE give us the values rather than parsing them else { this.withActualBg( PIE.ieDocMode < 9 ? function() { var propNames = this.propertyNames, posX = cs[propNames.POSITION + 'X'], posY = cs[propNames.POSITION + 'Y'], img = cs[propNames.IMAGE], color = cs[propNames.COLOR]; if( color !== 'transparent' ) { props.color = PIE.getColor( color ) } if( img !== 'none' ) { props.bgImages = [ { imgType: 'image', imgUrl: new PIE.Tokenizer( img ).next().tokenValue, imgRepeat: cs[propNames.REPEAT], bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() ) } ]; } } : function() { var propNames = this.propertyNames, splitter = /\s*,\s*/, images = cs[propNames.IMAGE].split( splitter ), color = cs[propNames.COLOR], repeats, positions, origins, clips, sizes, i, len, image, sizeParts; if( color !== 'transparent' ) { props.color = PIE.getColor( color ) } len = images.length; if( len && images[0] !== 'none' ) { repeats = cs[propNames.REPEAT].split( splitter ); positions = cs[propNames.POSITION].split( splitter ); origins = cs[propNames.ORIGIN].split( splitter ); clips = cs[propNames.CLIP].split( splitter ); sizes = cs[propNames.SIZE].split( splitter ); props.bgImages = []; for( i = 0; i < len; i++ ) { image = images[ i ]; if( image && image !== 'none' ) { sizeParts = sizes[i].split( ' ' ); props.bgImages.push( { origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' + origins[ i ] + ' ' + clips[ i ], imgType: 'image', imgUrl: new PIE.Tokenizer( image ).next().tokenValue, imgRepeat: repeats[ i ], bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ), bgOrigin: origins[ i ], bgClip: clips[ i ], bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] ) } ); } } } } ); } return ( props.color || props.bgImages[0] ) ? props : null; }, /** * Execute a function with the actual background styles (not overridden with runtimeStyle * properties set by the renderers) available via currentStyle. * @param fn */ withActualBg: function( fn ) { var isIE9 = PIE.ieDocMode > 8, propNames = this.propertyNames, rs = this.targetElement.runtimeStyle, rsImage = rs[propNames.IMAGE], rsColor = rs[propNames.COLOR], rsRepeat = rs[propNames.REPEAT], rsClip, rsOrigin, rsSize, rsPosition, ret; if( rsImage ) rs[propNames.IMAGE] = ''; if( rsColor ) rs[propNames.COLOR] = ''; if( rsRepeat ) rs[propNames.REPEAT] = ''; if( isIE9 ) { rsClip = rs[propNames.CLIP]; rsOrigin = rs[propNames.ORIGIN]; rsPosition = rs[propNames.POSITION]; rsSize = rs[propNames.SIZE]; if( rsClip ) rs[propNames.CLIP] = ''; if( rsOrigin ) rs[propNames.ORIGIN] = ''; if( rsPosition ) rs[propNames.POSITION] = ''; if( rsSize ) rs[propNames.SIZE] = ''; } ret = fn.call( this ); if( rsImage ) rs[propNames.IMAGE] = rsImage; if( rsColor ) rs[propNames.COLOR] = rsColor; if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat; if( isIE9 ) { if( rsClip ) rs[propNames.CLIP] = rsClip; if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin; if( rsPosition ) rs[propNames.POSITION] = rsPosition; if( rsSize ) rs[propNames.SIZE] = rsSize; } return ret; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { return this.getCss3() || this.withActualBg( function() { var cs = this.targetElement.currentStyle, propNames = this.propertyNames; return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' + cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y']; } ); } ), getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement; return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty ); } ), /** * For a given background-origin value, return the dimensions of the background area. * @param {String} bgOrigin * @param {PIE.BoundsInfo} boundsInfo * @param {PIE.BorderStyleInfo} borderInfo */ getBgAreaSize: function( bgOrigin, boundsInfo, borderInfo, paddingInfo ) { var el = this.targetElement, bounds = boundsInfo.getBounds(), w = bounds.w, h = bounds.h, borders, paddings; if( bgOrigin !== 'border-box' ) { borders = borderInfo.getProps(); if( borders && ( borders = borders.widths ) ) { w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el ); h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el ); } } if ( bgOrigin === 'content-box' ) { paddings = paddingInfo.getProps(); if ( paddings ) { w -= paddings[ 'l' ].pixels( el ) + paddings[ 'l' ].pixels( el ); h -= paddings[ 't' ].pixels( el ) + paddings[ 'b' ].pixels( el ); } } return { w: w, h: h }; }, /** * Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6. */ isPngFix: function() { var val = 0, el; if( PIE.ieVersion < 7 ) { el = this.targetElement; val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' ); } return val; }, /** * The isActive logic is slightly different, because getProps() always returns an object * even if it is just falling back to the native background properties. But we only want * to report is as being "active" if either the -pie-background override property is present * and parses successfully or '-pie-png-fix' is set to true in IE6. */ isActive: PIE.StyleInfoBase.cacheWhenLocked( function() { return (this.getCss3() || this.isPngFix()) && !!this.getProps(); } ) } );/** * Handles parsing, caching, and detecting changes to border CSS * @constructor * @param {Element} el the target element */ PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( { sides: [ 'Top', 'Right', 'Bottom', 'Left' ], namedWidths: { 'thin': '1px', 'medium': '3px', 'thick': '5px' }, parseCss: function( css ) { var w = {}, s = {}, c = {}, active = false, colorsSame = true, stylesSame = true, widthsSame = true; this.withActualBorder( function() { var el = this.targetElement, cs = el.currentStyle, i = 0, style, color, width, lastStyle, lastColor, lastWidth, side, ltr; for( ; i < 4; i++ ) { side = this.sides[ i ]; ltr = side.charAt(0).toLowerCase(); style = s[ ltr ] = cs[ 'border' + side + 'Style' ]; color = cs[ 'border' + side + 'Color' ]; width = cs[ 'border' + side + 'Width' ]; if( i > 0 ) { if( style !== lastStyle ) { stylesSame = false; } if( color !== lastColor ) { colorsSame = false; } if( width !== lastWidth ) { widthsSame = false; } } lastStyle = style; lastColor = color; lastWidth = width; c[ ltr ] = PIE.getColor( color ); width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) ); if( width.pixels( this.targetElement ) > 0 ) { active = true; } } } ); return active ? { widths: w, styles: s, colors: c, widthsSame: widthsSame, colorsSame: colorsSame, stylesSame: stylesSame } : null; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement, cs = el.currentStyle, css; // Don't redraw or hide borders for cells in border-collapse:collapse tables if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) { this.withActualBorder( function() { css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor; } ); } return css; } ), /** * Execute a function with the actual border styles (not overridden with runtimeStyle * properties set by the renderers) available via currentStyle. * @param fn */ withActualBorder: function( fn ) { var rs = this.targetElement.runtimeStyle, rsWidth = rs.borderWidth, rsColor = rs.borderColor, ret; if( rsWidth ) rs.borderWidth = ''; if( rsColor ) rs.borderColor = ''; ret = fn.call( this ); if( rsWidth ) rs.borderWidth = rsWidth; if( rsColor ) rs.borderColor = rsColor; return ret; } } ); /** * Handles parsing, caching, and detecting changes to border-radius CSS * @constructor * @param {Element} el the target element */ (function() { PIE.BorderRadiusStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'border-radius', styleProperty: 'borderRadius', parseCss: function( css ) { var p = null, x, y, tokenizer, token, length, hasNonZero = false; if( css ) { tokenizer = new PIE.Tokenizer( css ); function collectLengths() { var arr = [], num; while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) { length = PIE.getLength( token.tokenValue ); num = length.getNumber(); if( num < 0 ) { return null; } if( num > 0 ) { hasNonZero = true; } arr.push( length ); } return arr.length > 0 && arr.length < 5 ? { 'tl': arr[0], 'tr': arr[1] || arr[0], 'br': arr[2] || arr[0], 'bl': arr[3] || arr[1] || arr[0] } : null; } // Grab the initial sequence of lengths if( x = collectLengths() ) { // See if there is a slash followed by more lengths, for the y-axis radii if( token ) { if( token.tokenType & PIE.Tokenizer.Type.OPERATOR && token.tokenValue === '/' ) { y = collectLengths(); } } else { y = x; } // Treat all-zero values the same as no value if( hasNonZero && x && y ) { p = { x: x, y : y }; } } } return p; } } ); var zero = PIE.getLength( '0' ), zeros = { 'tl': zero, 'tr': zero, 'br': zero, 'bl': zero }; PIE.BorderRadiusStyleInfo.ALL_ZERO = { x: zeros, y: zeros }; })();/** * Handles parsing, caching, and detecting changes to border-image CSS * @constructor * @param {Element} el the target element */ PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'border-image', styleProperty: 'borderImage', repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 }, parseCss: function( css ) { var p = null, tokenizer, token, type, value, slices, widths, outsets, slashCount = 0, Type = PIE.Tokenizer.Type, IDENT = Type.IDENT, NUMBER = Type.NUMBER, PERCENT = Type.PERCENT; if( css ) { tokenizer = new PIE.Tokenizer( css ); p = {}; function isSlash( token ) { return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' ); } function isFillIdent( token ) { return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' ); } function collectSlicesEtc() { slices = tokenizer.until( function( tok ) { return !( tok.tokenType & ( NUMBER | PERCENT ) ); } ); if( isFillIdent( tokenizer.next() ) && !p.fill ) { p.fill = true; } else { tokenizer.prev(); } if( isSlash( tokenizer.next() ) ) { slashCount++; widths = tokenizer.until( function( token ) { return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' ); } ); if( isSlash( tokenizer.next() ) ) { slashCount++; outsets = tokenizer.until( function( token ) { return !token.isLength(); } ); } } else { tokenizer.prev(); } } while( token = tokenizer.next() ) { type = token.tokenType; value = token.tokenValue; // Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values if( type & ( NUMBER | PERCENT ) && !slices ) { tokenizer.prev(); collectSlicesEtc(); } else if( isFillIdent( token ) && !p.fill ) { p.fill = true; collectSlicesEtc(); } // Idents: one or values for 'repeat' else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) { p.repeat = { h: value }; if( token = tokenizer.next() ) { if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) { p.repeat.v = token.tokenValue; } else { tokenizer.prev(); } } } // URL of the image else if( ( type & Type.URL ) && !p.src ) { p.src = value; } // Found something unrecognized; exit. else { return null; } } // Validate what we collected if( !p.src || !slices || slices.length < 1 || slices.length > 4 || ( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) || ( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) { return null; } // Fill in missing values if( !p.repeat ) { p.repeat = { h: 'stretch' }; } if( !p.repeat.v ) { p.repeat.v = p.repeat.h; } function distributeSides( tokens, convertFn ) { return { 't': convertFn( tokens[0] ), 'r': convertFn( tokens[1] || tokens[0] ), 'b': convertFn( tokens[2] || tokens[0] ), 'l': convertFn( tokens[3] || tokens[1] || tokens[0] ) }; } p.slice = distributeSides( slices, function( tok ) { return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue ); } ); if( widths && widths[0] ) { p.widths = distributeSides( widths, function( tok ) { return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue; } ); } if( outsets && outsets[0] ) { p.outset = distributeSides( outsets, function( tok ) { return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue; } ); } } return p; } } );/** * Handles parsing, caching, and detecting changes to box-shadow CSS * @constructor * @param {Element} el the target element */ PIE.BoxShadowStyleInfo = PIE.StyleInfoBase.newStyleInfo( { cssProperty: 'box-shadow', styleProperty: 'boxShadow', parseCss: function( css ) { var props, getLength = PIE.getLength, Type = PIE.Tokenizer.Type, tokenizer; if( css ) { tokenizer = new PIE.Tokenizer( css ); props = { outset: [], inset: [] }; function parseItem() { var token, type, value, color, lengths, inset, len; while( token = tokenizer.next() ) { value = token.tokenValue; type = token.tokenType; if( type & Type.OPERATOR && value === ',' ) { break; } else if( token.isLength() && !lengths ) { tokenizer.prev(); lengths = tokenizer.until( function( token ) { return !token.isLength(); } ); } else if( type & Type.COLOR && !color ) { color = value; } else if( type & Type.IDENT && value === 'inset' && !inset ) { inset = true; } else { //encountered an unrecognized token; fail. return false; } } len = lengths && lengths.length; if( len > 1 && len < 5 ) { ( inset ? props.inset : props.outset ).push( { xOffset: getLength( lengths[0].tokenValue ), yOffset: getLength( lengths[1].tokenValue ), blur: getLength( lengths[2] ? lengths[2].tokenValue : '0' ), spread: getLength( lengths[3] ? lengths[3].tokenValue : '0' ), color: PIE.getColor( color || 'currentColor' ) } ); return true; } return false; } while( parseItem() ) {} } return props && ( props.inset.length || props.outset.length ) ? props : null; } } ); /** * Handles parsing, caching, and detecting changes to padding CSS * @constructor * @param {Element} el the target element */ PIE.PaddingStyleInfo = PIE.StyleInfoBase.newStyleInfo( { parseCss: function( css ) { var tokenizer = new PIE.Tokenizer( css ), arr = [], token; while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) { arr.push( PIE.getLength( token.tokenValue ) ); } return arr.length > 0 && arr.length < 5 ? { 't': arr[0], 'r': arr[1] || arr[0], 'b': arr[2] || arr[0], 'l': arr[3] || arr[1] || arr[0] } : null; }, getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement, rs = el.runtimeStyle, rsPadding = rs.padding, padding; if( rsPadding ) rs.padding = ''; padding = el.currentStyle.padding; if( rsPadding ) rs.padding = rsPadding; return padding; } ) } ); /** * Retrieves the state of the element's visibility and display * @constructor * @param {Element} el the target element */ PIE.VisibilityStyleInfo = PIE.StyleInfoBase.newStyleInfo( { getCss: PIE.StyleInfoBase.cacheWhenLocked( function() { var el = this.targetElement, rs = el.runtimeStyle, cs = el.currentStyle, rsVis = rs.visibility, ret; rs.visibility = ''; ret = cs.visibility + '|' + cs.display; rs.visibility = rsVis; return ret; } ), parseCss: function() { var info = this.getCss().split('|'); return { visible: info[0] !== 'hidden', displayed: info[1] !== 'none' }; }, /** * Always return false for isActive, since this property alone will not trigger * a renderer to do anything. */ isActive: function() { return false; } } ); /** * Abstraction for a VML shape element. Allows assembling a VML shape's properties in * a non-DOM structure, which can then both generate itself as a single HTML string, and/or * update itself incrementally if its DOM element already exists. */ PIE.VmlShape = (function() { var nsPrefix = 'pievml', attrsPrefix = '_attrs_', objectSetters = { 'colors': function( fill, name, value ) { if( fill[ name ] ) { //sometimes the colors object isn't initialized so we have to assign it directly (?) fill[ name ].value = value; } else { fill[ name ] = value; } }, 'size': function( fill, name, value ) { if ( !value ) { delete fill[ name ]; } else { fill[ name ][ 'x' ] = 1; //Can be any value, just has to be set to "prime" it so the next line works. Weird! fill[ name ] = value; } }, 'o:opacity2': function( fill, name, value ) { // The VML DOM does not allow dynamic setting of o:opacity2, so we must regenerate // the entire shape from markup instead. var me = this; if( value !== me.lastOpacity2 ) { me.getShape().insertAdjacentHTML( 'afterEnd', me.getMarkup() ); me.destroy(); me.lastOpacity2 = value; } } }; function createSetter( objName ) { return function() { var args = arguments, i, len = args.length, obj, name, setter; // Store the property locally obj = this[ attrsPrefix + objName ] || ( this[ attrsPrefix + objName ] = {} ); for( i = 0; i < len; i += 2 ) { obj[ args[ i ] ] = args[ i + 1 ]; } // If there is a rendered VML shape already, set the property directly via the VML DOM obj = this.getShape(); if( obj ) { if( objName ) { obj = obj[ objName ]; } for( i = 0; i < len; i += 2 ) { name = args[ i ]; setter = objectSetters[ name ]; //if there is a custom setter for this property, use it if ( setter ) { setter.call( this, obj, name, args[ i + 1 ]); } else { obj[ name ] = args[ i + 1 ]; } } } } } /** * The VML namespace has to be registered with the document, or the shapes will be invisible * on initial render sometimes. This results in the infamous "Unspecified error" if called * at certain times, so catch that and retry after a delay. */ (function addVmlNamespace() { try { doc.namespaces.add(nsPrefix, 'urn:schemas-microsoft-com:vml', '#default#VML'); } catch (e) { setTimeout(addVmlNamespace, 1); } })(); function VmlShape( idSeed, ordinalGroup ) { this.elId = '_pie_' + ( idSeed || 'shape' ) + PIE.Util.getUID(this); this.ordinalGroup = ordinalGroup || 0; } VmlShape.prototype = { behaviorStyle: 'behavior:url(#default#VML);', defaultStyles: 'position:absolute;top:0px;left:0px;', defaultAttrs: 'coordorigin="1,1" stroked="false" ', tagName: 'shape', mightBeRendered: 0, getShape: function() { return this.mightBeRendered ? ( this._shape || ( this._shape = doc.getElementById( this.elId ) ) ) : null; }, setAttrs: createSetter( '' ), setStyles: createSetter( 'style' ), setFillAttrs: createSetter( 'fill' ), setSize: function( w, h ) { this.setStyles( 'width', w + 'px', 'height', h + 'px' ); this.setAttrs( 'coordsize', w * 2 + ',' + h * 2 ); }, getStyleCssText: function() { var styles = this[ attrsPrefix + 'style' ] || {}, cssText = [], p; for( p in styles ) { if( styles.hasOwnProperty( p ) ) { cssText.push( p + ':' + styles[p] ); } } return this.behaviorStyle + this.defaultStyles + cssText.join( ';' ); }, getMarkup: function() { var m, me = this, tag = me.tagName, tagStart = '<' + nsPrefix + ':', subElEnd = ' style="' + me.behaviorStyle + '" />'; me.mightBeRendered = 1; function pushAttrs( keyVals ) { if( keyVals ) { for( var key in keyVals ) { if( keyVals.hasOwnProperty( key ) ) { m.push( ' ' + key + '="' + keyVals[key] + '"' ); } } } } function pushElement( name ) { var attrs = me[ attrsPrefix + name ]; if( attrs ) { m.push( tagStart + name ); pushAttrs( attrs ); m.push( subElEnd ); } } m = [ tagStart, tag, ' id="', me.elId, '" style="', me.getStyleCssText(), '" ', me.defaultAttrs ]; pushAttrs( me[ attrsPrefix ] ); m.push( '>' ); pushElement( 'fill' ); m.push( '</' + nsPrefix + ':' + tag + '>' ); return m.join( '' ); }, destroy: function() { var shape = this.getShape(), par = shape && shape.parentNode; if( par ) { par.removeChild(shape); delete this._shape; } } }; return VmlShape; })();PIE.RendererBase = { /** * Create a new Renderer class, with the standard constructor, and augmented by * the RendererBase's members. * @param proto */ newRenderer: function( proto ) { function Renderer( el, boundsInfo, styleInfos, parent ) { this.targetElement = el; this.boundsInfo = boundsInfo; this.styleInfos = styleInfos; this.parent = parent; } PIE.merge( Renderer.prototype, PIE.RendererBase, proto ); return Renderer; }, /** * Determine if the renderer needs to be updated * @return {boolean} */ needsUpdate: function() { return false; }, /** * Run any preparation logic that would affect the main update logic of this * renderer or any of the other renderers, e.g. things that might affect the * element's size or style properties. */ prepareUpdate: PIE.emptyFn, /** * Tell the renderer to update based on modified properties or element dimensions */ updateRendering: function() { if( this.isActive() ) { this.draw(); } else { this.destroy(); } }, /** * Hide the target element's border */ hideBorder: function() { this.targetElement.runtimeStyle.borderColor = 'transparent'; }, /** * Destroy the rendered objects. This is a base implementation which handles common renderer * structures, but individual renderers may override as necessary. */ destroy: function() { } }; PIE.merge(PIE.RendererBase, { /** * Get a VmlShape by name, creating it if necessary. * @param {string} name A name identifying the element * @param {number} zIndex Specifies the target z-index of the shape. This will be used when rendering * the shape to ensure it is inserted in the correct order with other shapes to give * correct stacking order without using actual CSS z-index. * @return {PIE.VmlShape} */ getShape: function( name, zIndex ) { var shapes = this._shapes || ( this._shapes = {} ), shape = shapes[ name ]; if( !shape ) { shape = shapes[ name ] = new PIE.VmlShape( name, zIndex ); this.parent.enqueueShapeForRender( shape ); } return shape; }, /** * Delete a named shape which was created by getShape(). Returns true if a shape with the * given name was found and deleted, or false if there was no shape of that name. * @param {string} name * @return {boolean} */ deleteShape: function( name ) { var shapes = this._shapes, shape = shapes && shapes[ name ]; if( shape ) { shape.destroy(); this.parent.removeShape( shape ); delete shapes[ name ]; } return !!shape; }, /** * For a given set of border radius length/percentage values, convert them to concrete pixel * values based on the current size of the target element. * @param {Object} radii * @return {Object} */ getRadiiPixels: function( radii ) { var el = this.targetElement, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, tlX, tlY, trX, trY, brX, brY, blX, blY, f; tlX = radii.x['tl'].pixels( el, w ); tlY = radii.y['tl'].pixels( el, h ); trX = radii.x['tr'].pixels( el, w ); trY = radii.y['tr'].pixels( el, h ); brX = radii.x['br'].pixels( el, w ); brY = radii.y['br'].pixels( el, h ); blX = radii.x['bl'].pixels( el, w ); blY = radii.y['bl'].pixels( el, h ); // If any corner ellipses overlap, reduce them all by the appropriate factor. This formula // is taken straight from the CSS3 Backgrounds and Borders spec. f = Math.min( w / ( tlX + trX ), h / ( trY + brY ), w / ( blX + brX ), h / ( tlY + blY ) ); if( f < 1 ) { tlX *= f; tlY *= f; trX *= f; trY *= f; brX *= f; brY *= f; blX *= f; blY *= f; } return { x: { 'tl': tlX, 'tr': trX, 'br': brX, 'bl': blX }, y: { 'tl': tlY, 'tr': trY, 'br': brY, 'bl': blY } } }, /** * Return the VML path string for the element's background box, with corners rounded. * @param {number} shrinkT - number of pixels to shrink the box path inward from the element's top side. * @param {number} shrinkR - number of pixels to shrink the box path inward from the element's right side. * @param {number} shrinkB - number of pixels to shrink the box path inward from the element's bottom side. * @param {number} shrinkL - number of pixels to shrink the box path inward from the element's left side. * @param {number} mult All coordinates will be multiplied by this number * @param {Object=} radii If specified, this will be used for the corner radii instead of the properties * from this renderer's borderRadiusInfo object. * @return {string} the VML path */ getBoxPath: function( shrinkT, shrinkR, shrinkB, shrinkL, mult, radii ) { var coords = this.getBoxPathCoords( shrinkT, shrinkR, shrinkB, shrinkL, mult, radii ); return 'm' + coords[ 0 ] + ',' + coords[ 1 ] + 'qy' + coords[ 2 ] + ',' + coords[ 3 ] + 'l' + coords[ 4 ] + ',' + coords[ 5 ] + 'qx' + coords[ 6 ] + ',' + coords[ 7 ] + 'l' + coords[ 8 ] + ',' + coords[ 9 ] + 'qy' + coords[ 10 ] + ',' + coords[ 11 ] + 'l' + coords[ 12 ] + ',' + coords[ 13 ] + 'qx' + coords[ 14 ] + ',' + coords[ 15 ] + 'x'; }, /** * Return the VML coordinates for all the vertices in the rounded box path. * @param {number} shrinkT - number of pixels to shrink the box path inward from the element's top side. * @param {number} shrinkR - number of pixels to shrink the box path inward from the element's right side. * @param {number} shrinkB - number of pixels to shrink the box path inward from the element's bottom side. * @param {number} shrinkL - number of pixels to shrink the box path inward from the element's left side. * @param {number=} mult If specified, all coordinates will be multiplied by this number * @param {Object=} radii If specified, this will be used for the corner radii instead of the properties * from this renderer's borderRadiusInfo object. * @return {Array.<number>} all the coordinates going clockwise, starting with the top-left corner's lower vertex */ getBoxPathCoords: function( shrinkT, shrinkR, shrinkB, shrinkL, mult, radii ) { var bounds = this.boundsInfo.getBounds(), w = bounds.w * mult, h = bounds.h * mult, M = Math, floor = M.floor, ceil = M.ceil, max = M.max, min = M.min, coords; shrinkT *= mult; shrinkR *= mult; shrinkB *= mult; shrinkL *= mult; if ( !radii ) { radii = this.styleInfos.borderRadiusInfo.getProps(); } if ( radii ) { radii = this.getRadiiPixels( radii ); var tlRadiusX = radii.x['tl'] * mult, tlRadiusY = radii.y['tl'] * mult, trRadiusX = radii.x['tr'] * mult, trRadiusY = radii.y['tr'] * mult, brRadiusX = radii.x['br'] * mult, brRadiusY = radii.y['br'] * mult, blRadiusX = radii.x['bl'] * mult, blRadiusY = radii.y['bl'] * mult; coords = [ floor( shrinkL ), // top-left lower x floor( min( max( tlRadiusY, shrinkT ), h - shrinkB ) ), // top-left lower y floor( min( max( tlRadiusX, shrinkL ), w - shrinkR ) ), // top-left upper x floor( shrinkT ), // top-left upper y ceil( max( shrinkL, w - max( trRadiusX, shrinkR ) ) ), // top-right upper x floor( shrinkT ), // top-right upper y ceil( w - shrinkR ), // top-right lower x floor( min( max( trRadiusY, shrinkT ), h - shrinkB ) ), // top-right lower y ceil( w - shrinkR ), // bottom-right upper x ceil( max( shrinkT, h - max( brRadiusY, shrinkB ) ) ), // bottom-right upper y ceil( max( shrinkL, w - max( brRadiusX, shrinkR ) ) ), // bottom-right lower x ceil( h - shrinkB ), // bottom-right lower y floor( min( max( blRadiusX, shrinkL ), w - shrinkR ) ), // bottom-left lower x ceil( h - shrinkB ), // bottom-left lower y floor( shrinkL ), // bottom-left upper x ceil( max( shrinkT, h - max( blRadiusY, shrinkB ) ) ) // bottom-left upper y ]; } else { // Skip most of the heavy math for a simple non-rounded box var t = floor( shrinkT ), r = ceil( w - shrinkR ), b = ceil( h - shrinkB ), l = floor( shrinkL ); coords = [ l, t, l, t, r, t, r, t, r, b, r, b, l, b, l, b ]; } return coords; }, /** * Hide the actual border of the element. In IE7 and up we can just set its color to transparent; * however IE6 does not support transparent borders so we have to get tricky with it. Also, some elements * like form buttons require removing the border width altogether, so for those we increase the padding * by the border size. */ hideBorder: function() { var el = this.targetElement, cs = el.currentStyle, rs = el.runtimeStyle, tag = el.tagName, isIE6 = PIE.ieVersion === 6, sides, side, i; if( ( isIE6 && ( tag in PIE.childlessElements || tag === 'FIELDSET' ) ) || tag === 'BUTTON' || ( tag === 'INPUT' && el.type in PIE.inputButtonTypes ) ) { rs.borderWidth = ''; sides = this.styleInfos.borderInfo.sides; for( i = sides.length; i--; ) { side = sides[ i ]; rs[ 'padding' + side ] = ''; rs[ 'padding' + side ] = ( PIE.getLength( cs[ 'padding' + side ] ) ).pixels( el ) + ( PIE.getLength( cs[ 'border' + side + 'Width' ] ) ).pixels( el ) + ( PIE.ieVersion !== 8 && i % 2 ? 1 : 0 ); //needs an extra horizontal pixel to counteract the extra "inner border" going away } rs.borderWidth = 0; } else if( isIE6 ) { // Wrap all the element's children in a custom element, set the element to visiblity:hidden, // and set the wrapper element to visiblity:visible. This hides the outer element's decorations // (background and border) but displays all the contents. // TODO find a better way to do this that doesn't mess up the DOM parent-child relationship, // as this can interfere with other author scripts which add/modify/delete children. Also, this // won't work for elements which cannot take children, e.g. input/button/textarea/img/etc. Look into // using a compositor filter or some other filter which masks the border. if( el.childNodes.length !== 1 || el.firstChild.tagName !== 'ie6-mask' ) { var cont = doc.createElement( 'ie6-mask' ), s = cont.style, child; s.visibility = 'visible'; s.zoom = 1; while( child = el.firstChild ) { cont.appendChild( child ); } el.appendChild( cont ); rs.visibility = 'hidden'; } } else { rs.borderColor = 'transparent'; } }, unhideBorder: function() { }, /** * Destroy the rendered objects. This is a base implementation which handles common renderer * structures, but individual renderers may override as necessary. */ destroy: function() { var shapes = this._shapes, s; if ( shapes ) { for( s in shapes ) { if( shapes.hasOwnProperty( s ) ) { this.deleteShape( s ); } } } } }); /** * Root renderer; creates the outermost container element and handles keeping it aligned * with the target element's size and position. * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects */ PIE.RootRenderer = PIE.RendererBase.newRenderer( { isActive: function() { var children = this.childRenderers; for( var i in children ) { if( children.hasOwnProperty( i ) && children[ i ].isActive() ) { return true; } } return false; }, getBoxCssText: function() { var el = this.getPositioningElement(), par = el, docEl, parRect, tgtCS = el.currentStyle, tgtPos = tgtCS.position, boxPos, cs, x = 0, y = 0, elBounds = this.boundsInfo.getBounds(), vis = this.styleInfos.visibilityInfo.getProps(), logicalZoomRatio = elBounds.logicalZoomRatio; if( tgtPos === 'fixed' && PIE.ieVersion > 6 ) { x = elBounds.x * logicalZoomRatio; y = elBounds.y * logicalZoomRatio; boxPos = tgtPos; } else { // Get the element's offsets from its nearest positioned ancestor. Uses // getBoundingClientRect for accuracy and speed. do { par = par.offsetParent; } while( par && ( par.currentStyle.position === 'static' ) ); if( par ) { parRect = par.getBoundingClientRect(); cs = par.currentStyle; x = ( elBounds.x - parRect.left ) * logicalZoomRatio - ( parseFloat(cs.borderLeftWidth) || 0 ); y = ( elBounds.y - parRect.top ) * logicalZoomRatio - ( parseFloat(cs.borderTopWidth) || 0 ); } else { docEl = doc.documentElement; x = ( elBounds.x + docEl.scrollLeft - docEl.clientLeft ) * logicalZoomRatio; y = ( elBounds.y + docEl.scrollTop - docEl.clientTop ) * logicalZoomRatio; } boxPos = 'absolute'; } return 'direction:ltr;' + 'position:absolute;' + 'behavior:none !important;' + 'position:' + boxPos + ';' + 'left:' + x + 'px;' + 'top:' + y + 'px;' + 'z-index:' + ( tgtPos === 'static' ? -1 : tgtCS.zIndex ) + ';' + 'display:' + ( vis.visible && vis.displayed ? 'block' : 'none' ); }, updateBoxStyles: function() { var me = this, boxEl = me.getBoxEl(); if( boxEl && ( me.boundsInfo.positionChanged() || me.styleInfos.visibilityInfo.changed() ) ) { boxEl.style.cssText = me.getBoxCssText(); } }, getPositioningElement: function() { var el = this.targetElement; return el.tagName in PIE.tableCellTags ? el.offsetParent : el; }, /** * Get a reference to the css3pie container element that contains the VML shapes, * if it has been inserted. */ getBoxEl: function() { var box = this._box; if( !box ) { box = this._box = doc.getElementById( '_pie' + PIE.Util.getUID( this ) ); } return box; }, /** * Render any child rendrerer shapes which have not already been rendered into the DOM. */ updateRendering: function() { var me = this, queue = me._shapeRenderQueue, renderedShapes, markup, i, len, j, ref, pos, vis; if (me.isActive()) { if( queue ) { // We've already rendered something once, so do incremental insertion of new shapes renderedShapes = me._renderedShapes; if( renderedShapes ) { for( i = 0, len = queue.length; i < len; i++ ) { for( j = renderedShapes.length; j--; ) { if( renderedShapes[ j ].ordinalGroup < queue[ i ].ordinalGroup ) { break; } } if ( j < 0 ) { ref = me.getBoxEl(); pos = 'afterBegin'; } else { ref = renderedShapes[ j ].getShape(); pos = 'afterEnd'; } ref.insertAdjacentHTML( pos, queue[ i ].getMarkup() ); renderedShapes.splice( j < 0 ? 0 : j, 0, queue[ i ] ); } me._shapeRenderQueue = 0; me.updateBoxStyles(); } // This is the first render, so build up a single markup string and insert it all at once else { vis = me.styleInfos.visibilityInfo.getProps(); if( vis.visible && vis.displayed ) { queue.sort( me.shapeSorter ); markup = [ '<css3pie id="_pie' + PIE.Util.getUID( me ) + '" style="' + me.getBoxCssText() + '">' ]; for( i = 0, len = queue.length; i < len; i++ ) { markup.push( queue[ i ].getMarkup() ); } markup.push( '</css3pie>' ); me.getPositioningElement().insertAdjacentHTML( 'beforeBegin', markup.join( '' ) ); me._renderedShapes = queue; me._shapeRenderQueue = 0; } } } else { me.updateBoxStyles(); } } else { me.destroy(); } }, shapeSorter: function( shape1, shape2 ) { return shape1.ordinalGroup - shape2.ordinalGroup; }, /** * Add a VmlShape into the queue to get rendered in finishUpdate */ enqueueShapeForRender: function( shape ) { var me = this, queue = me._shapeRenderQueue || ( me._shapeRenderQueue = [] ); queue.push( shape ); }, /** * Remove a VmlShape from the DOM and also from the internal list of rendered shapes. */ removeShape: function( shape ) { var shapes = this._renderedShapes, i; if ( shapes ) { for( i = shapes.length; i--; ) { if( shapes[ i ] === shape ) { shapes.splice( i, 1 ); break; } } } }, destroy: function() { var box = this._box, par; if( box && ( par = box.parentNode ) ) { par.removeChild( box ); } delete this._box; delete this._renderedShapes; } } ); // Prime IE for recognizing the custom <css3pie> element doc.createElement( 'css3pie' ); /** * Renderer for element backgrounds. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BackgroundRenderer = PIE.RendererBase.newRenderer( { shapeZIndex: 2, needsUpdate: function() { var si = this.styleInfos; return si.backgroundInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderImageInfo.isActive() || si.borderRadiusInfo.isActive() || si.backgroundInfo.isActive() || ( si.boxShadowInfo.isActive() && si.boxShadowInfo.getProps().inset ); }, /** * Draw the shapes */ draw: function() { var bounds = this.boundsInfo.getBounds(); if( bounds.w && bounds.h ) { this.drawBgColor(); this.drawBgImages(); } }, /** * Draw the background color shape */ drawBgColor: function() { var props = this.styleInfos.backgroundInfo.getProps(), bounds = this.boundsInfo.getBounds(), el = this.targetElement, color = props && props.color, shape, alpha; if( color && color.alpha() > 0 ) { this.hideBackground(); shape = this.getShape( 'bgColor', this.shapeZIndex ); shape.setSize( bounds.w, bounds.h ); shape.setAttrs( 'path', this.getBgClipPath( bounds, props.colorClip ) ); shape.setFillAttrs( 'color', color.colorValue( el ) ); alpha = color.alpha(); if( alpha < 1 ) { shape.setFillAttrs( 'opacity', alpha ); } } else { this.deleteShape( 'bgColor' ); } }, /** * Draw all the background image layers */ drawBgImages: function() { var props = this.styleInfos.backgroundInfo.getProps(), bounds = this.boundsInfo.getBounds(), images = props && props.bgImages, img, shape, w, h, i; if( images ) { this.hideBackground(); w = bounds.w; h = bounds.h; i = images.length; while( i-- ) { img = images[i]; shape = this.getShape( 'bgImage' + i, this.shapeZIndex + ( .5 - i / 1000 ) ); shape.setAttrs( 'path', this.getBgClipPath( bounds, img.bgClip ) ); shape.setSize( w, h ); if( img.imgType === 'linear-gradient' ) { this.addLinearGradient( shape, img ); } else { shape.setFillAttrs( 'type', 'tile', 'color', 'none' ); this.positionBgImage( shape, img.imgUrl, i ); } } } // Delete any bgImage shapes previously created which weren't used above i = images ? images.length : 0; while( this.deleteShape( 'bgImage' + i++ ) ) {} }, /** * Set the position and clipping of the background image for a layer * @param {Element} shape * @param {String} src * @param {number} index */ positionBgImage: function( shape, src, index ) { PIE.Util.withImageSize( src, function( imgSize ) { var me = this, el = me.targetElement, bounds = me.boundsInfo.getBounds(), elW = bounds.w, elH = bounds.h; // It's possible that the element dimensions are zero now but weren't when the original // update executed, make sure that's not the case to avoid divide-by-zero error if( elW && elH ) { var styleInfos = me.styleInfos, bgInfo = styleInfos.backgroundInfo, bg = bgInfo.getProps().bgImages[ index ], bgAreaSize = bgInfo.getBgAreaSize( bg.bgOrigin, me.boundsInfo, styleInfos.borderInfo, styleInfos.paddingInfo ), adjustedImgSize = ( bg.bgSize || PIE.BgSize.DEFAULT ).pixels( me.targetElement, bgAreaSize.w, bgAreaSize.h, imgSize.w, imgSize.h ), bgOriginXY = me.getBgOriginXY( bg.bgOrigin ), bgPos = bg.bgPosition ? bg.bgPosition.coords( el, bgAreaSize.w - adjustedImgSize.w, bgAreaSize.h - adjustedImgSize.h ) : { x:0, y:0 }, repeat = bg.imgRepeat, pxX, pxY, clipT = 0, clipL = 0, clipR = elW + 1, clipB = elH + 1, //make sure the default clip region is not inside the box (by a subpixel) clipAdjust = PIE.ieVersion === 8 ? 0 : 1; //prior to IE8 requires 1 extra pixel in the image clip region // Positioning - find the pixel offset from the top/left and convert to a ratio // The position is shifted by half a pixel, to adjust for the half-pixel coordorigin shift which is // needed to fix antialiasing but makes the bg image fuzzy. pxX = Math.round( bgOriginXY.x + bgPos.x ) + 0.5; pxY = Math.round( bgOriginXY.y + bgPos.y ) + 0.5; shape.setFillAttrs( 'src', src, 'position', ( pxX / elW ) + ',' + ( pxY / elH ), // Set the size of the image. We only set it if the image is scaled via background-size or by // the user changing the browser zoom level, to avoid fuzzy images at normal size. For some reason // using px units doesn't work in VML markup so we must convert to pt. 'size', ( adjustedImgSize.w !== imgSize.w || adjustedImgSize.h !== imgSize.h || bounds.logicalZoomRatio !== 1 || screen['logicalXDPI'] / screen['deviceXDPI'] !== 1 ) ? PIE.Length.pxToPt( adjustedImgSize.w ) + 'pt,' + PIE.Length.pxToPt( adjustedImgSize.h ) + 'pt' : '' ); // Repeating - clip the image shape if( repeat && repeat !== 'repeat' ) { if( repeat === 'repeat-x' || repeat === 'no-repeat' ) { clipT = pxY + 1; clipB = pxY + adjustedImgSize.h + clipAdjust; } if( repeat === 'repeat-y' || repeat === 'no-repeat' ) { clipL = pxX + 1; clipR = pxX + adjustedImgSize.w + clipAdjust; } shape.setStyles( 'clip', 'rect(' + clipT + 'px,' + clipR + 'px,' + clipB + 'px,' + clipL + 'px)' ); } } }, this ); }, /** * For a given background-clip value, return the VML path for that clip area. * @param {Object} bounds * @param {String} bgClip */ getBgClipPath: function( bounds, bgClip ) { var me = this, shrinkT = 0, shrinkR = 0, shrinkB = 0, shrinkL = 0, el = me.targetElement, styleInfos = me.styleInfos, borders, paddings; if ( bgClip && bgClip !== 'border-box' ) { borders = styleInfos.borderInfo.getProps(); if ( borders && ( borders = borders.widths ) ) { shrinkT += borders[ 't' ].pixels( el ); shrinkR += borders[ 'r' ].pixels( el ); shrinkB += borders[ 'b' ].pixels( el ); shrinkL += borders[ 'l' ].pixels( el ); } } if ( bgClip === 'content-box' ) { paddings = styleInfos.paddingInfo.getProps(); if( paddings ) { shrinkT += paddings[ 't' ].pixels( el ); shrinkR += paddings[ 'r' ].pixels( el ); shrinkB += paddings[ 'b' ].pixels( el ); shrinkL += paddings[ 'l' ].pixels( el ); } } // Add points at 0,0 and w,h so that the image size/position will still be // based on the full element area. return 'm0,0r0,0m' + bounds.w * 2 + ',' + bounds.h * 2 + 'r0,0' + me.getBoxPath( shrinkT, shrinkR, shrinkB, shrinkL, 2 ); }, /** * For a given background-origin value, return the x/y position of the origin * from the top-left of the element bounds. * @param {String} bgOrigin */ getBgOriginXY: function( bgOrigin ) { var me = this, el = me.targetElement, styleInfos = me.styleInfos, x = 0, y = 0, borders, paddings; if( bgOrigin !== 'border-box' ) { borders = styleInfos.borderInfo.getProps(); if( borders && ( borders = borders.widths ) ) { x += borders[ 'l' ].pixels( el ); y += borders[ 't' ].pixels( el ); } } if ( bgOrigin === 'content-box' ) { paddings = styleInfos.paddingInfo.getProps(); if( paddings ) { x += paddings[ 'l' ].pixels( el ); y += paddings[ 't' ].pixels( el ); } } return { x: x, y: y }; }, /** * Draw the linear gradient for a gradient layer * @param {Element} shape * @param {Object} info The object holding the information about the gradient */ addLinearGradient: function( shape, info ) { var el = this.targetElement, bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, stops = info.stops, stopCount = stops.length, PI = Math.PI, metrics = PIE.GradientUtil.getGradientMetrics( el, w, h, info ), angle = metrics.angle, lineLength = metrics.lineLength, vmlAngle, vmlColors, stopPx, i, j, before, after; // In VML land, the angle of the rendered gradient depends on the aspect ratio of the shape's // bounding box; for example specifying a 45 deg angle actually results in a gradient // drawn diagonally from one corner to its opposite corner, which will only appear to the // viewer as 45 degrees if the shape is equilateral. We adjust for this by taking the x/y deltas // between the start and end points, multiply one of them by the shape's aspect ratio, // and get their arctangent, resulting in an appropriate VML angle. If the angle is perfectly // horizontal or vertical then we don't need to do this conversion. // VML angles go in the opposite direction from CSS angles. vmlAngle = ( angle % 90 ) ? Math.atan2( metrics.startY - metrics.endY, ( metrics.endX - metrics.startX ) * w / h ) / PI * 180 - 90 : -angle; while( vmlAngle < 0 ) { vmlAngle += 360; } vmlAngle = vmlAngle % 360; // Add all the stops to the VML 'colors' list, including the first and last stops. // For each, we find its pixel offset along the gradient-line; if the offset of a stop is less // than that of its predecessor we increase it to be equal. vmlColors = []; // Find the pixel offsets along the CSS3 gradient-line for each stop. stopPx = []; for( i = 0; i < stopCount; i++ ) { stopPx.push( stops[i].offset ? stops[i].offset.pixels( el, lineLength ) : i === 0 ? 0 : i === stopCount - 1 ? lineLength : null ); } // Fill in gaps with evenly-spaced offsets for( i = 1; i < stopCount; i++ ) { if( stopPx[ i ] === null ) { before = stopPx[ i - 1 ]; j = i; do { after = stopPx[ ++j ]; } while( after === null ); stopPx[ i ] = before + ( after - before ) / ( j - i + 1 ); } // Make sure each stop's offset is no less than the one before it stopPx[ i ] = Math.max( stopPx[ i ], stopPx[ i - 1 ] ); } // Convert to percentage along the gradient line and add to the VML 'colors' value for( i = 0; i < stopCount; i++ ) { vmlColors.push( ( stopPx[ i ] / lineLength * 100 ) + '% ' + stops[i].color.colorValue( el ) ); } // Now, finally, we're ready to render the gradient fill. Set the start and end colors to // the first and last stop colors; this just sets outer bounds for the gradient. shape.setFillAttrs( 'angle', vmlAngle, 'type', 'gradient', 'method', 'sigma', 'color', stops[0].color.colorValue( el ), 'color2', stops[stopCount - 1].color.colorValue( el ), 'colors', vmlColors.join( ',' ) ); // Set opacity; right now we only support this for two-stop gradients, multi-stop // opacity will require chopping up each segment into its own shape. // Note these seem backwards but they must be that way since VML strangely reverses // them when the 'colors' property is present. if ( stopCount === 2 ) { shape.setFillAttrs( 'opacity', stops[1].color.alpha(), 'o:opacity2', stops[0].color.alpha() ); } }, /** * Hide the actual background image and color of the element. */ hideBackground: function() { var rs = this.targetElement.runtimeStyle; rs.backgroundImage = 'url(about:blank)'; //ensures the background area reacts to mouse events rs.backgroundColor = 'transparent'; }, destroy: function() { PIE.RendererBase.destroy.call( this ); var rs = this.targetElement.runtimeStyle; rs.backgroundImage = rs.backgroundColor = ''; } } ); /** * Renderer for element borders. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BorderRenderer = PIE.RendererBase.newRenderer( { shapeZIndex: 4, /** * Single definition of arguments for use by the per-side creation loop in * getBorderSegmentsInfo. Arguments are, in order: * centerX1, centerY1, outerX1, outerY1, centerX2, centerY2, outerX2, outerY2, baseAngle */ sideArgs: { 't': [ 2, 1, 0, 3, 4, 7, 6, 5, 90 ], 'r': [ 4, 7, 6, 5, 10, 9, 8, 11, 0 ], 'b': [ 10, 9, 8, 11, 12, 15, 14, 13, 270 ], 'l': [ 12, 15, 14, 13, 2, 1, 0, 3, 180 ] }, dashedStyles: { 'dotted': 1, 'dashed': 1 }, colorManipStyles: { 'groove': 1, 'ridge': 1, 'inset': 1, 'outset': 1 }, doubleStyles: { 'groove': 1, 'ridge': 1, 'double': 1 }, needsUpdate: function() { var si = this.styleInfos; return si.borderInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderRadiusInfo.isActive() && !si.borderImageInfo.isActive() && si.borderInfo.isActive(); //check BorderStyleInfo last because it's the most expensive }, /** * Draw the border shape(s) */ draw: function() { var me = this, props = me.styleInfos.borderInfo.getProps(), bounds = me.boundsInfo.getBounds(), shape, segmentsInfo, i, j, len; if( props ) { me.hideBorder(); segmentsInfo = me.getBorderSegmentsInfo(); for( i = j = 0, len = segmentsInfo.length; i < len; i += 2) { shape = me.getShape( 'border' + j++, me.shapeZIndex ); shape.setSize( bounds.w, bounds.h ); shape.setAttrs( 'path', segmentsInfo[ i ] ); shape.setFillAttrs( 'color', segmentsInfo[ i + 1 ] ); } // remove any previously-created border shapes which didn't get used above while( me.deleteShape( 'border' + j++ ) ) {} } }, /** * Adds rectangular sub-paths at intervals along a given side which serve to "cut out" * those areas, forming the spaces in a dashed or dotted border. * @param {Array.<string>} path The path string array to which the extra sub-paths will be added * @param {number} startCoord The x or y coordinate at which the dashing starts * @param {number} endCoord The x or y coordinate at which the dashing ends * @param {number} sideWidth The width of the border on the target side * @param {number} shift A shift of the perpendicular coordinate * @param {boolean} isVertical True if this is a vertical border (left or right) * @param {string} style The border style, either 'dotted' or 'dashed' */ dashify: function( path, startCoord, endCoord, sideWidth, shift, isVertical, style ) { var dashLength = sideWidth * ( style === 'dashed' ? 3 : 1 ), shift2 = shift + sideWidth, dashEndCoord; // If dash is longer than the box edge, don't make any cutouts if( dashLength < endCoord - startCoord ) { // adjust the start to keep the dash pattern centered on the box edge, favoring full // spaces over full dashes, like WebKit does. startCoord += ( endCoord - startCoord - dashLength ) / 2 % dashLength; // add rectangular sub-paths to cut out each dash's space while( startCoord < endCoord ) { dashEndCoord = Math.min( startCoord + dashLength, endCoord ); path.push( isVertical ? ( 'm' + shift + ',' + startCoord + 'l' + shift + ',' + dashEndCoord + 'l' + shift2 + ',' + dashEndCoord + 'l' + shift2 + ',' + startCoord + 'x' ) : ( 'm' + startCoord + ',' + shift + 'l' + dashEndCoord + ',' + shift + 'l' + dashEndCoord + ',' + shift2 + 'l' + startCoord + ',' + shift2 + 'x' ) ); startCoord += dashLength * 2; } } }, /** * Get the VML path definitions for the border segment(s). * @return {Array.<string>} Pairs of segment info: 1st item in each pair is the path string, 2nd is the fill color */ getBorderSegmentsInfo: function() { var me = this, borderInfo = me.styleInfos.borderInfo, segmentsInfo = []; if( borderInfo.isActive() ) { var mult = 2, el = me.targetElement, bounds = me.boundsInfo.getBounds(), borderProps = borderInfo.getProps(), widths = borderProps.widths, styles = borderProps.styles, colors = borderProps.colors, M = Math, abs = M.abs, round = M.round, wT = round( widths['t'].pixels( el ) ), wR = round( widths['r'].pixels( el ) ), wB = round( widths['b'].pixels( el ) ), wL = round( widths['l'].pixels( el ) ), path = [], innerCoords, outerCoords, doubleOuterCoords, doubleInnerCoords, sideArgs = me.sideArgs, side, deg = 65535, dashedStyles = me.dashedStyles, style, color; // When the border has uniform color and style all the way around, we can get // away with a single VML path shape, otherwise we need four separate shapes. if ( borderProps.stylesSame && borderProps.colorsSame && !( styles[ 't' ] in me.colorManipStyles ) ) { if( colors['t'].alpha() > 0 ) { // Outer path path[ 0 ] = me.getBoxPath( 0, 0, 0, 0, mult ); // If double style, add the middle cutout sub-paths style = styles[ 't' ]; if( style === 'double' ) { path.push( me.getBoxPath( wT / 3, wR / 3, wB / 3, wL / 3, mult ) + me.getBoxPath( wT * 2 / 3, wR * 2 / 3, wB * 2 / 3, wL * 2 / 3, mult ) ); } // If dashed, add the dash cutout sub-paths else if( style in dashedStyles ) { innerCoords = me.getBoxPathCoords( wT, wR, wB, wL, mult ); me.dashify( path, innerCoords[ 2 ], innerCoords[ 4 ], wT * mult, 0, 0, styles[ 't' ] ); me.dashify( path, innerCoords[ 7 ], innerCoords[ 9 ], wR * mult, ( bounds.w - wR ) * mult, 1, styles[ 'r' ] ); me.dashify( path, innerCoords[ 12 ], innerCoords[ 10 ], wB * mult, ( bounds.h - wB ) * mult, 0, styles[ 'b' ] ); me.dashify( path, innerCoords[ 1 ], innerCoords[ 15 ], wL * mult, 0, 1, styles[ 'l' ] ); } // Inner path path.push( me.getBoxPath( wT, wR, wB, wL, mult ) ); segmentsInfo.push( path.join( '' ), colors['t'].colorValue( el ) ); } } else { outerCoords = me.getBoxPathCoords( 0, 0, 0, 0, mult ); innerCoords = me.getBoxPathCoords( wT, wR, wB, wL, mult ); // Build the segment for each side for( side in sideArgs ) { if ( sideArgs.hasOwnProperty( side ) && colors[ side ].alpha() > 0 ) { var args = sideArgs[ side ], centerX1 = args[ 0 ], centerY1 = args[ 1 ], outerX1 = args[ 2 ], outerY1 = args[ 3 ], centerX2 = args[ 4 ], centerY2 = args[ 5 ], outerX2 = args[ 6 ], outerY2 = args[ 7 ], baseAngle = args[ 8 ], isTopLeft = side === 't' || side === 'l'; style = styles[ side ]; // Outer edge path[ 0 ] = 'al' + outerCoords[ centerX1 ] + ',' + outerCoords[ centerY1 ] + ',' + abs( outerCoords[ outerX1 ] - outerCoords[ centerX1 ] ) + ',' + abs( outerCoords[ outerY1 ] - outerCoords[ centerY1 ] ) + ',' + ( baseAngle + 45 ) * deg + ',' + -45 * deg + 'ae' + outerCoords[ centerX2 ] + ',' + outerCoords[ centerY2 ] + ',' + abs( outerCoords[ outerX2 ] - outerCoords[ centerX2 ] ) + ',' + abs( outerCoords[ outerY2 ] - outerCoords[ centerY2 ] ) + ',' + baseAngle * deg + ',' + -45 * deg; // If double style, add the middle sub-paths if( style in me.doubleStyles ) { if( !doubleOuterCoords ) { if ( style === 'double' ) { doubleOuterCoords = me.getBoxPathCoords( wT / 3, wR / 3, wB / 3, wL / 3, mult ); doubleInnerCoords = me.getBoxPathCoords( wT * 2 / 3, wR * 2 / 3, wB * 2 / 3, wL * 2 / 3, mult ); } else { doubleOuterCoords = doubleInnerCoords = me.getBoxPathCoords( wT / 2, wR / 2, wB / 2, wL / 2, mult ); } } path.push( 'ae' + doubleOuterCoords[ centerX2 ] + ',' + doubleOuterCoords[ centerY2 ] + ',' + abs( doubleOuterCoords[ outerX2 ] - doubleOuterCoords[ centerX2 ] ) + ',' + abs( doubleOuterCoords[ outerY2 ] - doubleOuterCoords[ centerY2 ] ) + ',' + ( baseAngle - 45 ) * deg + ',' + 45 * deg + 'ae' + doubleOuterCoords[ centerX1 ] + ',' + doubleOuterCoords[ centerY1 ] + ',' + abs( doubleOuterCoords[ outerX1 ] - doubleOuterCoords[ centerX1 ] ) + ',' + abs( doubleOuterCoords[ outerY1 ] - doubleOuterCoords[ centerY1 ] ) + ',' + baseAngle * deg + ',' + 45 * deg + 'x' ); // Actual 'double' style with have both paths as a single shape, but 'ridge' and // 'groove' need separate shapes for the different colors if( style !== 'double' ) { color = colors[ side ].colorValue( el ) + ( ( style === 'groove' ? isTopLeft : !isTopLeft ) ? ' darken(128)' : ' lighten(128)' ); segmentsInfo.push( path.join( '' ), color ); path.length = 0; //reuse same array for next loop } path.push( 'al' + doubleInnerCoords[ centerX1 ] + ',' + doubleInnerCoords[ centerY1 ] + ',' + abs( doubleInnerCoords[ outerX1 ] - doubleInnerCoords[ centerX1 ] ) + ',' + abs( doubleInnerCoords[ outerY1 ] - doubleInnerCoords[ centerY1 ] ) + ',' + ( baseAngle + 45 ) * deg + ',' + -45 * deg + 'ae' + doubleInnerCoords[ centerX2 ] + ',' + doubleInnerCoords[ centerY2 ] + ',' + abs( doubleInnerCoords[ outerX2 ] - doubleInnerCoords[ centerX2 ] ) + ',' + abs( doubleInnerCoords[ outerY2 ] - doubleInnerCoords[ centerY2 ] ) + ',' + baseAngle * deg + ',' + -45 * deg ); } // Inner edge path.push( 'ae' + innerCoords[ centerX2 ] + ',' + innerCoords[ centerY2 ] + ',' + abs( innerCoords[ outerX2 ] - innerCoords[ centerX2 ] ) + ',' + abs( innerCoords[ outerY2 ] - innerCoords[ centerY2 ] ) + ',' + ( baseAngle - 45 ) * deg + ',' + 45 * deg + 'ae' + innerCoords[ centerX1 ] + ',' + innerCoords[ centerY1 ] + ',' + abs( innerCoords[ outerX1 ] - innerCoords[ centerX1 ] ) + ',' + abs( innerCoords[ outerY1 ] - innerCoords[ centerY1 ] ) + ',' + baseAngle * deg + ',' + 45 * deg + 'x' ); // For dashed/dotted styles, add the dash cutout sub-paths if ( style in dashedStyles ) { side === 't' ? me.dashify( path, innerCoords[ 2 ], innerCoords[ 4 ], wT * mult, 0, 0, style ) : side === 'r' ? me.dashify( path, innerCoords[ 7 ], innerCoords[ 9 ], wR * mult, ( bounds.w - wR ) * mult, 1, style ) : side === 'b' ? me.dashify( path, innerCoords[ 12 ], innerCoords[ 10 ], wB * mult, ( bounds.h - wB ) * mult, 0, style ) : //side === 'l' ? me.dashify( path, innerCoords[ 1 ], innerCoords[ 15 ], wL * mult, 0, 1, style ); } color = colors[ side ].colorValue( el ); if ( style in me.colorManipStyles ) { // lighten or darken as appropriate color += ( ( ( style === 'groove' || style === 'outset' ) ? isTopLeft : !isTopLeft ) ? ' lighten(128)' : ' darken(128)' ); } segmentsInfo.push( path.join( '' ), color ); path.length = 0; //reuse same array for next loop } } } } return segmentsInfo; }, destroy: function() { var me = this; if (me.finalized || !me.styleInfos.borderImageInfo.isActive()) { me.targetElement.runtimeStyle.borderColor = ''; } PIE.RendererBase.destroy.call( me ); } } ); /** * Renderer for border-image * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BorderImageRenderer = PIE.RendererBase.newRenderer( { shapeZIndex: 5, needsUpdate: function() { return this.styleInfos.borderImageInfo.changed(); }, isActive: function() { return this.styleInfos.borderImageInfo.isActive(); }, draw: function() { var me = this, props = me.styleInfos.borderImageInfo.getProps(), borderProps = me.styleInfos.borderInfo.getProps(), bounds = me.boundsInfo.getBounds(), el = me.targetElement; PIE.Util.withImageSize( props.src, function( imgSize ) { var me = this, elW = bounds.w, elH = bounds.h, zero = PIE.getLength( '0' ), widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ), widthT = widths['t'].pixels( el ), widthR = widths['r'].pixels( el ), widthB = widths['b'].pixels( el ), widthL = widths['l'].pixels( el ), slices = props.slice, sliceT = slices['t'].pixels( el ), sliceR = slices['r'].pixels( el ), sliceB = slices['b'].pixels( el ), sliceL = slices['l'].pixels( el ), src = props.src, imgW = imgSize.w, imgH = imgSize.h; function setSizeAndPos( rect, rectX, rectY, rectW, rectH, sliceX, sliceY, sliceW, sliceH ) { // Hide the piece entirely if we have zero dimensions for the image, the rect, or the slice var max = Math.max; if ( !imgW || !imgH || !rectW || !rectH || !sliceW || !sliceH ) { rect.setStyles( 'display', 'none' ); } else { rectW = max( rectW, 0 ); rectH = max( rectH, 0 ); rect.setAttrs( 'path', 'm0,0l' + rectW * 2 + ',0l' + rectW * 2 + ',' + rectH * 2 + 'l0,' + rectH * 2 + 'x' ); rect.setFillAttrs( 'src', src, 'type', 'tile', 'position', '0,0', 'origin', ( ( sliceX - 0.5 ) / imgW ) + ',' + ( ( sliceY - 0.5 ) / imgH ), // For some reason using px units doesn't work in VML markup so we must convert to pt. 'size', PIE.Length.pxToPt( rectW * imgW / sliceW ) + 'pt,' + PIE.Length.pxToPt( rectH * imgH / sliceH ) + 'pt' ); rect.setSize( rectW, rectH ); rect.setStyles( 'left', rectX + 'px', 'top', rectY + 'px', 'display', '' ); } } // Piece positions and sizes // TODO right now this treats everything like 'stretch', need to support other schemes setSizeAndPos( me.getRect( 'tl' ), 0, 0, widthL, widthT, 0, 0, sliceL, sliceT ); setSizeAndPos( me.getRect( 't' ), widthL, 0, elW - widthL - widthR, widthT, sliceL, 0, imgW - sliceL - sliceR, sliceT ); setSizeAndPos( me.getRect( 'tr' ), elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT ); setSizeAndPos( me.getRect( 'r' ), elW - widthR, widthT, widthR, elH - widthT - widthB, imgW - sliceR, sliceT, sliceR, imgH - sliceT - sliceB ); setSizeAndPos( me.getRect( 'br' ), elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB ); setSizeAndPos( me.getRect( 'b' ), widthL, elH - widthB, elW - widthL - widthR, widthB, sliceL, imgH - sliceB, imgW - sliceL - sliceR, sliceB ); setSizeAndPos( me.getRect( 'bl' ), 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB ); setSizeAndPos( me.getRect( 'l' ), 0, widthT, widthL, elH - widthT - widthB, 0, sliceT, sliceL, imgH - sliceT - sliceB ); setSizeAndPos( me.getRect( 'c' ), widthL, widthT, elW - widthL - widthR, elH - widthT - widthB, sliceL, sliceT, props.fill ? imgW - sliceL - sliceR : 0, imgH - sliceT - sliceB ); }, me ); }, getRect: function( name ) { return this.getShape( 'borderImage_' + name, this.shapeZIndex ); }, prepareUpdate: function() { if (this.isActive()) { var me = this, el = me.targetElement, rs = el.runtimeStyle, widths = me.styleInfos.borderImageInfo.getProps().widths; // Force border-style to solid so it doesn't collapse rs.borderStyle = 'solid'; // If widths specified in border-image shorthand, override border-width if ( widths ) { rs.borderTopWidth = widths['t'].pixels( el ); rs.borderRightWidth = widths['r'].pixels( el ); rs.borderBottomWidth = widths['b'].pixels( el ); rs.borderLeftWidth = widths['l'].pixels( el ); } // Make the border transparent me.hideBorder(); } }, destroy: function() { var me = this, rs = me.targetElement.runtimeStyle; rs.borderStyle = ''; if (me.finalized || !me.styleInfos.borderInfo.isActive()) { rs.borderColor = rs.borderWidth = ''; } PIE.RendererBase.destroy.call( me ); } } ); /** * Renderer for outset box-shadows * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.BoxShadowOutsetRenderer = PIE.RendererBase.newRenderer( { shapeZIndex: 1, needsUpdate: function() { var si = this.styleInfos; return si.boxShadowInfo.changed() || si.borderRadiusInfo.changed(); }, isActive: function() { var boxShadowInfo = this.styleInfos.boxShadowInfo; return boxShadowInfo.isActive() && boxShadowInfo.getProps().outset[0]; }, draw: function() { var me = this, el = me.targetElement, styleInfos = me.styleInfos, shadowInfos = styleInfos.boxShadowInfo.getProps().outset, radii = styleInfos.borderRadiusInfo.getProps(), len = shadowInfos.length, i = len, bounds = me.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, shadowInfo, shape, xOff, yOff, spread, blur, shrink, color, alpha, path, totalW, totalH, focusX, focusY, focusAdjustRatio; while( i-- ) { shadowInfo = shadowInfos[ i ]; xOff = shadowInfo.xOffset.pixels( el ); yOff = shadowInfo.yOffset.pixels( el ); spread = shadowInfo.spread.pixels( el ); blur = shadowInfo.blur.pixels( el ); color = shadowInfo.color; alpha = color.alpha(); color = color.colorValue( el ); // Shape path shrink = -spread - blur; if( !radii && blur ) { // If blurring, use a non-null border radius info object so that getBoxPath will // round the corners of the expanded shadow shape rather than squaring them off. radii = PIE.BorderRadiusStyleInfo.ALL_ZERO; } path = me.getBoxPath( shrink, shrink, shrink, shrink, 2, radii ); // Create the shape object shape = me.getShape( 'shadow' + i, me.shapeZIndex + ( .5 - i / 1000 ) ); if( blur ) { totalW = ( spread + blur ) * 2 + w; totalH = ( spread + blur ) * 2 + h; focusX = totalW ? blur * 2 / totalW : 0; focusY = totalH ? blur * 2 / totalH : 0; // If the blur is larger than half the element's narrowest dimension, then its focussize // will to be less than zero which results in ugly artifacts. To get around this, we adjust // the focus to keep it centered and then bump the center opacity down to match. if (focusX > 0.5 || focusY > 0.5) { focusAdjustRatio = 0.5 / Math.max(focusX, focusY); focusX *= focusAdjustRatio; focusY *= focusAdjustRatio; alpha *= focusAdjustRatio * focusAdjustRatio; //this is a rough eyeball-adjustment, could be refined } shape.setFillAttrs( 'type', 'gradienttitle', //makes the VML gradient follow the shape's outline - hooray for undocumented features?!?! 'color2', color, 'focusposition', focusX + ',' + focusY, 'focussize', ( 1 - focusX * 2 ) + ',' + ( 1 - focusY * 2 ), 'opacity', 0, 'o:opacity2', alpha ); } else { shape.setFillAttrs( 'type', 'solid', 'opacity', alpha ); } shape.setAttrs( 'path', path ); shape.setFillAttrs( 'color', color ); shape.setStyles( 'left', xOff + 'px', 'top', yOff + 'px' ); shape.setSize( w, h ); } // Delete any shadow shapes previously created which weren't reused above while( me.deleteShape( 'shadow' + len++ ) ) {} } } ); /** * Renderer for re-rendering img elements using VML. Kicks in if the img has * a border-radius applied, or if the -pie-png-fix flag is set. * @constructor * @param {Element} el The target element * @param {Object} styleInfos The StyleInfo objects * @param {PIE.RootRenderer} parent */ PIE.ImgRenderer = PIE.RendererBase.newRenderer( { shapeZIndex: 6, needsUpdate: function() { var si = this.styleInfos; return this.targetElement.src !== this._lastSrc || si.borderRadiusInfo.changed(); }, isActive: function() { var si = this.styleInfos; return si.borderRadiusInfo.isActive() || si.backgroundInfo.isPngFix(); }, draw: function() { this._lastSrc = src; this.hideActualImg(); var shape = this.getShape( 'img', this.shapeZIndex ), bounds = this.boundsInfo.getBounds(), w = bounds.w, h = bounds.h, borderProps = this.styleInfos.borderInfo.getProps(), borderWidths = borderProps && borderProps.widths, el = this.targetElement, src = el.src, round = Math.round, paddings = this.styleInfos.paddingInfo.getProps(), zero; // In IE6, the BorderRenderer will have hidden the border by moving the border-width to // the padding; therefore we want to pretend the borders have no width so they aren't doubled // when adding in the current padding value below. if( !borderWidths || PIE.ieVersion < 7 ) { zero = PIE.getLength( '0' ); borderWidths = { 't': zero, 'r': zero, 'b': zero, 'l': zero }; } shape.setAttrs( 'path', this.getBoxPath( round( borderWidths['t'].pixels( el ) + paddings[ 't' ].pixels( el ) ), round( borderWidths['r'].pixels( el ) + paddings[ 'r' ].pixels( el ) ), round( borderWidths['b'].pixels( el ) + paddings[ 'b' ].pixels( el ) ), round( borderWidths['l'].pixels( el ) + paddings[ 'l' ].pixels( el ) ), 2 ) ); shape.setFillAttrs( 'type', 'frame', 'src', src, 'position', (w ? 0.5 / w : 0) + ',' + (h ? 0.5 / h : 0) ); shape.setSize( w, h ); }, hideActualImg: function() { this.targetElement.runtimeStyle.filter = 'alpha(opacity=0)'; }, destroy: function() { PIE.RendererBase.destroy.call( this ); this.targetElement.runtimeStyle.filter = ''; } } ); PIE.Element = (function() { var wrappers = {}, lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init', pollCssProp = PIE.CSS_PREFIX + 'poll', trackActiveCssProp = PIE.CSS_PREFIX + 'track-active', trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover', hoverClass = PIE.CLASS_PREFIX + 'hover', activeClass = PIE.CLASS_PREFIX + 'active', focusClass = PIE.CLASS_PREFIX + 'focus', firstChildClass = PIE.CLASS_PREFIX + 'first-child', ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 }, classNameRegExes = {}, dummyArray = []; function addClass( el, className ) { el.className += ' ' + className; } function removeClass( el, className ) { var re = classNameRegExes[ className ] || ( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) ); el.className = el.className.replace( re, '' ); } function delayAddClass( el, className /*, className2*/ ) { var classes = dummyArray.slice.call( arguments, 1 ), i = classes.length; setTimeout( function() { if( el ) { while( i-- ) { addClass( el, classes[ i ] ); } } }, 0 ); } function delayRemoveClass( el, className /*, className2*/ ) { var classes = dummyArray.slice.call( arguments, 1 ), i = classes.length; setTimeout( function() { if( el ) { while( i-- ) { removeClass( el, classes[ i ] ); } } }, 0 ); } function Element( el ) { var me = this, childRenderers, rootRenderer, boundsInfo = new PIE.BoundsInfo( el ), styleInfos, styleInfosArr, initializing, initialized, eventsAttached, eventListeners = [], delayed, destroyed, poll; me.el = el; /** * Initialize PIE for this element. */ function init() { if( !initialized ) { var docEl, bounds, ieDocMode = PIE.ieDocMode, cs = el.currentStyle, lazy = cs.getAttribute( lazyInitCssProp ) === 'true', trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false', trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false'; // Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll poll = cs.getAttribute( pollCssProp ); poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true'; // Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes // after load, but make sure it only gets called the first time through to avoid recursive calls to init(). if( !initializing ) { initializing = 1; el.runtimeStyle.zoom = 1; initFirstChildPseudoClass(); } boundsInfo.lock(); // If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) && ( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) { if( !delayed ) { delayed = 1; PIE.OnScroll.observe( init ); } } else { initialized = 1; delayed = initializing = 0; PIE.OnScroll.unobserve( init ); // Create the style infos and renderers if ( ieDocMode === 9 ) { styleInfos = { backgroundInfo: new PIE.BackgroundStyleInfo( el ), borderImageInfo: new PIE.BorderImageStyleInfo( el ), borderInfo: new PIE.BorderStyleInfo( el ), paddingInfo: new PIE.PaddingStyleInfo( el ) }; styleInfosArr = [ styleInfos.backgroundInfo, styleInfos.borderInfo, styleInfos.borderImageInfo, styleInfos.paddingInfo ]; rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos ); childRenderers = [ new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer ) ]; } else { styleInfos = { backgroundInfo: new PIE.BackgroundStyleInfo( el ), borderInfo: new PIE.BorderStyleInfo( el ), borderImageInfo: new PIE.BorderImageStyleInfo( el ), borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ), boxShadowInfo: new PIE.BoxShadowStyleInfo( el ), paddingInfo: new PIE.PaddingStyleInfo( el ), visibilityInfo: new PIE.VisibilityStyleInfo( el ) }; styleInfosArr = [ styleInfos.backgroundInfo, styleInfos.borderInfo, styleInfos.borderImageInfo, styleInfos.borderRadiusInfo, styleInfos.boxShadowInfo, styleInfos.paddingInfo, styleInfos.visibilityInfo ]; rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos ); childRenderers = [ new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ), //new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ), new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer ) ]; if( el.tagName === 'IMG' ) { childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) ); } rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way? } // Add property change listeners to ancestors if requested initAncestorEventListeners(); // Add to list of polled elements when -pie-poll:true if( poll ) { PIE.Heartbeat.observe( update ); PIE.Heartbeat.run(); } // Trigger rendering update( 0, 1 ); } if( !eventsAttached ) { eventsAttached = 1; if( ieDocMode < 9 ) { addListener( el, 'onmove', handleMoveOrResize ); } addListener( el, 'onresize', handleMoveOrResize ); addListener( el, 'onpropertychange', propChanged ); if( trackHover ) { addListener( el, 'onmouseenter', mouseEntered ); } if( trackHover || trackActive ) { addListener( el, 'onmouseleave', mouseLeft ); } if( trackActive ) { addListener( el, 'onmousedown', mousePressed ); } if( el.tagName in PIE.focusableElements ) { addListener( el, 'onfocus', focused ); addListener( el, 'onblur', blurred ); } PIE.OnResize.observe( handleMoveOrResize ); PIE.OnUnload.observe( removeEventListeners ); } boundsInfo.unlock(); } } /** * Event handler for onmove and onresize events. Invokes update() only if the element's * bounds have previously been calculated, to prevent multiple runs during page load when * the element has no initial CSS3 properties. */ function handleMoveOrResize() { if( boundsInfo && boundsInfo.hasBeenQueried() ) { update(); } } /** * Update position and/or size as necessary. Both move and resize events call * this rather than the updatePos/Size functions because sometimes, particularly * during page load, one will fire but the other won't. */ function update( isPropChange, force ) { if( !destroyed ) { if( initialized ) { lockAll(); var i = 0, len = childRenderers.length, sizeChanged = boundsInfo.sizeChanged(); for( ; i < len; i++ ) { childRenderers[i].prepareUpdate(); } for( i = 0; i < len; i++ ) { if( force || sizeChanged || ( isPropChange && childRenderers[i].needsUpdate() ) ) { childRenderers[i].updateRendering(); } } if( force || sizeChanged || isPropChange || boundsInfo.positionChanged() ) { rootRenderer.updateRendering(); } unlockAll(); } else if( !initializing ) { init(); } } } /** * Handle property changes to trigger update when appropriate. */ function propChanged() { // Some elements like <table> fire onpropertychange events for old-school background properties // ('background', 'bgColor') when runtimeStyle background properties are changed, which // results in an infinite loop; therefore we filter out those property names. Also, 'display' // is ignored because size calculations don't work correctly immediately when its onpropertychange // event fires, and because it will trigger an onresize event anyway. if( initialized && !( event && event.propertyName in ignorePropertyNames ) ) { update( 1 ); } } /** * Handle mouseenter events. Adds a custom class to the element to allow IE6 to add * hover styles to non-link elements, and to trigger a propertychange update. */ function mouseEntered() { //must delay this because the mouseenter event fires before the :hover styles are added. delayAddClass( el, hoverClass ); } /** * Handle mouseleave events */ function mouseLeft() { //must delay this because the mouseleave event fires before the :hover styles are removed. delayRemoveClass( el, hoverClass, activeClass ); } /** * Handle mousedown events. Adds a custom class to the element to allow IE6 to add * active styles to non-link elements, and to trigger a propertychange update. */ function mousePressed() { //must delay this because the mousedown event fires before the :active styles are added. delayAddClass( el, activeClass ); // listen for mouseups on the document; can't just be on the element because the user might // have dragged out of the element while the mouse button was held down PIE.OnMouseup.observe( mouseReleased ); } /** * Handle mouseup events */ function mouseReleased() { //must delay this because the mouseup event fires before the :active styles are removed. delayRemoveClass( el, activeClass ); PIE.OnMouseup.unobserve( mouseReleased ); } /** * Handle focus events. Adds a custom class to the element to trigger a propertychange update. */ function focused() { //must delay this because the focus event fires before the :focus styles are added. delayAddClass( el, focusClass ); } /** * Handle blur events */ function blurred() { //must delay this because the blur event fires before the :focus styles are removed. delayRemoveClass( el, focusClass ); } /** * Handle property changes on ancestors of the element; see initAncestorEventListeners() * which adds these listeners as requested with the -pie-watch-ancestors CSS property. */ function ancestorPropChanged() { var name = event.propertyName; if( name === 'className' || name === 'id' || name.indexOf( 'style.' ) === 0 ) { propChanged(); } } function lockAll() { boundsInfo.lock(); for( var i = styleInfosArr.length; i--; ) { styleInfosArr[i].lock(); } } function unlockAll() { for( var i = styleInfosArr.length; i--; ) { styleInfosArr[i].unlock(); } boundsInfo.unlock(); } function addListener( targetEl, type, handler ) { targetEl.attachEvent( type, handler ); eventListeners.push( [ targetEl, type, handler ] ); } /** * Remove all event listeners from the element and any monitored ancestors. */ function removeEventListeners() { if (eventsAttached) { var i = eventListeners.length, listener; while( i-- ) { listener = eventListeners[ i ]; listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] ); } PIE.OnUnload.unobserve( removeEventListeners ); eventsAttached = 0; eventListeners = []; } } /** * Clean everything up when the behavior is removed from the element, or the element * is manually destroyed. */ function destroy() { if( !destroyed ) { var i, len; removeEventListeners(); destroyed = 1; // destroy any active renderers if( childRenderers ) { for( i = 0, len = childRenderers.length; i < len; i++ ) { childRenderers[i].finalized = 1; childRenderers[i].destroy(); } } rootRenderer.destroy(); // Remove from list of polled elements in IE8 if( poll ) { PIE.Heartbeat.unobserve( update ); } // Stop onresize listening PIE.OnResize.unobserve( update ); // Kill references childRenderers = rootRenderer = boundsInfo = styleInfos = styleInfosArr = el = null; me.el = me = 0; } } /** * If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and * other event listeners to ancestor(s) of the element so we can pick up style changes * based on CSS rules using descendant selectors. */ function initAncestorEventListeners() { var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ), i, a; if( watch ) { watch = parseInt( watch, 10 ); i = 0; a = el.parentNode; while( a && ( watch === 'NaN' || i++ < watch ) ) { addListener( a, 'onpropertychange', ancestorPropChanged ); addListener( a, 'onmouseenter', mouseEntered ); addListener( a, 'onmouseleave', mouseLeft ); addListener( a, 'onmousedown', mousePressed ); if( a.tagName in PIE.focusableElements ) { addListener( a, 'onfocus', focused ); addListener( a, 'onblur', blurred ); } a = a.parentNode; } } } /** * If the target element is a first child, add a pie_first-child class to it. This allows using * the added class as a workaround for the fact that PIE's rendering element breaks the :first-child * pseudo-class selector. */ function initFirstChildPseudoClass() { var tmpEl = el, isFirst = 1; while( tmpEl = tmpEl.previousSibling ) { if( tmpEl.nodeType === 1 ) { isFirst = 0; break; } } if( isFirst ) { addClass( el, firstChildClass ); } } // These methods are all already bound to this instance so there's no need to wrap them // in a closure to maintain the 'this' scope object when calling them. me.init = init; me.destroy = destroy; } Element.getInstance = function( el ) { var id = el[ 'uniqueID' ]; return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) ); }; Element.destroy = function( el ) { var id = el[ 'uniqueID' ], wrapper = wrappers[ id ]; if( wrapper ) { wrapper.destroy(); delete wrappers[ id ]; } }; Element.destroyAll = function() { var els = [], wrapper; if( wrappers ) { for( var w in wrappers ) { if( wrappers.hasOwnProperty( w ) ) { wrapper = wrappers[ w ]; els.push( wrapper.el ); wrapper.destroy(); } } wrappers = {}; } return els; }; return Element; })(); /* * This file exposes the public API for invoking PIE. */ /** * The version number of this PIE build. */ PIE[ 'version' ] = '2.0beta1'; /** * @property supportsVML * True if the current IE browser environment has a functioning VML engine. Should be true * in most IEs, but in rare cases may be false. If false, PIE will exit immediately when * attached to an element (for IE<9) to prevent errors; this property may also be used for * debugging or by external scripts to perform some special action when VML support is absent. * @type {boolean} */ PIE[ 'supportsVML' ] = PIE.supportsVML; /** * Programatically attach PIE to a single element. * @param {Element} el */ PIE[ 'attach' ] = function( el ) { if ( PIE.ieDocMode === 9 || ( PIE.ieDocMode < 9 && PIE.supportsVML ) ) { PIE.Element.getInstance( el ).init(); } }; /** * Programatically detach PIE from a single element. * @param {Element} el */ PIE[ 'detach' ] = function( el ) { PIE.Element.destroy( el ); }; })( window, document );
JavaScript
<?php /** This file is part of KCFinder project * * @desc Folder related functionality * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> browser.initFolders = function() { $('#folders').scroll(function() { browser.hideDialog(); }); $('div.folder > a').unbind(); $('div.folder > a').bind('click', function() { browser.hideDialog(); return false; }); $('div.folder > a > span.brace').unbind(); $('div.folder > a > span.brace').click(function() { if ($(this).hasClass('opened') || $(this).hasClass('closed')) browser.expandDir($(this).parent()); }); $('div.folder > a > span.folder').unbind(); $('div.folder > a > span.folder').click(function() { browser.changeDir($(this).parent()); }); $('div.folder > a > span.folder').rightClick(function(e) { _.unselect(); browser.menuDir($(this).parent(), e); }); if ($.browser.msie && $.browser.version && (parseInt($.browser.version.substr(0, 1)) < 8) ) { var fls = $('div.folder').get(); var body = $('body').get(0); var div; $.each(fls, function(i, folder) { div = document.createElement('div'); div.style.display = 'inline'; div.style.margin = div.style.border = div.style.padding = '0'; div.innerHTML='<table style="border-collapse:collapse;border:0;margin:0;width:0"><tr><td nowrap="nowrap" style="white-space:nowrap;padding:0;border:0">' + $(folder).html() + "</td></tr></table>"; body.appendChild(div); $(folder).css('width', $(div).innerWidth() + 'px'); body.removeChild(div); }); } }; browser.setTreeData = function(data, path) { if (!path) path = ''; else if (path.length && (path.substr(path.length - 1, 1) != '/')) path += '/'; path += data.name; var selector = '#folders a[href="kcdir:/' + _.escapeDirs(path) + '"]'; $(selector).data({ name: data.name, path: path, readable: data.readable, writable: data.writable, removable: data.removable, hasDirs: data.hasDirs }); $(selector + ' span.folder').addClass(data.current ? 'current' : 'regular'); if (data.dirs && data.dirs.length) { $(selector + ' span.brace').addClass('opened'); $.each(data.dirs, function(i, cdir) { browser.setTreeData(cdir, path + '/'); }); } else if (data.hasDirs) $(selector + ' span.brace').addClass('closed'); }; browser.buildTree = function(root, path) { if (!path) path = ""; path += root.name; var html = '<div class="folder"><a href="kcdir:/' + _.escapeDirs(path) + '"><span class="brace">&nbsp;</span><span class="folder">' + _.htmlData(root.name) + '</span></a>'; if (root.dirs) { html += '<div class="folders">'; for (var i = 0; i < root.dirs.length; i++) { cdir = root.dirs[i]; html += browser.buildTree(cdir, path + '/'); } html += '</div>'; } html += '</div>'; return html; }; browser.expandDir = function(dir) { var path = dir.data('path'); if (dir.children('.brace').hasClass('opened')) { dir.parent().children('.folders').hide(500, function() { if (path == browser.dir.substr(0, path.length)) browser.changeDir(dir); }); dir.children('.brace').removeClass('opened'); dir.children('.brace').addClass('closed'); } else { if (dir.parent().children('.folders').get(0)) { dir.parent().children('.folders').show(500); dir.children('.brace').removeClass('closed'); dir.children('.brace').addClass('opened'); } else if (!$('#loadingDirs').get(0)) { dir.parent().append('<div id="loadingDirs">' + this.label("Loading folders...") + '</div>'); $('#loadingDirs').css('display', 'none'); $('#loadingDirs').show(200, function() { $.ajax({ type: 'POST', dataType: 'json', url: browser.baseGetData('expand'), data: {dir:path}, async: false, success: function(data) { $('#loadingDirs').hide(200, function() { $('#loadingDirs').detach(); }); if (browser.check4errors(data)) return; var html = ''; $.each(data.dirs, function(i, cdir) { html += '<div class="folder"><a href="kcdir:/' + _.escapeDirs(path + '/' + cdir.name) + '"><span class="brace">&nbsp;</span><span class="folder">' + _.htmlData(cdir.name) + '</span></a></div>'; }); if (html.length) { dir.parent().append('<div class="folders">' + html + '</div>'); var folders = $(dir.parent().children('.folders').first()); folders.css('display', 'none'); $(folders).show(500); $.each(data.dirs, function(i, cdir) { browser.setTreeData(cdir, path); }); } if (data.dirs.length) { dir.children('.brace').removeClass('closed'); dir.children('.brace').addClass('opened'); } else { dir.children('.brace').removeClass('opened'); dir.children('.brace').removeClass('closed'); } browser.initFolders(); browser.initDropUpload(); }, error: function() { $('#loadingDirs').detach(); browser.alert(browser.label("Unknown error.")); } }); }); } } }; browser.changeDir = function(dir) { if (dir.children('span.folder').hasClass('regular')) { $('div.folder > a > span.folder').removeClass('current'); $('div.folder > a > span.folder').removeClass('regular'); $('div.folder > a > span.folder').addClass('regular'); dir.children('span.folder').removeClass('regular'); dir.children('span.folder').addClass('current'); $('#files').html(browser.label("Loading files...")); $.ajax({ type: 'POST', dataType: 'json', url: browser.baseGetData('chDir'), data: {dir:dir.data('path')}, async: false, success: function(data) { if (browser.check4errors(data)) return; browser.files = data.files; browser.orderFiles(); browser.dir = dir.data('path'); browser.dirWritable = data.dirWritable; var title = "KCFinder: /" + browser.dir; document.title = title; if (browser.opener.TinyMCE) tinyMCEPopup.editor.windowManager.setTitle(window, title); browser.statusDir(); }, error: function() { $('#files').html(browser.label("Unknown error.")); } }); } }; browser.statusDir = function() { for (var i = 0, size = 0; i < this.files.length; i++) size += parseInt(this.files[i].size); size = this.humanSize(size); $('#fileinfo').html(this.files.length + ' ' + this.label("files") + ' (' + size + ')'); }; browser.menuDir = function(dir, e) { var data = dir.data(); var html = '<div class="menu">'; if (this.clipboard && this.clipboard.length) { if (this.access.files.copy) html += '<a href="kcact:cpcbd"' + (!data.writable ? ' class="denied"' : '') + '>' + this.label("Copy {count} files", {count: this.clipboard.length}) + '</a>'; if (this.access.files.move) html += '<a href="kcact:mvcbd"' + (!data.writable ? ' class="denied"' : '') + '>' + this.label("Move {count} files", {count: this.clipboard.length}) + '</a>'; if (this.access.files.copy || this.access.files.move) html += '<div class="delimiter"></div>'; } html += '<a href="kcact:refresh">' + this.label("Refresh") + '</a>'; if (this.support.zip) html+= '<div class="delimiter"></div>' + '<a href="kcact:download">' + this.label("Download") + '</a>'; if (this.access.dirs.create || this.access.dirs.rename || this.access.dirs['delete']) html += '<div class="delimiter"></div>'; if (this.access.dirs.create) html += '<a href="kcact:mkdir"' + (!data.writable ? ' class="denied"' : '') + '>' + this.label("New Subfolder...") + '</a>'; if (this.access.dirs.rename) html += '<a href="kcact:mvdir"' + (!data.removable ? ' class="denied"' : '') + '>' + this.label("Rename...") + '</a>'; if (this.access.dirs['delete']) html += '<a href="kcact:rmdir"' + (!data.removable ? ' class="denied"' : '') + '>' + this.label("Delete") + '</a>'; html += '</div>'; $('#dialog').html(html); this.showMenu(e); $('div.folder > a > span.folder').removeClass('context'); if (dir.children('span.folder').hasClass('regular')) dir.children('span.folder').addClass('context'); if (this.clipboard && this.clipboard.length && data.writable) { $('.menu a[href="kcact:cpcbd"]').click(function() { browser.hideDialog(); browser.copyClipboard(data.path); return false; }); $('.menu a[href="kcact:mvcbd"]').click(function() { browser.hideDialog(); browser.moveClipboard(data.path); return false; }); } $('.menu a[href="kcact:refresh"]').click(function() { browser.hideDialog(); browser.refreshDir(dir); return false; }); $('.menu a[href="kcact:download"]').click(function() { browser.hideDialog(); browser.post(browser.baseGetData('downloadDir'), {dir:data.path}); return false; }); $('.menu a[href="kcact:mkdir"]').click(function(e) { if (!data.writable) return false; browser.hideDialog(); browser.fileNameDialog( e, {dir: data.path}, 'newDir', '', browser.baseGetData('newDir'), { title: "New folder name:", errEmpty: "Please enter new folder name.", errSlash: "Unallowable characters in folder name.", errDot: "Folder name shouldn't begins with '.'" }, function() { browser.refreshDir(dir); browser.initDropUpload(); if (!data.hasDirs) { dir.data('hasDirs', true); dir.children('span.brace').addClass('closed'); } } ); return false; }); $('.menu a[href="kcact:mvdir"]').click(function(e) { if (!data.removable) return false; browser.hideDialog(); browser.fileNameDialog( e, {dir: data.path}, 'newName', data.name, browser.baseGetData('renameDir'), { title: "New folder name:", errEmpty: "Please enter new folder name.", errSlash: "Unallowable characters in folder name.", errDot: "Folder name shouldn't begins with '.'" }, function(dt) { if (!dt.name) { browser.alert(browser.label("Unknown error.")); return; } var currentDir = (data.path == browser.dir); dir.children('span.folder').html(_.htmlData(dt.name)); dir.data('name', dt.name); dir.data('path', _.dirname(data.path) + '/' + dt.name); if (currentDir) browser.dir = dir.data('path'); browser.initDropUpload(); }, true ); return false; }); $('.menu a[href="kcact:rmdir"]').click(function() { if (!data.removable) return false; browser.hideDialog(); browser.confirm( "Are you sure you want to delete this folder and all its content?", function(callBack) { $.ajax({ type: 'POST', dataType: 'json', url: browser.baseGetData('deleteDir'), data: {dir: data.path}, async: false, success: function(data) { if (callBack) callBack(); if (browser.check4errors(data)) return; dir.parent().hide(500, function() { var folders = dir.parent().parent(); var pDir = folders.parent().children('a').first(); dir.parent().detach(); if (!folders.children('div.folder').get(0)) { pDir.children('span.brace').first().removeClass('opened'); pDir.children('span.brace').first().removeClass('closed'); pDir.parent().children('.folders').detach(); pDir.data('hasDirs', false); } if (pDir.data('path') == browser.dir.substr(0, pDir.data('path').length)) browser.changeDir(pDir); browser.initDropUpload(); }); }, error: function() { if (callBack) callBack(); browser.alert(browser.label("Unknown error.")); } }); } ); return false; }); }; browser.refreshDir = function(dir) { var path = dir.data('path'); if (dir.children('.brace').hasClass('opened') || dir.children('.brace').hasClass('closed')) { dir.children('.brace').removeClass('opened'); dir.children('.brace').addClass('closed'); } dir.parent().children('.folders').first().detach(); if (path == browser.dir.substr(0, path.length)) browser.changeDir(dir); browser.expandDir(dir); return true; };
JavaScript
<?php /** This file is part of KCFinder project * * @desc File related functionality * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> browser.initFiles = function() { $(document).unbind('keydown'); $(document).keydown(function(e) { return !browser.selectAll(e); }); $('#files').unbind(); $('#files').scroll(function() { browser.hideDialog(); }); $('.file').unbind(); $('.file').click(function(e) { _.unselect(); browser.selectFile($(this), e); }); $('.file').rightClick(function(e) { _.unselect(); browser.menuFile($(this), e); }); $('.file').dblclick(function() { _.unselect(); browser.returnFile($(this)); }); $('.file').mouseup(function() { _.unselect(); }); $('.file').mouseout(function() { _.unselect(); }); $.each(this.shows, function(i, val) { var display = (_.kuki.get('show' + val) == 'off') ? 'none' : 'block'; $('#files .file div.' + val).css('display', display); }); this.statusDir(); }; browser.showFiles = function(callBack, selected) { this.fadeFiles(); setTimeout(function() { var html = ''; $.each(browser.files, function(i, file) { var stamp = []; $.each(file, function(key, val) { stamp[stamp.length] = key + "|" + val; }); stamp = _.md5(stamp.join('|')); if (_.kuki.get('view') == 'list') { if (!i) html += '<table summary="list">'; var icon = _.getFileExtension(file.name); if (file.thumb) icon = '.image'; else if (!icon.length || !file.smallIcon) icon = '.'; icon = 'themes/' + browser.theme + '/img/files/small/' + icon + '.png'; html += '<tr class="file">' + '<td class="name" style="background-image:url(' + icon + ')">' + _.htmlData(file.name) + '</td>' + '<td class="time">' + file.date + '</td>' + '<td class="size">' + browser.humanSize(file.size) + '</td>' + '</tr>'; if (i == browser.files.length - 1) html += '</table>'; } else { if (file.thumb) var icon = browser.baseGetData('thumb') + '&file=' + encodeURIComponent(file.name) + '&dir=' + encodeURIComponent(browser.dir) + '&stamp=' + stamp; else if (file.smallThumb) { var icon = browser.uploadURL + '/' + browser.dir + '/' + file.name; icon = _.escapeDirs(icon).replace(/\'/g, "%27"); } else { var icon = file.bigIcon ? _.getFileExtension(file.name) : '.'; if (!icon.length) icon = '.'; icon = 'themes/' + browser.theme + '/img/files/big/' + icon + '.png'; } html += '<div class="file">' + '<div class="thumb" style="background-image:url(\'' + icon + '\')" ></div>' + '<div class="name">' + _.htmlData(file.name) + '</div>' + '<div class="time">' + file.date + '</div>' + '<div class="size">' + browser.humanSize(file.size) + '</div>' + '</div>'; } }); $('#files').html('<div>' + html + '<div>'); $.each(browser.files, function(i, file) { var item = $('#files .file').get(i); $(item).data(file); if (_.inArray(file.name, selected) || ((typeof selected != 'undefined') && !selected.push && (file.name == selected)) ) $(item).addClass('selected'); }); $('#files > div').css({opacity:'', filter:''}); if (callBack) callBack(); browser.initFiles(); }, 200); }; browser.selectFile = function(file, e) { if (e.ctrlKey || e.metaKey) { if (file.hasClass('selected')) file.removeClass('selected'); else file.addClass('selected'); var files = $('.file.selected').get(); var size = 0; if (!files.length) this.statusDir(); else { $.each(files, function(i, cfile) { size += parseInt($(cfile).data('size')); }); size = this.humanSize(size); if (files.length > 1) $('#fileinfo').html(files.length + ' ' + this.label("selected files") + ' (' + size + ')'); else { var data = $(files[0]).data(); $('#fileinfo').html(data.name + ' (' + this.humanSize(data.size) + ', ' + data.date + ')'); } } } else { var data = file.data(); $('.file').removeClass('selected'); file.addClass('selected'); $('#fileinfo').html(data.name + ' (' + this.humanSize(data.size) + ', ' + data.date + ')'); } }; browser.selectAll = function(e) { if ((!e.ctrlKey && !e.metaKey) || ((e.keyCode != 65) && (e.keyCode != 97))) return false; var files = $('.file').get(); if (files.length) { var size = 0; $.each(files, function(i, file) { if (!$(file).hasClass('selected')) $(file).addClass('selected'); size += parseInt($(file).data('size')); }); size = this.humanSize(size); $('#fileinfo').html(files.length + ' ' + this.label("selected files") + ' (' + size + ')'); } return true; }; browser.returnFile = function(file) { var fileURL = file.substr ? file : browser.uploadURL + '/' + browser.dir + '/' + file.data('name'); fileURL = _.escapeDirs(fileURL); if (this.opener.CKEditor) { this.opener.CKEditor.object.tools.callFunction(this.opener.CKEditor.funcNum, fileURL, ''); window.close(); } else if (this.opener.FCKeditor) { window.opener.SetUrl(fileURL) ; window.close() ; } else if (this.opener.TinyMCE) { var win = tinyMCEPopup.getWindowArg('window'); win.document.getElementById(tinyMCEPopup.getWindowArg('input')).value = fileURL; if (win.getImageData) win.getImageData(); if (typeof(win.ImageDialog) != "undefined") { if (win.ImageDialog.getImageData) win.ImageDialog.getImageData(); if (win.ImageDialog.showPreviewImage) win.ImageDialog.showPreviewImage(fileURL); } tinyMCEPopup.close(); } else if (this.opener.callBack) { if (window.opener && window.opener.KCFinder) { this.opener.callBack(fileURL); window.close(); } if (window.parent && window.parent.KCFinder) { var button = $('#toolbar a[href="kcact:maximize"]'); if (button.hasClass('selected')) this.maximize(button); this.opener.callBack(fileURL); } } else if (this.opener.callBackMultiple) { if (window.opener && window.opener.KCFinder) { this.opener.callBackMultiple([fileURL]); window.close(); } if (window.parent && window.parent.KCFinder) { var button = $('#toolbar a[href="kcact:maximize"]'); if (button.hasClass('selected')) this.maximize(button); this.opener.callBackMultiple([fileURL]); } } }; browser.returnFiles = function(files) { if (this.opener.callBackMultiple && files.length) { var rfiles = []; $.each(files, function(i, file) { rfiles[i] = browser.uploadURL + '/' + browser.dir + '/' + $(file).data('name'); rfiles[i] = _.escapeDirs(rfiles[i]); }); this.opener.callBackMultiple(rfiles); if (window.opener) window.close() } }; browser.returnThumbnails = function(files) { if (this.opener.callBackMultiple) { var rfiles = []; var j = 0; $.each(files, function(i, file) { if ($(file).data('thumb')) { rfiles[j] = browser.thumbsURL + '/' + browser.dir + '/' + $(file).data('name'); rfiles[j] = _.escapeDirs(rfiles[j++]); } }); this.opener.callBackMultiple(rfiles); if (window.opener) window.close() } }; browser.menuFile = function(file, e) { var data = file.data(); var path = this.dir + '/' + data.name; var files = $('.file.selected').get(); var html = ''; if (file.hasClass('selected') && files.length && (files.length > 1)) { var thumb = false; var notWritable = 0; var cdata; $.each(files, function(i, cfile) { cdata = $(cfile).data(); if (cdata.thumb) thumb = true; if (!data.writable) notWritable++; }); if (this.opener.callBackMultiple) { html += '<a href="kcact:pick">' + this.label("Select") + '</a>'; if (thumb) html += '<a href="kcact:pick_thumb">' + this.label("Select Thumbnails") + '</a>'; } if (data.thumb || data.smallThumb || this.support.zip) { html += (html.length ? '<div class="delimiter"></div>' : ''); if (data.thumb || data.smallThumb) html +='<a href="kcact:view">' + this.label("View") + '</a>'; if (this.support.zip) html += (html.length ? '<div class="delimiter"></div>' : '') + '<a href="kcact:download">' + this.label("Download") + '</a>'; } if (this.access.files.copy || this.access.files.move) html += (html.length ? '<div class="delimiter"></div>' : '') + '<a href="kcact:clpbrdadd">' + this.label("Add to Clipboard") + '</a>'; if (this.access.files['delete']) html += (html.length ? '<div class="delimiter"></div>' : '') + '<a href="kcact:rm"' + ((notWritable == files.length) ? ' class="denied"' : '') + '>' + this.label("Delete") + '</a>'; if (html.length) { html = '<div class="menu">' + html + '</div>'; $('#dialog').html(html); this.showMenu(e); } else return; $('.menu a[href="kcact:pick"]').click(function() { browser.returnFiles(files); browser.hideDialog(); return false; }); $('.menu a[href="kcact:pick_thumb"]').click(function() { browser.returnThumbnails(files); browser.hideDialog(); return false; }); $('.menu a[href="kcact:download"]').click(function() { browser.hideDialog(); var pfiles = []; $.each(files, function(i, cfile) { pfiles[i] = $(cfile).data('name'); }); browser.post(browser.baseGetData('downloadSelected'), {dir:browser.dir, files:pfiles}); return false; }); $('.menu a[href="kcact:clpbrdadd"]').click(function() { browser.hideDialog(); var msg = ''; $.each(files, function(i, cfile) { var cdata = $(cfile).data(); var failed = false; for (i = 0; i < browser.clipboard.length; i++) if ((browser.clipboard[i].name == cdata.name) && (browser.clipboard[i].dir == browser.dir) ) { failed = true msg += cdata.name + ": " + browser.label("This file is already added to the Clipboard.") + "\n"; break; } if (!failed) { cdata.dir = browser.dir; browser.clipboard[browser.clipboard.length] = cdata; } }); browser.initClipboard(); if (msg.length) browser.alert(msg.substr(0, msg.length - 1)); return false; }); $('.menu a[href="kcact:rm"]').click(function() { if ($(this).hasClass('denied')) return false; browser.hideDialog(); var failed = 0; var dfiles = []; $.each(files, function(i, cfile) { var cdata = $(cfile).data(); if (!cdata.writable) failed++; else dfiles[dfiles.length] = browser.dir + "/" + cdata.name; }); if (failed == files.length) { browser.alert(browser.label("The selected files are not removable.")); return false; } var go = function(callBack) { browser.fadeFiles(); $.ajax({ type: 'POST', dataType: 'json', url: browser.baseGetData('rm_cbd'), data: {files:dfiles}, async: false, success: function(data) { if (callBack) callBack(); browser.check4errors(data); browser.refresh(); }, error: function() { if (callBack) callBack(); $('#files > div').css({ opacity: '', filter: '' }); browser.alert(browser.label("Unknown error.")); } }); }; if (failed) browser.confirm( browser.label("{count} selected files are not removable. Do you want to delete the rest?", {count:failed}), go ) else browser.confirm( browser.label("Are you sure you want to delete all selected files?"), go ); return false; }); } else { html += '<div class="menu">'; $('.file').removeClass('selected'); file.addClass('selected'); $('#fileinfo').html(data.name + ' (' + this.humanSize(data.size) + ', ' + data.date + ')'); if (this.opener.callBack || this.opener.callBackMultiple) { html += '<a href="kcact:pick">' + this.label("Select") + '</a>'; if (data.thumb) html += '<a href="kcact:pick_thumb">' + this.label("Select Thumbnail") + '</a>'; html += '<div class="delimiter"></div>'; } if (data.thumb || data.smallThumb) html +='<a href="kcact:view">' + this.label("View") + '</a>'; html += '<a href="kcact:download">' + this.label("Download") + '</a>'; if (this.access.files.copy || this.access.files.move) html += '<div class="delimiter"></div>' + '<a href="kcact:clpbrdadd">' + this.label("Add to Clipboard") + '</a>'; if (this.access.files.rename || this.access.files['delete']) html += '<div class="delimiter"></div>'; if (this.access.files.rename) html += '<a href="kcact:mv"' + (!data.writable ? ' class="denied"' : '') + '>' + this.label("Rename...") + '</a>'; if (this.access.files['delete']) html += '<a href="kcact:rm"' + (!data.writable ? ' class="denied"' : '') + '>' + this.label("Delete") + '</a>'; html += '</div>'; $('#dialog').html(html); this.showMenu(e); $('.menu a[href="kcact:pick"]').click(function() { browser.returnFile(file); browser.hideDialog(); return false; }); $('.menu a[href="kcact:pick_thumb"]').click(function() { var path = browser.thumbsURL + '/' + browser.dir + '/' + data.name; browser.returnFile(path); browser.hideDialog(); return false; }); $('.menu a[href="kcact:download"]').click(function() { var html = '<form id="downloadForm" method="post" action="' + browser.baseGetData('download') + '">' + '<input type="hidden" name="dir" />' + '<input type="hidden" name="file" />' + '</form>'; $('#dialog').html(html); $('#downloadForm input').get(0).value = browser.dir; $('#downloadForm input').get(1).value = data.name; $('#downloadForm').submit(); return false; }); $('.menu a[href="kcact:clpbrdadd"]').click(function() { for (i = 0; i < browser.clipboard.length; i++) if ((browser.clipboard[i].name == data.name) && (browser.clipboard[i].dir == browser.dir) ) { browser.hideDialog(); browser.alert(browser.label("This file is already added to the Clipboard.")); return false; } var cdata = data; cdata.dir = browser.dir; browser.clipboard[browser.clipboard.length] = cdata; browser.initClipboard(); browser.hideDialog(); return false; }); $('.menu a[href="kcact:mv"]').click(function(e) { if (!data.writable) return false; browser.fileNameDialog( e, {dir: browser.dir, file: data.name}, 'newName', data.name, browser.baseGetData('rename'), { title: "New file name:", errEmpty: "Please enter new file name.", errSlash: "Unallowable characters in file name.", errDot: "File name shouldn't begins with '.'" }, function() { browser.refresh(); } ); return false; }); $('.menu a[href="kcact:rm"]').click(function() { if (!data.writable) return false; browser.hideDialog(); browser.confirm(browser.label("Are you sure you want to delete this file?"), function(callBack) { $.ajax({ type: 'POST', dataType: 'json', url: browser.baseGetData('delete'), data: {dir:browser.dir, file:data.name}, async: false, success: function(data) { if (callBack) callBack(); browser.clearClipboard(); if (browser.check4errors(data)) return; browser.refresh(); }, error: function() { if (callBack) callBack(); browser.alert(browser.label("Unknown error.")); } }); } ); return false; }); } $('.menu a[href="kcact:view"]').click(function() { browser.hideDialog(); var ts = new Date().getTime(); var showImage = function(data) { url = _.escapeDirs(browser.uploadURL + '/' + browser.dir + '/' + data.name) + '?ts=' + ts, $('#loading').html(browser.label("Loading image...")); $('#loading').css('display', 'inline'); var img = new Image(); img.src = url; img.onerror = function() { browser.lock = false; $('#loading').css('display', 'none'); browser.alert(browser.label("Unknown error.")); $(document).unbind('keydown'); $(document).keydown(function(e) { return !browser.selectAll(e); }); browser.refresh(); }; var onImgLoad = function() { browser.lock = false; $('#files .file').each(function() { if ($(this).data('name') == data.name) browser.ssImage = this; }); $('#loading').css('display', 'none'); $('#dialog').html('<div class="slideshow"><img /></div>'); $('#dialog img').attr({ src: url, title: data.name }).fadeIn('fast', function() { var o_w = $('#dialog').outerWidth(); var o_h = $('#dialog').outerHeight(); var f_w = $(window).width() - 30; var f_h = $(window).height() - 30; if ((o_w > f_w) || (o_h > f_h)) { if ((f_w / f_h) > (o_w / o_h)) f_w = parseInt((o_w * f_h) / o_h); else if ((f_w / f_h) < (o_w / o_h)) f_h = parseInt((o_h * f_w) / o_w); $('#dialog img').attr({ width: f_w, height: f_h }); } $('#dialog').unbind('click'); $('#dialog').click(function(e) { browser.hideDialog(); $(document).unbind('keydown'); $(document).keydown(function(e) { return !browser.selectAll(e); }); if (browser.ssImage) { browser.selectFile($(browser.ssImage), e); } }); browser.showDialog(); var images = []; $.each(browser.files, function(i, file) { if (file.thumb || file.smallThumb) images[images.length] = file; }); if (images.length) $.each(images, function(i, image) { if (image.name == data.name) { $(document).unbind('keydown'); $(document).keydown(function(e) { if (images.length > 1) { if (!browser.lock && (e.keyCode == 37)) { var nimg = i ? images[i - 1] : images[images.length - 1]; browser.lock = true; showImage(nimg); } if (!browser.lock && (e.keyCode == 39)) { var nimg = (i >= images.length - 1) ? images[0] : images[i + 1]; browser.lock = true; showImage(nimg); } } if (e.keyCode == 27) { browser.hideDialog(); $(document).unbind('keydown'); $(document).keydown(function(e) { return !browser.selectAll(e); }); } }); } }); }); }; if (img.complete) onImgLoad(); else img.onload = onImgLoad; }; showImage(data); return false; }); };
JavaScript
<?php /** This file is part of KCFinder project * * @desc Toolbar functionality * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> browser.initToolbar = function() { $('#toolbar a').click(function() { browser.hideDialog(); }); if (!_.kuki.isSet('displaySettings')) _.kuki.set('displaySettings', 'off'); if (_.kuki.get('displaySettings') == 'on') { $('#toolbar a[href="kcact:settings"]').addClass('selected'); $('#settings').css('display', 'block'); browser.resize(); } $('#toolbar a[href="kcact:settings"]').click(function () { if ($('#settings').css('display') == 'none') { $(this).addClass('selected'); _.kuki.set('displaySettings', 'on'); $('#settings').css('display', 'block'); browser.fixFilesHeight(); } else { $(this).removeClass('selected'); _.kuki.set('displaySettings', 'off'); $('#settings').css('display', 'none'); browser.fixFilesHeight(); } return false; }); $('#toolbar a[href="kcact:refresh"]').click(function() { browser.refresh(); return false; }); if (window.opener || this.opener.TinyMCE || $('iframe', window.parent.document).get(0)) $('#toolbar a[href="kcact:maximize"]').click(function() { browser.maximize(this); return false; }); else $('#toolbar a[href="kcact:maximize"]').css('display', 'none'); $('#toolbar a[href="kcact:about"]').click(function() { var html = '<div class="box about">' + '<div class="head"><a href="http://kcfinder.sunhater.com" target="_blank">KCFinder</a> ' + browser.version + '</div>'; if (browser.support.check4Update) html += '<div id="checkver"><span class="loading"><span>' + browser.label("Checking for new version...") + '</span></span></div>'; html += '<div>' + browser.label("Licenses:") + ' GPLv2 & LGPLv2</div>' + '<div>Copyright &copy;2010, 2011 Pavel Tzonkov</div>' + '<button>' + browser.label("OK") + '</button>' + '</div>'; $('#dialog').html(html); $('#dialog').data('title', browser.label("About")); browser.showDialog(); var close = function() { browser.hideDialog(); browser.unshadow(); } $('#dialog button').click(close); var span = $('#checkver > span'); setTimeout(function() { $.ajax({ dataType: 'json', url: browser.baseGetData('check4Update'), async: true, success: function(data) { if (!$('#dialog').html().length) return; span.removeClass('loading'); if (!data.version) { span.html(browser.label("Unable to connect!")); browser.showDialog(); return; } if (browser.version < data.version) span.html('<a href="http://kcfinder.sunhater.com/download" target="_blank">' + browser.label("Download version {version} now!", {version: data.version}) + '</a>'); else span.html(browser.label("KCFinder is up to date!")); browser.showDialog(); }, error: function() { if (!$('#dialog').html().length) return; span.removeClass('loading'); span.html(browser.label("Unable to connect!")); browser.showDialog(); } }); }, 1000); $('#dialog').unbind(); return false; }); this.initUploadButton(); }; browser.initUploadButton = function() { var btn = $('#toolbar a[href="kcact:upload"]'); if (!this.access.files.upload) { btn.css('display', 'none'); return; } var top = btn.get(0).offsetTop; var width = btn.outerWidth(); var height = btn.outerHeight(); $('#toolbar').prepend('<div id="upload" style="top:' + top + 'px;width:' + width + 'px;height:' + height + 'px">' + '<form enctype="multipart/form-data" method="post" target="uploadResponse" action="' + browser.baseGetData('upload') + '">' + '<input type="file" name="upload[]" onchange="browser.uploadFile(this.form)" style="height:' + height + 'px" multiple="multiple" />' + '<input type="hidden" name="dir" value="" />' + '</form>' + '</div>'); $('#upload input').css('margin-left', "-" + ($('#upload input').outerWidth() - width) + 'px'); $('#upload').mouseover(function() { $('#toolbar a[href="kcact:upload"]').addClass('hover'); }); $('#upload').mouseout(function() { $('#toolbar a[href="kcact:upload"]').removeClass('hover'); }); }; browser.uploadFile = function(form) { if (!this.dirWritable) { browser.alert(this.label("Cannot write to upload folder.")); $('#upload').detach(); browser.initUploadButton(); return; } form.elements[1].value = browser.dir; $('<iframe id="uploadResponse" name="uploadResponse" src="javascript:;"></iframe>').prependTo(document.body); $('#loading').html(this.label("Uploading file...")); $('#loading').css('display', 'inline'); form.submit(); $('#uploadResponse').load(function() { var response = $(this).contents().find('body').html(); $('#loading').css('display', 'none'); response = response.split("\n"); var selected = [], errors = []; $.each(response, function(i, row) { if (row.substr(0, 1) == '/') selected[selected.length] = row.substr(1, row.length - 1) else errors[errors.length] = row; }); if (errors.length) browser.alert(errors.join("\n")); if (!selected.length) selected = null browser.refresh(selected); $('#upload').detach(); setTimeout(function() { $('#uploadResponse').detach(); }, 1); browser.initUploadButton(); }); }; browser.maximize = function(button) { if (window.opener) { window.moveTo(0, 0); width = screen.availWidth; height = screen.availHeight; if ($.browser.opera) height -= 50; window.resizeTo(width, height); } else if (browser.opener.TinyMCE) { var win, ifr, id; $('iframe', window.parent.document).each(function() { if (/^mce_\d+_ifr$/.test($(this).attr('id'))) { id = parseInt($(this).attr('id').replace(/^mce_(\d+)_ifr$/, "$1")); win = $('#mce_' + id, window.parent.document); ifr = $('#mce_' + id + '_ifr', window.parent.document); } }); if ($(button).hasClass('selected')) { $(button).removeClass('selected'); win.css({ left: browser.maximizeMCE.left + 'px', top: browser.maximizeMCE.top + 'px', width: browser.maximizeMCE.width + 'px', height: browser.maximizeMCE.height + 'px' }); ifr.css({ width: browser.maximizeMCE.width - browser.maximizeMCE.Hspace + 'px', height: browser.maximizeMCE.height - browser.maximizeMCE.Vspace + 'px' }); } else { $(button).addClass('selected') browser.maximizeMCE = { width: _.nopx(win.css('width')), height: _.nopx(win.css('height')), left: win.position().left, top: win.position().top, Hspace: _.nopx(win.css('width')) - _.nopx(ifr.css('width')), Vspace: _.nopx(win.css('height')) - _.nopx(ifr.css('height')) }; var width = $(window.parent).width(); var height = $(window.parent).height(); win.css({ left: $(window.parent).scrollLeft() + 'px', top: $(window.parent).scrollTop() + 'px', width: width + 'px', height: height + 'px' }); ifr.css({ width: width - browser.maximizeMCE.Hspace + 'px', height: height - browser.maximizeMCE.Vspace + 'px' }); } } else if ($('iframe', window.parent.document).get(0)) { var ifrm = $('iframe[name="' + window.name + '"]', window.parent.document); var parent = ifrm.parent(); var width, height; if ($(button).hasClass('selected')) { $(button).removeClass('selected'); if (browser.maximizeThread) { clearInterval(browser.maximizeThread); browser.maximizeThread = null; } if (browser.maximizeW) browser.maximizeW = null; if (browser.maximizeH) browser.maximizeH = null; $.each($('*', window.parent.document).get(), function(i, e) { e.style.display = browser.maximizeDisplay[i]; }); ifrm.css({ display: browser.maximizeCSS.display, position: browser.maximizeCSS.position, left: browser.maximizeCSS.left, top: browser.maximizeCSS.top, width: browser.maximizeCSS.width, height: browser.maximizeCSS.height }); $(window.parent).scrollLeft(browser.maximizeLest); $(window.parent).scrollTop(browser.maximizeTop); } else { $(button).addClass('selected'); browser.maximizeCSS = { display: ifrm.css('display'), position: ifrm.css('position'), left: ifrm.css('left'), top: ifrm.css('top'), width: ifrm.outerWidth() + 'px', height: ifrm.outerHeight() + 'px' }; browser.maximizeTop = $(window.parent).scrollTop(); browser.maximizeLeft = $(window.parent).scrollLeft(); browser.maximizeDisplay = []; $.each($('*', window.parent.document).get(), function(i, e) { browser.maximizeDisplay[i] = $(e).css('display'); $(e).css('display', 'none'); }); ifrm.css('display', 'block'); ifrm.parents().css('display', 'block'); var resize = function() { width = $(window.parent).width(); height = $(window.parent).height(); if (!browser.maximizeW || (browser.maximizeW != width) || !browser.maximizeH || (browser.maximizeH != height) ) { browser.maximizeW = width; browser.maximizeH = height; ifrm.css({ width: width + 'px', height: height + 'px' }); browser.resize(); } } ifrm.css('position', 'absolute'); if ((ifrm.offset().left == ifrm.position().left) && (ifrm.offset().top == ifrm.position().top) ) ifrm.css({left: '0', top: '0'}); else ifrm.css({ left: - ifrm.offset().left + 'px', top: - ifrm.offset().top + 'px' }); resize(); browser.maximizeThread = setInterval(resize, 250); } } }; browser.refresh = function(selected) { this.fadeFiles(); $.ajax({ type: 'POST', dataType: 'json', url: browser.baseGetData('chDir'), data: {dir:browser.dir}, async: false, success: function(data) { if (browser.check4errors(data)) return; browser.dirWritable = data.dirWritable; browser.files = data.files ? data.files : []; browser.orderFiles(null, selected); browser.statusDir(); }, error: function() { $('#files > div').css({opacity:'', filter:''}); $('#files').html(browser.label("Unknown error.")); } }); };
JavaScript
<?php /** This file is part of KCFinder project * * @desc Clipboard functionality * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> browser.initClipboard = function() { if (!this.clipboard || !this.clipboard.length) return; var size = 0; $.each(this.clipboard, function(i, val) { size += parseInt(val.size); }); size = this.humanSize(size); $('#clipboard').html('<div title="' + this.label("Clipboard") + ' (' + this.clipboard.length + ' ' + this.label("files") + ', ' + size + ')" onclick="browser.openClipboard()"></div>'); var resize = function() { $('#clipboard').css({ left: $(window).width() - $('#clipboard').outerWidth() + 'px', top: $(window).height() - $('#clipboard').outerHeight() + 'px' }); }; resize(); $('#clipboard').css('display', 'block'); $(window).unbind(); $(window).resize(function() { browser.resize(); resize(); }); }; browser.openClipboard = function() { if (!this.clipboard || !this.clipboard.length) return; if ($('.menu a[href="kcact:cpcbd"]').html()) { $('#clipboard').removeClass('selected'); this.hideDialog(); return; } var html = '<div class="menu"><div class="list">'; $.each(this.clipboard, function(i, val) { icon = _.getFileExtension(val.name); if (val.thumb) icon = '.image'; else if (!val.smallIcon || !icon.length) icon = '.'; var icon = 'themes/' + browser.theme + '/img/files/small/' + icon + '.png'; html += '<a style="background-image:url(' + _.escapeDirs(icon) + ')" title="' + browser.label("Click to remove from the Clipboard") + '" onclick="browser.removeFromClipboard(' + i + ')">' + _.htmlData(_.basename(val.name)) + '</a>'; }); html += '</div><div class="delimiter"></div>'; if (this.support.zip) html+= '<a href="kcact:download">' + this.label("Download files") + '</a>'; if (this.access.files.copy || this.access.files.move || this.access.files['delete']) html += '<div class="delimiter"></div>'; if (this.access.files.copy) html += '<a href="kcact:cpcbd"' + (!browser.dirWritable ? ' class="denied"' : '') + '>' + this.label("Copy files here") + '</a>'; if (this.access.files.move) html += '<a href="kcact:mvcbd"' + (!browser.dirWritable ? ' class="denied"' : '') + '>' + this.label("Move files here") + '</a>'; if (this.access.files['delete']) html += '<a href="kcact:rmcbd">' + this.label("Delete files") + '</a>'; html += '<div class="delimiter"></div>' + '<a href="kcact:clrcbd">' + this.label("Clear the Clipboard") + '</a>' + '</div>'; setTimeout(function() { $('#clipboard').addClass('selected'); $('#dialog').html(html); $('.menu a[href="kcact:download"]').click(function() { browser.hideDialog(); browser.downloadClipboard(); return false; }); $('.menu a[href="kcact:cpcbd"]').click(function() { if (!browser.dirWritable) return false; browser.hideDialog(); browser.copyClipboard(browser.dir); return false; }); $('.menu a[href="kcact:mvcbd"]').click(function() { if (!browser.dirWritable) return false; browser.hideDialog(); browser.moveClipboard(browser.dir); return false; }); $('.menu a[href="kcact:rmcbd"]').click(function() { browser.hideDialog(); browser.confirm( browser.label("Are you sure you want to delete all files in the Clipboard?"), function(callBack) { if (callBack) callBack(); browser.deleteClipboard(); } ); return false; }); $('.menu a[href="kcact:clrcbd"]').click(function() { browser.hideDialog(); browser.clearClipboard(); return false; }); var left = $(window).width() - $('#dialog').outerWidth(); var top = $(window).height() - $('#dialog').outerHeight() - $('#clipboard').outerHeight(); var lheight = top + _.outerTopSpace('#dialog'); $('.menu .list').css('max-height', lheight + 'px'); var top = $(window).height() - $('#dialog').outerHeight() - $('#clipboard').outerHeight(); $('#dialog').css({ left: (left - 4) + 'px', top: top + 'px' }); $('#dialog').fadeIn(); }, 1); }; browser.removeFromClipboard = function(i) { if (!this.clipboard || !this.clipboard[i]) return false; if (this.clipboard.length == 1) { this.clearClipboard(); this.hideDialog(); return; } if (i < this.clipboard.length - 1) { var last = this.clipboard.slice(i + 1); this.clipboard = this.clipboard.slice(0, i); this.clipboard = this.clipboard.concat(last); } else this.clipboard.pop(); this.initClipboard(); this.hideDialog(); this.openClipboard(); return true; }; browser.copyClipboard = function(dir) { if (!this.clipboard || !this.clipboard.length) return; var files = []; var failed = 0; for (i = 0; i < this.clipboard.length; i++) if (this.clipboard[i].readable) files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name; else failed++; if (this.clipboard.length == failed) { browser.alert(this.label("The files in the Clipboard are not readable.")); return; } var go = function(callBack) { if (dir == browser.dir) browser.fadeFiles(); $.ajax({ type: 'POST', dataType: 'json', url: browser.baseGetData('cp_cbd'), data: {dir: dir, files: files}, async: false, success: function(data) { if (callBack) callBack(); browser.check4errors(data); browser.clearClipboard(); if (dir == browser.dir) browser.refresh(); }, error: function() { if (callBack) callBack(); $('#files > div').css({ opacity: '', filter: '' }); browser.alert(browser.label("Unknown error.")); } }); }; if (failed) browser.confirm( browser.label("{count} files in the Clipboard are not readable. Do you want to copy the rest?", {count:failed}), go ) else go(); }; browser.moveClipboard = function(dir) { if (!this.clipboard || !this.clipboard.length) return; var files = []; var failed = 0; for (i = 0; i < this.clipboard.length; i++) if (this.clipboard[i].readable && this.clipboard[i].writable) files[i] = this.clipboard[i].dir + "/" + this.clipboard[i].name; else failed++; if (this.clipboard.length == failed) { browser.alert(this.label("The files in the Clipboard are not movable.")) return; } var go = function(callBack) { browser.fadeFiles(); $.ajax({ type: 'POST', dataType: 'json', url: browser.baseGetData('mv_cbd'), data: {dir: dir, files: files}, async: false, success: function(data) { if (callBack) callBack(); browser.check4errors(data); browser.clearClipboard(); browser.refresh(); }, error: function() { if (callBack) callBack(); $('#files > div').css({ opacity: '', filter: '' }); browser.alert(browser.label("Unknown error.")); } }); }; if (failed) browser.confirm( browser.label("{count} files in the Clipboard are not movable. Do you want to move the rest?", {count: failed}), go ); else go(); }; browser.deleteClipboard = function() { if (!this.clipboard || !this.clipboard.length) return; var files = []; var failed = 0; for (i = 0; i < this.clipboard.length; i++) if (this.clipboard[i].readable && this.clipboard[i].writable) files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name; else failed++; if (this.clipboard.length == failed) { browser.alert(this.label("The files in the Clipboard are not removable.")) return; } var go = function(callBack) { browser.fadeFiles(); $.ajax({ type: 'POST', dataType: 'json', url: browser.baseGetData('rm_cbd'), data: {files:files}, async: false, success: function(data) { if (callBack) callBack(); browser.check4errors(data); browser.clearClipboard(); browser.refresh(); }, error: function() { if (callBack) callBack(); $('#files > div').css({ opacity: '', filter:'' }); browser.alert(browser.label("Unknown error.")); } }); }; if (failed) browser.confirm( browser.label("{count} files in the Clipboard are not removable. Do you want to delete the rest?", {count: failed}), go ); else go(); }; browser.downloadClipboard = function() { if (!this.clipboard || !this.clipboard.length) return; var files = []; for (i = 0; i < this.clipboard.length; i++) if (this.clipboard[i].readable) files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name; if (files.length) this.post(this.baseGetData('downloadClipboard'), {files:files}); }; browser.clearClipboard = function() { $('#clipboard').html(''); this.clipboard = []; };
JavaScript
<?php /** This file is part of KCFinder project * * @desc Base JavaScript object properties * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> var browser = { opener: {}, support: {}, files: [], clipboard: [], labels: [], shows: [], orders: [], cms: "" };
JavaScript
<?php /** This file is part of KCFinder project * * @desc Upload files using drag and drop * @package KCFinder * @version 2.51 * @author Forum user (updated by Pavel Tzonkov) * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> browser.initDropUpload = function() { if ((typeof(XMLHttpRequest) == 'undefined') || (typeof(document.addEventListener) == 'undefined') || (typeof(File) == 'undefined') || (typeof(FileReader) == 'undefined') ) return; if (!XMLHttpRequest.prototype.sendAsBinary) { XMLHttpRequest.prototype.sendAsBinary = function(datastr) { var ords = Array.prototype.map.call(datastr, function(x) { return x.charCodeAt(0) & 0xff; }); var ui8a = new Uint8Array(ords); this.send(ui8a.buffer); } } var uploadQueue = [], uploadInProgress = false, filesCount = 0, errors = [], files = $('#files'), folders = $('div.folder > a'), boundary = '------multipartdropuploadboundary' + (new Date).getTime(), currentFile, filesDragOver = function(e) { if (e.preventDefault) e.preventDefault(); $('#files').addClass('drag'); return false; }, filesDragEnter = function(e) { if (e.preventDefault) e.preventDefault(); return false; }, filesDragLeave = function(e) { if (e.preventDefault) e.preventDefault(); $('#files').removeClass('drag'); return false; }, filesDrop = function(e) { if (e.preventDefault) e.preventDefault(); if (e.stopPropagation) e.stopPropagation(); $('#files').removeClass('drag'); if (!$('#folders span.current').first().parent().data('writable')) { browser.alert("Cannot write to upload folder."); return false; } filesCount += e.dataTransfer.files.length for (var i = 0; i < e.dataTransfer.files.length; i++) { var file = e.dataTransfer.files[i]; file.thisTargetDir = browser.dir; uploadQueue.push(file); } processUploadQueue(); return false; }, folderDrag = function(e) { if (e.preventDefault) e.preventDefault(); return false; }, folderDrop = function(e, dir) { if (e.preventDefault) e.preventDefault(); if (e.stopPropagation) e.stopPropagation(); if (!$(dir).data('writable')) { browser.alert("Cannot write to upload folder."); return false; } filesCount += e.dataTransfer.files.length for (var i = 0; i < e.dataTransfer.files.length; i++) { var file = e.dataTransfer.files[i]; file.thisTargetDir = $(dir).data('path'); uploadQueue.push(file); } processUploadQueue(); return false; }; files.get(0).removeEventListener('dragover', filesDragOver, false); files.get(0).removeEventListener('dragenter', filesDragEnter, false); files.get(0).removeEventListener('dragleave', filesDragLeave, false); files.get(0).removeEventListener('drop', filesDrop, false); files.get(0).addEventListener('dragover', filesDragOver, false); files.get(0).addEventListener('dragenter', filesDragEnter, false); files.get(0).addEventListener('dragleave', filesDragLeave, false); files.get(0).addEventListener('drop', filesDrop, false); folders.each(function() { var folder = this, dragOver = function(e) { $(folder).children('span.folder').addClass('context'); return folderDrag(e); }, dragLeave = function(e) { $(folder).children('span.folder').removeClass('context'); return folderDrag(e); }, drop = function(e) { $(folder).children('span.folder').removeClass('context'); return folderDrop(e, folder); }; this.removeEventListener('dragover', dragOver, false); this.removeEventListener('dragenter', folderDrag, false); this.removeEventListener('dragleave', dragLeave, false); this.removeEventListener('drop', drop, false); this.addEventListener('dragover', dragOver, false); this.addEventListener('dragenter', folderDrag, false); this.addEventListener('dragleave', dragLeave, false); this.addEventListener('drop', drop, false); }); function updateProgress(evt) { var progress = evt.lengthComputable ? Math.round((evt.loaded * 100) / evt.total) + '%' : Math.round(evt.loaded / 1024) + " KB"; $('#loading').html(browser.label("Uploading file {number} of {count}... {progress}", { number: filesCount - uploadQueue.length, count: filesCount, progress: progress })); } function processUploadQueue() { if (uploadInProgress) return false; if (uploadQueue && uploadQueue.length) { var file = uploadQueue.shift(); currentFile = file; $('#loading').html(browser.label("Uploading file {number} of {count}... {progress}", { number: filesCount - uploadQueue.length, count: filesCount, progress: "" })); $('#loading').css('display', 'inline'); var reader = new FileReader(); reader.thisFileName = file.name; reader.thisFileType = file.type; reader.thisFileSize = file.size; reader.thisTargetDir = file.thisTargetDir; reader.onload = function(evt) { uploadInProgress = true; var postbody = '--' + boundary + '\r\nContent-Disposition: form-data; name="upload[]"'; if (evt.target.thisFileName) postbody += '; filename="' + _.utf8encode(evt.target.thisFileName) + '"'; postbody += '\r\n'; if (evt.target.thisFileSize) postbody += 'Content-Length: ' + evt.target.thisFileSize + '\r\n'; postbody += 'Content-Type: ' + evt.target.thisFileType + '\r\n\r\n' + evt.target.result + '\r\n--' + boundary + '\r\nContent-Disposition: form-data; name="dir"\r\n\r\n' + _.utf8encode(evt.target.thisTargetDir) + '\r\n--' + boundary + '\r\n--' + boundary + '--\r\n'; var xhr = new XMLHttpRequest(); xhr.thisFileName = evt.target.thisFileName; if (xhr.upload) { xhr.upload.thisFileName = evt.target.thisFileName; xhr.upload.addEventListener("progress", updateProgress, false); } xhr.open('POST', browser.baseGetData('upload'), true); xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary); xhr.setRequestHeader('Content-Length', postbody.length); xhr.onload = function(e) { $('#loading').css('display', 'none'); if (browser.dir == reader.thisTargetDir) browser.fadeFiles(); uploadInProgress = false; processUploadQueue(); if (xhr.responseText.substr(0, 1) != '/') errors[errors.length] = xhr.responseText; } xhr.sendAsBinary(postbody); }; reader.onerror = function(evt) { $('#loading').css('display', 'none'); uploadInProgress = false; processUploadQueue(); errors[errors.length] = browser.label("Failed to upload {filename}!", { filename: evt.target.thisFileName }); }; reader.readAsBinaryString(file); } else { filesCount = 0; var loop = setInterval(function() { if (uploadInProgress) return; clearInterval(loop); if (currentFile.thisTargetDir == browser.dir) browser.refresh(); boundary = '------multipartdropuploadboundary' + (new Date).getTime(); if (errors.length) { browser.alert(errors.join('\n')); errors = []; } }, 333); } } };
JavaScript
<?php /** This file is part of KCFinder project * * @desc Settings panel functionality * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> browser.initSettings = function() { if (!this.shows.length) { var showInputs = $('#show input[type="checkbox"]').toArray(); $.each(showInputs, function (i, input) { browser.shows[i] = input.name; }); } var shows = this.shows; if (!_.kuki.isSet('showname')) { _.kuki.set('showname', 'on'); $.each(shows, function (i, val) { if (val != "name") _.kuki.set('show' + val, 'off'); }); } $('#show input[type="checkbox"]').click(function() { var kuki = $(this).get(0).checked ? 'on' : 'off'; _.kuki.set('show' + $(this).get(0).name, kuki) if ($(this).get(0).checked) $('#files .file div.' + $(this).get(0).name).css('display', 'block'); else $('#files .file div.' + $(this).get(0).name).css('display', 'none'); }); $.each(shows, function(i, val) { var checked = (_.kuki.get('show' + val) == 'on') ? 'checked' : ''; $('#show input[name="' + val + '"]').get(0).checked = checked; }); if (!this.orders.length) { var orderInputs = $('#order input[type="radio"]').toArray(); $.each(orderInputs, function (i, input) { browser.orders[i] = input.value; }); } var orders = this.orders; if (!_.kuki.isSet('order')) _.kuki.set('order', 'name'); if (!_.kuki.isSet('orderDesc')) _.kuki.set('orderDesc', 'off'); $('#order input[value="' + _.kuki.get('order') + '"]').get(0).checked = true; $('#order input[name="desc"]').get(0).checked = (_.kuki.get('orderDesc') == 'on'); $('#order input[type="radio"]').click(function() { _.kuki.set('order', $(this).get(0).value); browser.orderFiles(); }); $('#order input[name="desc"]').click(function() { _.kuki.set('orderDesc', $(this).get(0).checked ? 'on' : 'off'); browser.orderFiles(); }); if (!_.kuki.isSet('view')) _.kuki.set('view', 'thumbs'); if (_.kuki.get('view') == 'list') { $('#show input').each(function() { this.checked = true; }); $('#show input').each(function() { this.disabled = true; }); } $('#view input[value="' + _.kuki.get('view') + '"]').get(0).checked = true; $('#view input').click(function() { var view = $(this).attr('value'); if (_.kuki.get('view') != view) { _.kuki.set('view', view); if (view == 'list') { $('#show input').each(function() { this.checked = true; }); $('#show input').each(function() { this.disabled = true; }); } else { $.each(browser.shows, function(i, val) { $('#show input[name="' + val + '"]').get(0).checked = (_.kuki.get('show' + val) == "on"); }); $('#show input').each(function() { this.disabled = false; }); } } browser.refresh(); }); };
JavaScript
<?php /** This file is part of KCFinder project * * @desc Miscellaneous functionality * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> browser.drag = function(ev, dd) { var top = dd.offsetY, left = dd.offsetX; if (top < 0) top = 0; if (left < 0) left = 0; if (top + $(this).outerHeight() > $(window).height()) top = $(window).height() - $(this).outerHeight(); if (left + $(this).outerWidth() > $(window).width()) left = $(window).width() - $(this).outerWidth(); $(this).css({ top: top, left: left }); }; browser.showDialog = function(e) { $('#dialog').css({left: 0, top: 0}); this.shadow(); if ($('#dialog div.box') && !$('#dialog div.title').get(0)) { var html = $('#dialog div.box').html(); var title = $('#dialog').data('title') ? $('#dialog').data('title') : ""; html = '<div class="title"><span class="close"></span>' + title + '</div>' + html; $('#dialog div.box').html(html); $('#dialog div.title span.close').mousedown(function() { $(this).addClass('clicked'); }); $('#dialog div.title span.close').mouseup(function() { $(this).removeClass('clicked'); }); $('#dialog div.title span.close').click(function() { browser.hideDialog(); browser.hideAlert(); }); } $('#dialog').drag(browser.drag, {handle: '#dialog div.title'}); $('#dialog').css('display', 'block'); if (e) { var left = e.pageX - parseInt($('#dialog').outerWidth() / 2); var top = e.pageY - parseInt($('#dialog').outerHeight() / 2); if (left < 0) left = 0; if (top < 0) top = 0; if (($('#dialog').outerWidth() + left) > $(window).width()) left = $(window).width() - $('#dialog').outerWidth(); if (($('#dialog').outerHeight() + top) > $(window).height()) top = $(window).height() - $('#dialog').outerHeight(); $('#dialog').css({ left: left + 'px', top: top + 'px' }); } else $('#dialog').css({ left: parseInt(($(window).width() - $('#dialog').outerWidth()) / 2) + 'px', top: parseInt(($(window).height() - $('#dialog').outerHeight()) / 2) + 'px' }); $(document).unbind('keydown'); $(document).keydown(function(e) { if (e.keyCode == 27) browser.hideDialog(); }); }; browser.hideDialog = function() { this.unshadow(); if ($('#clipboard').hasClass('selected')) $('#clipboard').removeClass('selected'); $('#dialog').css('display', 'none'); $('div.folder > a > span.folder').removeClass('context'); $('#dialog').html(''); $('#dialog').data('title', null); $('#dialog').unbind(); $('#dialog').click(function() { return false; }); $(document).unbind('keydown'); $(document).keydown(function(e) { return !browser.selectAll(e); }); browser.hideAlert(); }; browser.showAlert = function(shadow) { $('#alert').css({left: 0, top: 0}); if (typeof shadow == 'undefined') shadow = true; if (shadow) this.shadow(); var left = parseInt(($(window).width() - $('#alert').outerWidth()) / 2), top = parseInt(($(window).height() - $('#alert').outerHeight()) / 2); var wheight = $(window).height(); if (top < 0) top = 0; $('#alert').css({ left: left + 'px', top: top + 'px', display: 'block' }); if ($('#alert').outerHeight() > wheight) { $('#alert div.message').css({ height: wheight - $('#alert div.title').outerHeight() - $('#alert div.ok').outerHeight() - 20 + 'px' }); } $(document).unbind('keydown'); $(document).keydown(function(e) { if (e.keyCode == 27) { browser.hideDialog(); browser.hideAlert(); $(document).unbind('keydown'); $(document).keydown(function(e) { return !browser.selectAll(e); }); } }); }; browser.hideAlert = function(shadow) { if (typeof shadow == 'undefined') shadow = true; if (shadow) this.unshadow(); $('#alert').css('display', 'none'); $('#alert').html(''); $('#alert').data('title', null); }; browser.alert = function(msg, shadow) { msg = msg.replace(/\r?\n/g, "<br />"); var title = $('#alert').data('title') ? $('#alert').data('title') : browser.label("Attention"); $('#alert').html('<div class="title"><span class="close"></span>' + title + '</div><div class="message">' + msg + '</div><div class="ok"><button>' + browser.label("OK") + '</button></div>'); $('#alert div.ok button').click(function() { browser.hideAlert(shadow); }); $('#alert div.title span.close').mousedown(function() { $(this).addClass('clicked'); }); $('#alert div.title span.close').mouseup(function() { $(this).removeClass('clicked'); }); $('#alert div.title span.close').click(function() { browser.hideAlert(shadow); }); $('#alert').drag(browser.drag, {handle: "#alert div.title"}); browser.showAlert(shadow); }; browser.confirm = function(question, callBack) { $('#dialog').data('title', browser.label("Question")); $('#dialog').html('<div class="box"><div class="question">' + browser.label(question) + '<div class="buttons"><button>' + browser.label("No") + '</button> <button>' + browser.label("Yes") + '</button></div></div></div>'); browser.showDialog(); $('#dialog div.buttons button').first().click(function() { browser.hideDialog(); }); $('#dialog div.buttons button').last().click(function() { if (callBack) callBack(function() { browser.hideDialog(); }); else browser.hideDialog(); }); $('#dialog div.buttons button').get(1).focus(); }; browser.shadow = function() { $('#shadow').css('display', 'block'); }; browser.unshadow = function() { $('#shadow').css('display', 'none'); }; browser.showMenu = function(e) { var left = e.pageX; var top = e.pageY; if (($('#dialog').outerWidth() + left) > $(window).width()) left = $(window).width() - $('#dialog').outerWidth(); if (($('#dialog').outerHeight() + top) > $(window).height()) top = $(window).height() - $('#dialog').outerHeight(); $('#dialog').css({ left: left + 'px', top: top + 'px', display: 'none' }); $('#dialog').fadeIn(); }; browser.fileNameDialog = function(e, post, inputName, inputValue, url, labels, callBack, selectAll) { var html = '<form method="post" action="javascript:;">' + '<div class="box">' + '<input name="' + inputName + '" type="text" /><br />' + '<div style="text-align:right">' + '<input type="submit" value="' + _.htmlValue(this.label("OK")) + '" /> ' + '<input type="button" value="' + _.htmlValue(this.label("Cancel")) + '" onclick="browser.hideDialog(); browser.hideAlert(); return false" />' + '</div></div></form>'; $('#dialog').html(html); $('#dialog').data('title', this.label(labels.title)); $('#dialog input[name="' + inputName + '"]').attr('value', inputValue); $('#dialog').unbind(); $('#dialog').click(function() { return false; }); $('#dialog form').submit(function() { var name = this.elements[0]; name.value = $.trim(name.value); if (name.value == '') { browser.alert(browser.label(labels.errEmpty), false); name.focus(); return; } else if (/[\/\\]/g.test(name.value)) { browser.alert(browser.label(labels.errSlash), false); name.focus(); return; } else if (name.value.substr(0, 1) == ".") { browser.alert(browser.label(labels.errDot), false); name.focus(); return; } eval('post.' + inputName + ' = name.value;'); $.ajax({ type: 'POST', dataType: 'json', url: url, data: post, async: false, success: function(data) { if (browser.check4errors(data, false)) return; if (callBack) callBack(data); browser.hideDialog(); }, error: function() { browser.alert(browser.label("Unknown error."), false); } }); return false; }); browser.showDialog(e); $('#dialog').css('display', 'block'); $('#dialog input[type="submit"]').click(function() { return $('#dialog form').submit(); }); var field = $('#dialog input[type="text"]'); var value = field.attr('value'); if (!selectAll && /^(.+)\.[^\.]+$/ .test(value)) { value = value.replace(/^(.+)\.[^\.]+$/, "$1"); _.selection(field.get(0), 0, value.length); } else { field.get(0).focus(); field.get(0).select(); } }; browser.orderFiles = function(callBack, selected) { var order = _.kuki.get('order'); var desc = (_.kuki.get('orderDesc') == 'on'); if (!browser.files || !browser.files.sort) browser.files = []; browser.files = browser.files.sort(function(a, b) { var a1, b1, arr; if (!order) order = 'name'; if (order == 'date') { a1 = a.mtime; b1 = b.mtime; } else if (order == 'type') { a1 = _.getFileExtension(a.name); b1 = _.getFileExtension(b.name); } else if (order == 'size') { a1 = a.size; b1 = b.size; } else eval('a1 = a.' + order + '.toLowerCase(); b1 = b.' + order + '.toLowerCase();'); if ((order == 'size') || (order == 'date')) { if (a1 < b1) return desc ? 1 : -1; if (a1 > b1) return desc ? -1 : 1; } if (a1 == b1) { a1 = a.name.toLowerCase(); b1 = b.name.toLowerCase(); arr = [a1, b1]; arr = arr.sort(); return (arr[0] == a1) ? -1 : 1; } arr = [a1, b1]; arr = arr.sort(); if (arr[0] == a1) return desc ? 1 : -1; return desc ? -1 : 1; }); browser.showFiles(callBack, selected); browser.initFiles(); }; browser.humanSize = function(size) { if (size < 1024) { size = size.toString() + ' B'; } else if (size < 1048576) { size /= 1024; size = parseInt(size).toString() + ' KB'; } else if (size < 1073741824) { size /= 1048576; size = parseInt(size).toString() + ' MB'; } else if (size < 1099511627776) { size /= 1073741824; size = parseInt(size).toString() + ' GB'; } else { size /= 1099511627776; size = parseInt(size).toString() + ' TB'; } return size; }; browser.baseGetData = function(act) { var data = 'browse.php?type=' + encodeURIComponent(this.type) + '&lng=' + this.lang; if (act) data += "&act=" + act; if (this.cms) data += "&cms=" + this.cms; return data; }; browser.label = function(index, data) { var label = this.labels[index] ? this.labels[index] : index; if (data) $.each(data, function(key, val) { label = label.replace('{' + key + '}', val); }); return label; }; browser.check4errors = function(data, shadow) { if (!data.error) return false; var msg; if (data.error.join) msg = data.error.join("\n"); else msg = data.error; browser.alert(msg, shadow); return true; }; browser.post = function(url, data) { var html = '<form id="postForm" method="POST" action="' + url + '">'; $.each(data, function(key, val) { if ($.isArray(val)) $.each(val, function(i, aval) { html += '<input type="hidden" name="' + _.htmlValue(key) + '[]" value="' + _.htmlValue(aval) + '" />'; }); else html += '<input type="hidden" name="' + _.htmlValue(key) + '" value="' + _.htmlValue(val) + '" />'; }); html += '</form>'; $('#dialog').html(html); $('#dialog').css('display', 'block'); $('#postForm').get(0).submit(); }; browser.fadeFiles = function() { $('#files > div').css({ opacity: '0.4', filter: 'alpha(opacity:40)' }); };
JavaScript
<?php /** This file is part of KCFinder project * * @desc Object initializations * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> browser.init = function() { if (!this.checkAgent()) return; $('body').click(function() { browser.hideDialog(); }); $('#shadow').click(function() { return false; }); $('#dialog').unbind(); $('#dialog').click(function() { return false; }); $('#alert').unbind(); $('#alert').click(function() { return false; }); this.initOpeners(); this.initSettings(); this.initContent(); this.initToolbar(); this.initResizer(); this.initDropUpload(); }; browser.checkAgent = function() { if (!$.browser.version || ($.browser.msie && (parseInt($.browser.version) < 7) && !this.support.chromeFrame) || ($.browser.opera && (parseInt($.browser.version) < 10)) || ($.browser.mozilla && (parseFloat($.browser.version.replace(/^(\d+(\.\d+)?)([^\d].*)?$/, "$1")) < 1.8)) ) { var html = '<div style="padding:10px">Your browser is not capable to display KCFinder. Please update your browser or install another one: <a href="http://www.mozilla.com/firefox/" target="_blank">Mozilla Firefox</a>, <a href="http://www.apple.com/safari" target="_blank">Apple Safari</a>, <a href="http://www.google.com/chrome" target="_blank">Google Chrome</a>, <a href="http://www.opera.com/browser" target="_blank">Opera</a>.'; if ($.browser.msie) html += ' You may also install <a href="http://www.google.com/chromeframe" target="_blank">Google Chrome Frame ActiveX plugin</a> to get Internet Explorer 6 working.'; html += '</div>'; $('body').html(html); return false; } return true; }; browser.initOpeners = function() { if (this.opener.TinyMCE && (typeof(tinyMCEPopup) == 'undefined')) this.opener.TinyMCE = null; if (this.opener.TinyMCE) this.opener.callBack = true; if ((!this.opener.name || (this.opener.name == 'fckeditor')) && window.opener && window.opener.SetUrl ) { this.opener.FCKeditor = true; this.opener.callBack = true; } if (this.opener.CKEditor) { if (window.parent && window.parent.CKEDITOR) this.opener.CKEditor.object = window.parent.CKEDITOR; else if (window.opener && window.opener.CKEDITOR) { this.opener.CKEditor.object = window.opener.CKEDITOR; this.opener.callBack = true; } else this.opener.CKEditor = null; } if (!this.opener.CKEditor && !this.opener.FCKEditor && !this.TinyMCE) { if ((window.opener && window.opener.KCFinder && window.opener.KCFinder.callBack) || (window.parent && window.parent.KCFinder && window.parent.KCFinder.callBack) ) this.opener.callBack = window.opener ? window.opener.KCFinder.callBack : window.parent.KCFinder.callBack; if (( window.opener && window.opener.KCFinder && window.opener.KCFinder.callBackMultiple ) || ( window.parent && window.parent.KCFinder && window.parent.KCFinder.callBackMultiple ) ) this.opener.callBackMultiple = window.opener ? window.opener.KCFinder.callBackMultiple : window.parent.KCFinder.callBackMultiple; } }; browser.initContent = function() { $('div#folders').html(this.label("Loading folders...")); $('div#files').html(this.label("Loading files...")); $.ajax({ type: 'GET', dataType: 'json', url: browser.baseGetData('init'), async: false, success: function(data) { if (browser.check4errors(data)) return; browser.dirWritable = data.dirWritable; $('#folders').html(browser.buildTree(data.tree)); browser.setTreeData(data.tree); browser.initFolders(); browser.files = data.files ? data.files : []; browser.orderFiles(); }, error: function() { $('div#folders').html(browser.label("Unknown error.")); $('div#files').html(browser.label("Unknown error.")); } }); }; browser.initResizer = function() { var cursor = ($.browser.opera) ? 'move' : 'col-resize'; $('#resizer').css('cursor', cursor); $('#resizer').drag('start', function() { $(this).css({opacity:'0.4', filter:'alpha(opacity:40)'}); $('#all').css('cursor', cursor); }); $('#resizer').drag(function(e) { var left = e.pageX - parseInt(_.nopx($(this).css('width')) / 2); left = (left >= 0) ? left : 0; left = (left + _.nopx($(this).css('width')) < $(window).width()) ? left : $(window).width() - _.nopx($(this).css('width')); $(this).css('left', left); }); var end = function() { $(this).css({opacity:'0', filter:'alpha(opacity:0)'}); $('#all').css('cursor', ''); var left = _.nopx($(this).css('left')) + _.nopx($(this).css('width')); var right = $(window).width() - left; $('#left').css('width', left + 'px'); $('#right').css('width', right + 'px'); _('files').style.width = $('#right').innerWidth() - _.outerHSpace('#files') + 'px'; _('resizer').style.left = $('#left').outerWidth() - _.outerRightSpace('#folders', 'm') + 'px'; _('resizer').style.width = _.outerRightSpace('#folders', 'm') + _.outerLeftSpace('#files', 'm') + 'px'; browser.fixFilesHeight(); }; $('#resizer').drag('end', end); $('#resizer').mouseup(end); }; browser.resize = function() { _('left').style.width = '25%'; _('right').style.width = '75%'; _('toolbar').style.height = $('#toolbar a').outerHeight() + "px"; _('shadow').style.width = $(window).width() + 'px'; _('shadow').style.height = _('resizer').style.height = $(window).height() + 'px'; _('left').style.height = _('right').style.height = $(window).height() - $('#status').outerHeight() + 'px'; _('folders').style.height = $('#left').outerHeight() - _.outerVSpace('#folders') + 'px'; browser.fixFilesHeight(); var width = $('#left').outerWidth() + $('#right').outerWidth(); _('status').style.width = width + 'px'; while ($('#status').outerWidth() > width) _('status').style.width = _.nopx(_('status').style.width) - 1 + 'px'; while ($('#status').outerWidth() < width) _('status').style.width = _.nopx(_('status').style.width) + 1 + 'px'; if ($.browser.msie && ($.browser.version.substr(0, 1) < 8)) _('right').style.width = $(window).width() - $('#left').outerWidth() + 'px'; _('files').style.width = $('#right').innerWidth() - _.outerHSpace('#files') + 'px'; _('resizer').style.left = $('#left').outerWidth() - _.outerRightSpace('#folders', 'm') + 'px'; _('resizer').style.width = _.outerRightSpace('#folders', 'm') + _.outerLeftSpace('#files', 'm') + 'px'; }; browser.fixFilesHeight = function() { _('files').style.height = $('#left').outerHeight() - $('#toolbar').outerHeight() - _.outerVSpace('#files') - (($('#settings').css('display') != "none") ? $('#settings').outerHeight() : 0) + 'px'; };
JavaScript
/** This file is part of KCFinder project * * @desc Helper object * @package KCFinder * @version 2.51 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */ var _ = function(id) { return document.getElementById(id); }; _.nopx = function(val) { return parseInt(val.replace(/^(\d+)px$/, "$1")); }; _.unselect = function() { if (document.selection && document.selection.empty) document.selection.empty() ; else if (window.getSelection) { var sel = window.getSelection(); if (sel && sel.removeAllRanges) sel.removeAllRanges(); } }; _.selection = function(field, start, end) { if (field.createTextRange) { var selRange = field.createTextRange(); selRange.collapse(true); selRange.moveStart('character', start); selRange.moveEnd('character', end-start); selRange.select(); } else if (field.setSelectionRange) { field.setSelectionRange(start, end); } else if (field.selectionStart) { field.selectionStart = start; field.selectionEnd = end; } field.focus(); }; _.htmlValue = function(value) { return value .replace(/\&/g, "&amp;") .replace(/\"/g, "&quot;") .replace(/\'/g, "&#39;"); }; _.htmlData = function(value) { return value .replace(/\&/g, "&amp;") .replace(/\</g, "&lt;") .replace(/\>/g, "&gt;") .replace(/\ /g, "&nbsp;"); } _.jsValue = function(value) { return value .replace(/\\/g, "\\\\") .replace(/\r?\n/, "\\\n") .replace(/\"/g, "\\\"") .replace(/\'/g, "\\'"); }; _.basename = function(path) { var expr = /^.*\/([^\/]+)\/?$/g; return expr.test(path) ? path.replace(expr, "$1") : path; }; _.dirname = function(path) { var expr = /^(.*)\/[^\/]+\/?$/g; return expr.test(path) ? path.replace(expr, "$1") : ''; }; _.inArray = function(needle, arr) { if ((typeof arr == 'undefined') || !arr.length || !arr.push) return false; for (var i = 0; i < arr.length; i++) if (arr[i] == needle) return true; return false; }; _.getFileExtension = function(filename, toLower) { if (typeof(toLower) == 'undefined') toLower = true; if (/^.*\.[^\.]*$/.test(filename)) { var ext = filename.replace(/^.*\.([^\.]*)$/, "$1"); return toLower ? ext.toLowerCase(ext) : ext; } else return ""; }; _.escapeDirs = function(path) { var fullDirExpr = /^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)$/, prefix = ""; if (fullDirExpr.test(path)) { var port = path.replace(fullDirExpr, "$4"); prefix = path.replace(fullDirExpr, "$1://$2") if (port.length) prefix += ":" + port; prefix += "/"; path = path.replace(fullDirExpr, "$5"); } var dirs = path.split('/'); var escapePath = ''; for (var i = 0; i < dirs.length; i++) escapePath += encodeURIComponent(dirs[i]) + '/'; return prefix + escapePath.substr(0, escapePath.length - 1); }; _.outerSpace = function(selector, type, mbp) { if (!mbp) mbp = "mbp"; var r = 0; if (/m/i.test(mbp)) { var m = _.nopx($(selector).css('margin-' + type)); if (m) r += m; } if (/b/i.test(mbp)) { var b = _.nopx($(selector).css('border-' + type + '-width')); if (b) r += b; } if (/p/i.test(mbp)) { var p = _.nopx($(selector).css('padding-' + type)); if (p) r += p; } return r; }; _.outerLeftSpace = function(selector, mbp) { return _.outerSpace(selector, 'left', mbp); }; _.outerTopSpace = function(selector, mbp) { return _.outerSpace(selector, 'top', mbp); }; _.outerRightSpace = function(selector, mbp) { return _.outerSpace(selector, 'right', mbp); }; _.outerBottomSpace = function(selector, mbp) { return _.outerSpace(selector, 'bottom', mbp); }; _.outerHSpace = function(selector, mbp) { return (_.outerLeftSpace(selector, mbp) + _.outerRightSpace(selector, mbp)); }; _.outerVSpace = function(selector, mbp) { return (_.outerTopSpace(selector, mbp) + _.outerBottomSpace(selector, mbp)); }; _.kuki = { prefix: '', duration: 356, domain: '', path: '', secure: false, set: function(name, value, duration, domain, path, secure) { name = this.prefix + name; if (duration == null) duration = this.duration; if (secure == null) secure = this.secure; if ((domain == null) && this.domain) domain = this.domain; if ((path == null) && this.path) path = this.path; secure = secure ? true : false; var date = new Date(); date.setTime(date.getTime() + (duration * 86400000)); var expires = date.toGMTString(); var str = name + '=' + value + '; expires=' + expires; if (domain != null) str += '; domain=' + domain; if (path != null) str += '; path=' + path; if (secure) str += '; secure'; return (document.cookie = str) ? true : false; }, get: function(name) { name = this.prefix + name; var nameEQ = name + '='; var kukis = document.cookie.split(';'); var kuki; for (var i = 0; i < kukis.length; i++) { kuki = kukis[i]; while (kuki.charAt(0) == ' ') kuki = kuki.substring(1, kuki.length); if (kuki.indexOf(nameEQ) == 0) return kuki.substring(nameEQ.length, kuki.length); } return null; }, del: function(name) { return this.set(name, '', -1); }, isSet: function(name) { return (this.get(name) != null); } }; _.md5 = function(string) { var RotateLeft = function(lValue, iShiftBits) { return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits)); }; var AddUnsigned = function(lX,lY) { var lX4, lY4, lX8, lY8, lResult; lX8 = (lX & 0x80000000); lY8 = (lY & 0x80000000); lX4 = (lX & 0x40000000); lY4 = (lY & 0x40000000); lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF); if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8); if (lX4 | lY4) return (lResult & 0x40000000) ? (lResult ^ 0xC0000000 ^ lX8 ^ lY8) : (lResult ^ 0x40000000 ^ lX8 ^ lY8); else return (lResult ^ lX8 ^ lY8); }; var F = function(x, y, z) { return (x & y) | ((~x) & z); }; var G = function(x, y, z) { return (x & z) | (y & (~z)); }; var H = function(x, y, z) { return (x ^ y ^ z); }; var I = function(x, y, z) { return (y ^ (x | (~z))); }; var FF = function(a, b, c, d, x, s, ac) { a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac)); return AddUnsigned(RotateLeft(a, s), b); }; var GG = function(a, b, c, d, x, s, ac) { a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac)); return AddUnsigned(RotateLeft(a, s), b); }; var HH = function(a, b, c, d, x, s, ac) { a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac)); return AddUnsigned(RotateLeft(a, s), b); }; var II = function(a, b, c, d, x, s, ac) { a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac)); return AddUnsigned(RotateLeft(a, s), b); }; var ConvertToWordArray = function(string) { var lWordCount; var lMessageLength = string.length; var lNumberOfWords_temp1 = lMessageLength + 8; var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64; var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16; var lWordArray = [lNumberOfWords - 1]; var lBytePosition = 0; var lByteCount = 0; while (lByteCount < lMessageLength) { lWordCount = (lByteCount - (lByteCount % 4)) / 4; lBytePosition = (lByteCount % 4) * 8; lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition)); lByteCount++; } lWordCount = (lByteCount - (lByteCount % 4)) / 4; lBytePosition = (lByteCount % 4) * 8; lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition); lWordArray[lNumberOfWords - 2] = lMessageLength << 3; lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29; return lWordArray; }; var WordToHex = function(lValue) { var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount; for (lCount = 0; lCount <= 3; lCount++) { lByte = (lValue >>> (lCount * 8)) & 255; WordToHexValue_temp = "0" + lByte.toString(16); WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2,2); } return WordToHexValue; }; var x = []; var k, AA, BB, CC, DD, a, b, c, d; var S11 = 7, S12 = 12, S13 = 17, S14 = 22; var S21 = 5, S22 = 9, S23 = 14, S24 = 20; var S31 = 4, S32 = 11, S33 = 16, S34 = 23; var S41 = 6, S42 = 10, S43 = 15, S44 = 21; string = _.utf8encode(string); x = ConvertToWordArray(string); a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; for (k = 0; k < x.length; k += 16) { AA = a; BB = b; CC = c; DD = d; a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478); d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756); c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB); b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE); a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF); d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A); c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613); b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501); a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8); d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF); c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1); b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE); a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122); d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193); c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E); b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821); a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562); d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340); c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51); b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA); a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D); d = GG(d, a, b, c, x[k + 10], S22, 0x2441453); c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681); b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8); a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6); d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6); c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87); b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED); a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905); d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8); c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9); b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A); a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942); d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681); c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122); b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C); a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44); d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9); c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60); b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70); a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6); d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA); c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085); b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05); a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039); d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5); c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8); b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665); a = II(a, b, c, d, x[k + 0], S41, 0xF4292244); d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97); c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7); b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039); a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3); d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92); c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D); b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1); a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F); d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0); c = II(c, d, a, b, x[k + 6], S43, 0xA3014314); b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1); a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82); d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235); c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB); b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391); a = AddUnsigned(a, AA); b = AddUnsigned(b, BB); c = AddUnsigned(c, CC); d = AddUnsigned(d, DD); } var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d); return temp.toLowerCase(); }; _.utf8encode = function(string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; };
JavaScript
/*! * jQuery Right-Click Plugin * * Version 1.01 * * Cory S.N. LaViska * A Beautiful Site (http://abeautifulsite.net/) * 20 December 2008 * * Visit http://abeautifulsite.net/notebook/68 for more information * * License: * This plugin is dual-licensed under the GNU General Public License and the MIT License * and is copyright 2008 A Beautiful Site, LLC. */ if(jQuery){(function(){$.extend($.fn,{rightClick:function(a){$(this).each(function(){$(this).mousedown(function(c){var b=c;if($.browser.safari&&navigator.userAgent.indexOf("Mac")!=-1&&parseInt($.browser.version,10)<=525){if(b.button==2){a.call($(this),b);return false}else{return true}}else{$(this).mouseup(function(){$(this).unbind("mouseup");if(b.button==2){a.call($(this),b);return false}else{return true}})}});$(this)[0].oncontextmenu=function(){return false}});return $(this)},rightMouseDown:function(a){$(this).each(function(){$(this).mousedown(function(b){if(b.button==2){a.call($(this),b);return false}else{return true}});$(this)[0].oncontextmenu=function(){return false}});return $(this)},rightMouseUp:function(a){$(this).each(function(){$(this).mouseup(function(b){if(b.button==2){a.call($(this),b);return false}else{return true}});$(this)[0].oncontextmenu=function(){return false}});return $(this)},noContext:function(){$(this).each(function(){$(this)[0].oncontextmenu=function(){return false}});return $(this)}})})(jQuery)};
JavaScript
// If this file exists in theme directory, it will be loaded in <head> section var imgLoading = new Image(); imgLoading.src = 'themes/oxygen/img/loading.gif';
JavaScript
// If this file exists in theme directory, it will be loaded in <head> section var imgLoading = new Image(); imgLoading.src = 'themes/dark/img/loading.gif';
JavaScript
/** * Galleria Flickr Plugin 2012-04-04 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function($) { /*global jQuery, Galleria, window */ Galleria.requires(1.25, 'The Flickr Plugin requires Galleria version 1.2.5 or later.'); // The script path var PATH = Galleria.utils.getScriptPath(); /** @class @constructor @example var flickr = new Galleria.Flickr(); @author http://aino.se @requires jQuery @requires Galleria @param {String} [api_key] Flickr API key to be used, defaults to the Galleria key @returns Instance */ Galleria.Flickr = function( api_key ) { this.api_key = api_key || '2a2ce06c15780ebeb0b706650fc890b2'; this.options = { max: 30, // photos to return imageSize: 'medium', // photo size ( thumb,small,medium,big,original ) thumbSize: 'thumb', // thumbnail size ( thumb,small,medium,big,original ) sort: 'interestingness-desc', // sort option ( date-posted-asc, date-posted-desc, date-taken-asc, date-taken-desc, interestingness-desc, interestingness-asc, relevance ) description: false, // set this to true to get description as caption complete: function(){}, // callback to be called inside the Galleria.prototype.load backlink: false // set this to true if you want to pass a link back to the original image }; }; Galleria.Flickr.prototype = { // bring back the constructor reference constructor: Galleria.Flickr, /** Search for anything at Flickr @param {String} phrase The string to search for @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ search: function( phrase, callback ) { return this._find({ text: phrase }, callback ); }, /** Search for anything at Flickr by tag @param {String} tag The tag(s) to search for @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ tags: function( tag, callback ) { return this._find({ tags: tag }, callback); }, /** Get a user's public photos @param {String} username The username as shown in the URL to fetch @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ user: function( username, callback ) { return this._call({ method: 'flickr.urls.lookupUser', url: 'flickr.com/photos/' + username }, function( data ) { this._find({ user_id: data.user.id, method: 'flickr.people.getPublicPhotos' }, callback); }); }, /** Get photos from a photoset by ID @param {String|Number} photoset_id The photoset id to fetch @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ set: function( photoset_id, callback ) { return this._find({ photoset_id: photoset_id, method: 'flickr.photosets.getPhotos' }, callback); }, /** Get photos from a gallery by ID @param {String|Number} gallery_id The gallery id to fetch @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ gallery: function( gallery_id, callback ) { return this._find({ gallery_id: gallery_id, method: 'flickr.galleries.getPhotos' }, callback); }, /** Search groups and fetch photos from the first group found Useful if you know the exact name of a group and want to show the groups photos. @param {String} group The group name to search for @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ groupsearch: function( group, callback ) { return this._call({ text: group, method: 'flickr.groups.search' }, function( data ) { this.group( data.groups.group[0].nsid, callback ); }); }, /** Get photos from a group by ID @param {String} group_id The group id to fetch @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ group: function ( group_id, callback ) { return this._find({ group_id: group_id, method: 'flickr.groups.pools.getPhotos' }, callback ); }, /** Set flickr options @param {Object} options The options object to blend @returns Instance */ setOptions: function( options ) { $.extend(this.options, options); return this; }, // call Flickr and raise errors _call: function( params, callback ) { var url = 'http://api.flickr.com/services/rest/?'; var scope = this; params = $.extend({ format : 'json', jsoncallback : '?', api_key: this.api_key }, params ); $.each(params, function( key, value ) { url += '&' + key + '=' + value; }); $.getJSON(url, function(data) { if ( data.stat === 'ok' ) { callback.call(scope, data); } else { Galleria.raise( data.code.toString() + ' ' + data.stat + ': ' + data.message, true ); } }); return scope; }, // "hidden" way of getting a big image (~1024) from flickr _getBig: function( photo ) { if ( photo.url_l ) { return photo.url_l; } else if ( parseInt( photo.width_o, 10 ) > 1280 ) { return 'http://farm'+photo.farm + '.static.flickr.com/'+photo.server + '/' + photo.id + '_' + photo.secret + '_b.jpg'; } return photo.url_o || photo.url_z || photo.url_m; }, // get image size by option name _getSize: function( photo, size ) { var img; switch(size) { case 'thumb': img = photo.url_t; break; case 'small': img = photo.url_s; break; case 'big': img = this._getBig( photo ); break; case 'original': img = photo.url_o ? photo.url_o : this._getBig( photo ); break; default: img = photo.url_z || photo.url_m; break; } return img; }, // ask flickr for photos, parse the result and call the callback with the galleria-ready data array _find: function( params, callback ) { params = $.extend({ method: 'flickr.photos.search', extras: 'url_t,url_m,url_o,url_s,url_l,url_z,description', sort: this.options.sort }, params ); return this._call( params, function(data) { var gallery = [], photos = data.photos ? data.photos.photo : data.photoset.photo, len = Math.min( this.options.max, photos.length ), photo, i; for ( i=0; i<len; i++ ) { photo = photos[i]; gallery.push({ thumb: this._getSize( photo, this.options.thumbSize ), image: this._getSize( photo, this.options.imageSize ), big: this._getBig( photo ), title: photos[i].title, description: this.options.description && photos[i].description ? photos[i].description._content : '', link: this.options.backlink ? 'http://flickr.com/photos/' + photo.owner + '/' + photo.id : '' }); } callback.call( this, gallery ); }); } }; /** Galleria modifications We fake-extend the load prototype to make Flickr integration as simple as possible */ // save the old prototype in a local variable var load = Galleria.prototype.load; // fake-extend the load prototype using the flickr data Galleria.prototype.load = function() { // pass if no data is provided or flickr option not found if ( arguments.length || typeof this._options.flickr !== 'string' ) { load.apply( this, Galleria.utils.array( arguments ) ); return; } // define some local vars var self = this, args = Galleria.utils.array( arguments ), flickr = this._options.flickr.split(':'), f, opts = $.extend({}, self._options.flickrOptions), loader = typeof opts.loader !== 'undefined' ? opts.loader : $('<div>').css({ width: 48, height: 48, opacity: 0.7, background:'#000 url('+PATH+'loader.gif) no-repeat 50% 50%' }); if ( flickr.length ) { // validate the method if ( typeof Galleria.Flickr.prototype[ flickr[0] ] !== 'function' ) { Galleria.raise( flickr[0] + ' method not found in Flickr plugin' ); return load.apply( this, args ); } // validate the argument if ( !flickr[1] ) { Galleria.raise( 'No flickr argument found' ); return load.apply( this, args ); } // apply the preloader window.setTimeout(function() { self.$( 'target' ).append( loader ); },100); // create the instance f = new Galleria.Flickr(); // apply Flickr options if ( typeof self._options.flickrOptions === 'object' ) { f.setOptions( self._options.flickrOptions ); } // call the flickr method and trigger the DATA event f[ flickr[0] ]( flickr[1], function( data ) { self._data = data; loader.remove(); self.trigger( Galleria.DATA ); f.options.complete.call(f, data); }); } else { // if flickr array not found, pass load.apply( this, args ); } }; }( jQuery ) );
JavaScript
/** * Galleria Picasa Plugin 2012-04-04 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function($) { /*global jQuery, Galleria, window */ Galleria.requires(1.25, 'The Picasa Plugin requires Galleria version 1.2.5 or later.'); // The script path var PATH = Galleria.utils.getScriptPath(); /** @class @constructor @example var picasa = new Galleria.Picasa(); @author http://aino.se @requires jQuery @requires Galleria @returns Instance */ Galleria.Picasa = function() { this.options = { max: 30, // photos to return imageSize: 'medium', // photo size ( thumb,small,medium,big,original ) or a number thumbSize: 'thumb', // thumbnail size ( thumb,small,medium,big,original ) or a number complete: function(){} // callback to be called inside the Galleria.prototype.load }; }; Galleria.Picasa.prototype = { // bring back the constructor reference constructor: Galleria.Picasa, /** Search for anything at Picasa @param {String} phrase The string to search for @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ search: function( phrase, callback ) { return this._call( 'search', 'all', { q: phrase }, callback ); }, /** Get a user's public photos @param {String} username The username to fetch photos from @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ user: function( username, callback ) { return this._call( 'user', 'user/' + username, callback ); }, /** Get photos from an album @param {String} username The username that owns the album @param {String} album The album ID @param {Function} [callback] The callback to be called when the data is ready @returns Instance */ useralbum: function( username, album, callback ) { return this._call( 'useralbum', 'user/' + username + '/album/' + album, callback ); }, /** Set picasa options @param {Object} options The options object to blend @returns Instance */ setOptions: function( options ) { $.extend(this.options, options); return this; }, // call Picasa _call: function( type, url, params, callback ) { url = 'https://picasaweb.google.com/data/feed/api/' + url + '?'; if (typeof params == 'function') { callback = params; params = {}; } var self = this; params = $.extend({ 'kind': 'photo', 'access': 'public', 'max-results': this.options.max, 'thumbsize': this._getSizes().join(','), 'alt': 'json-in-script', 'callback': '?' }, params ); $.each(params, function( key, value ) { url += '&' + key + '=' + value; }); // since Picasa throws 404 when the call is malformed, we must set a timeout here: var data = false; Galleria.utils.wait({ until: function() { return data; }, success: function() { self._parse.call( self, data.feed.entry, callback ); }, error: function() { var msg = ''; if ( type == 'user' ) { msg = 'user not found.'; } else if ( type == 'useralbum' ) { msg = 'album or user not found.'; } Galleria.raise('Picasa request failed' + (msg ? ': ' + msg : '.')); }, timeout: 5000 }); $.getJSON( url, function( result ) { data = result; }); return self; }, // parse image sizes and return an array of three _getSizes: function() { var self = this, norm = { small: '72c', thumb: '104u', medium: '640u', big: '1024u', original: '1600u' }, op = self.options, t = {}, n, sz = [32,48,64,72,94,104,110,128,144,150,160,200,220,288,320,400,512,576,640,720,800,912,1024,1152,1280,1440,1600]; $(['thumbSize', 'imageSize']).each(function() { if( op[this] in norm ) { t[this] = norm[ op[this] ]; } else { n = Galleria.utils.parseValue( op[this] ); if (n > 1600) { n = 1600; } else { $.each( sz, function(i) { if ( n < this ) { n = sz[i-1]; return false; } }); } t[this] = n; } }); return [ t.thumbSize, t.imageSize, '1280u']; }, // parse the result and call the callback with the galleria-ready data array _parse: function( data, callback ) { var self = this, gallery = [], img; $.each( data, function() { img = this.media$group.media$thumbnail; gallery.push({ thumb: img[0].url, image: img[1].url, big: img[2].url, title: this.summary.$t }); }); callback.call( this, gallery ); } }; /** Galleria modifications We fake-extend the load prototype to make Picasa integration as simple as possible */ // save the old prototype in a local variable var load = Galleria.prototype.load; // fake-extend the load prototype using the picasa data Galleria.prototype.load = function() { // pass if no data is provided or picasa option not found if ( arguments.length || typeof this._options.picasa !== 'string' ) { load.apply( this, Galleria.utils.array( arguments ) ); return; } // define some local vars var self = this, args = Galleria.utils.array( arguments ), picasa = this._options.picasa.split(':'), p, opts = $.extend({}, self._options.picasaOptions), loader = typeof opts.loader !== 'undefined' ? opts.loader : $('<div>').css({ width: 48, height: 48, opacity: 0.7, background:'#000 url('+PATH+'loader.gif) no-repeat 50% 50%' }); if ( picasa.length ) { // validate the method if ( typeof Galleria.Picasa.prototype[ picasa[0] ] !== 'function' ) { Galleria.raise( picasa[0] + ' method not found in Picasa plugin' ); return load.apply( this, args ); } // validate the argument if ( !picasa[1] ) { Galleria.raise( 'No picasa argument found' ); return load.apply( this, args ); } // apply the preloader window.setTimeout(function() { self.$( 'target' ).append( loader ); },100); // create the instance p = new Galleria.Picasa(); // apply Flickr options if ( typeof self._options.picasaOptions === 'object' ) { p.setOptions( self._options.picasaOptions ); } // call the picasa method and trigger the DATA event var arg = []; if ( picasa[0] == 'useralbum' ) { arg = picasa[1].split('/'); if (arg.length != 2) { Galleria.raise( 'Picasa useralbum not correctly formatted (should be [user]/[album])'); return; } } else { arg.push( picasa[1] ); } arg.push(function(data) { self._data = data; loader.remove(); self.trigger( Galleria.DATA ); p.options.complete.call(p, data); }); p[ picasa[0] ].apply( p, arg ); } else { // if flickr array not found, pass load.apply( this, args ); } }; }( jQuery ) );
JavaScript
/** * Galleria History Plugin 2012-04-04 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function( $, window ) { /*global jQuery, Galleria, window */ Galleria.requires(1.25, 'The History Plugin requires Galleria version 1.2.5 or later.'); Galleria.History = (function() { var onloads = [], init = false, loc = window.location, doc = window.document, ie = Galleria.IE, support = 'onhashchange' in window && ( doc.mode === undefined || doc.mode > 7 ), iframe, get = function( winloc ) { if( iframe && !support && Galleria.IE ) { winloc = winloc || iframe.location; } else { winloc = loc; } return parseInt( winloc.hash.substr(2), 10 ); }, saved = get( loc ), callbacks = [], onchange = function() { $.each( callbacks, function( i, fn ) { fn.call( window, get() ); }); }, ready = function() { $.each( onloads, function(i, fn) { fn(); }); init = true; }, setHash = function( val ) { return '/' + val; }; // always remove support if IE < 8 if ( support && ie < 8 ) { support = false; } if ( !support ) { $(function() { var interval = window.setInterval(function() { var hash = get(); if ( !isNaN( hash ) && hash != saved ) { saved = hash; loc.hash = setHash( hash ); onchange(); } }, 50); if ( ie ) { $('<iframe tabindex="-1" title="empty">').hide().attr( 'src', 'about:blank' ).one('load', function() { iframe = this.contentWindow; ready(); }).insertAfter(doc.body); } else { ready(); } }); } else { ready(); } return { change: function( fn ) { callbacks.push( fn ); if( support ) { window.onhashchange = onchange; } }, set: function( val ) { if ( isNaN( val ) ) { return; } if ( !support && ie ) { this.ready(function() { var idoc = iframe.document; idoc.open(); idoc.close(); iframe.location.hash = setHash( val ); }); } loc.hash = setHash( val ); }, ready: function(fn) { if (!init) { onloads.push(fn); } else { fn(); } } }; }()); }( jQuery, this ));
JavaScript
/** * Galleria v 1.2.7 2012-04-04 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function( $ ) { /*global jQuery, navigator, Galleria:true, Image */ // some references var undef, window = this, doc = window.document, $doc = $( doc ), $win = $( window ), // native prototypes protoArray = Array.prototype, // internal constants VERSION = 1.27, DEBUG = true, TIMEOUT = 30000, DUMMY = false, NAV = navigator.userAgent.toLowerCase(), HASH = window.location.hash.replace(/#\//, ''), F = function(){}, FALSE = function() { return false; }, IE = (function() { var v = 3, div = doc.createElement( 'div' ), all = div.getElementsByTagName( 'i' ); do { div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->'; } while ( all[0] ); return v > 4 ? v : undef; }() ), DOM = function() { return { html: doc.documentElement, body: doc.body, head: doc.getElementsByTagName('head')[0], title: doc.title }; }, // list of Galleria events _eventlist = 'data ready thumbnail loadstart loadfinish image play pause progress ' + 'fullscreen_enter fullscreen_exit idle_enter idle_exit rescale ' + 'lightbox_open lightbox_close lightbox_image', _events = (function() { var evs = []; $.each( _eventlist.split(' '), function( i, ev ) { evs.push( ev ); // legacy events if ( /_/.test( ev ) ) { evs.push( ev.replace( /_/g, '' ) ); } }); return evs; }()), // legacy options // allows the old my_setting syntax and converts it to camel case _legacyOptions = function( options ) { var n; if ( typeof options !== 'object' ) { // return whatever it was... return options; } $.each( options, function( key, value ) { if ( /^[a-z]+_/.test( key ) ) { n = ''; $.each( key.split('_'), function( i, k ) { n += i > 0 ? k.substr( 0, 1 ).toUpperCase() + k.substr( 1 ) : k; }); options[ n ] = value; delete options[ key ]; } }); return options; }, _patchEvent = function( type ) { // allow 'image' instead of Galleria.IMAGE if ( $.inArray( type, _events ) > -1 ) { return Galleria[ type.toUpperCase() ]; } return type; }, // video providers _video = { youtube: { reg: /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&amp;(?:amp;)?)*v(?:&lt;[A-Z]+&gt;)?=([0-9a-zA-Z\-\_]+))/i, embed: function(id) { return 'http://www.youtube.com/embed/'+id; }, getThumb: function( id, success, fail ) { fail = fail || F; $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + id + '?v=2&alt=json-in-script&callback=?', function(data) { try { success( data.entry.media$group.media$thumbnail[0].url ); } catch(e) { fail(); } }).error(fail); } }, vimeo: { reg: /https?:\/\/(?:www\.)?(vimeo\.com)\/(?:hd#)?([0-9]+)/i, embed: function(id) { return 'http://player.vimeo.com/video/'+id; }, getThumb: function( id, success, fail ) { fail = fail || F; $.getJSON('http://vimeo.com/api/v2/video/' + id + '.json?callback=?', function(data) { try { success( data[0].thumbnail_medium ); } catch(e) { fail(); } }).error(fail); } }, dailymotion: { reg: /https?:\/\/(?:www\.)?(dailymotion\.com)\/video\/([^_]+)/, embed: function(id) { return 'http://www.dailymotion.com/embed/video/'+id; }, getThumb: function( id, success, fail ) { fail = fail || F; $.getJSON('https://api.dailymotion.com/video/'+id+'?fields=thumbnail_medium_url&callback=?', function(data) { try { success( data.thumbnail_medium_url ); } catch(e) { fail(); } }).error(fail); } } }, // utility for testing the video URL and getting the video ID _videoTest = function( url ) { var match; for ( var v in _video ) { match = url && url.match( _video[v].reg ); if( match && match.length ) { return { id: match[2], provider: v }; } } return false; }, // the internal timeouts object // provides helper methods for controlling timeouts _timeouts = { trunk: {}, add: function( id, fn, delay, loop ) { id = id || new Date().getTime(); loop = loop || false; this.clear( id ); if ( loop ) { var old = fn; fn = function() { old(); _timeouts.add( id, fn, delay ); }; } this.trunk[ id ] = window.setTimeout( fn, delay ); }, clear: function( id ) { var del = function( i ) { window.clearTimeout( this.trunk[ i ] ); delete this.trunk[ i ]; }, i; if ( !!id && id in this.trunk ) { del.call( _timeouts, id ); } else if ( typeof id === 'undefined' ) { for ( i in this.trunk ) { if ( this.trunk.hasOwnProperty( i ) ) { del.call( _timeouts, i ); } } } } }, // the internal gallery holder _galleries = [], // the internal instance holder _instances = [], // flag for errors _hasError = false, // canvas holder _canvas = false, // instance pool, holds the galleries until themeLoad is triggered _pool = [], // themeLoad trigger _themeLoad = function( theme ) { Galleria.theme = theme; // run the instances we have in the pool $.each( _pool, function( i, instance ) { if ( !instance._initialized ) { instance._init.call( instance ); } }); }, // the Utils singleton Utils = (function() { return { array : function( obj ) { return protoArray.slice.call(obj, 0); }, create : function( className, nodeName ) { nodeName = nodeName || 'div'; var elem = doc.createElement( nodeName ); elem.className = className; return elem; }, getScriptPath : function( src ) { // the currently executing script is always the last src = src || $('script:last').attr('src'); var slices = src.split('/'); if (slices.length == 1) { return ''; } slices.pop(); return slices.join('/') + '/'; }, // CSS3 transitions, added in 1.2.4 animate : (function() { // detect transition var transition = (function( style ) { var props = 'transition WebkitTransition MozTransition OTransition'.split(' '), i; // disable css3 animations in opera until stable if ( window.opera ) { return false; } for ( i = 0; props[i]; i++ ) { if ( typeof style[ props[ i ] ] !== 'undefined' ) { return props[ i ]; } } return false; }(( doc.body || doc.documentElement).style )); // map transitionend event var endEvent = { MozTransition: 'transitionend', OTransition: 'oTransitionEnd', WebkitTransition: 'webkitTransitionEnd', transition: 'transitionend' }[ transition ]; // map bezier easing conversions var easings = { _default: [0.25, 0.1, 0.25, 1], galleria: [0.645, 0.045, 0.355, 1], galleriaIn: [0.55, 0.085, 0.68, 0.53], galleriaOut: [0.25, 0.46, 0.45, 0.94], ease: [0.25, 0, 0.25, 1], linear: [0.25, 0.25, 0.75, 0.75], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }; // function for setting transition css for all browsers var setStyle = function( elem, value, suffix ) { var css = {}; suffix = suffix || 'transition'; $.each( 'webkit moz ms o'.split(' '), function() { css[ '-' + this + '-' + suffix ] = value; }); elem.css( css ); }; // clear styles var clearStyle = function( elem ) { setStyle( elem, 'none', 'transition' ); if ( Galleria.WEBKIT && Galleria.TOUCH ) { setStyle( elem, 'translate3d(0,0,0)', 'transform' ); if ( elem.data('revert') ) { elem.css( elem.data('revert') ); elem.data('revert', null); } } }; // various variables var change, strings, easing, syntax, revert, form, css; // the actual animation method return function( elem, to, options ) { // extend defaults options = $.extend({ duration: 400, complete: F, stop: false }, options); // cache jQuery instance elem = $( elem ); if ( !options.duration ) { elem.css( to ); options.complete.call( elem[0] ); return; } // fallback to jQuery's animate if transition is not supported if ( !transition ) { elem.animate(to, options); return; } // stop if ( options.stop ) { // clear the animation elem.unbind( endEvent ); clearStyle( elem ); } // see if there is a change change = false; $.each( to, function( key, val ) { css = elem.css( key ); if ( Utils.parseValue( css ) != Utils.parseValue( val ) ) { change = true; } // also add computed styles for FF elem.css( key, css ); }); if ( !change ) { window.setTimeout( function() { options.complete.call( elem[0] ); }, options.duration ); return; } // the css strings to be applied strings = []; // the easing bezier easing = options.easing in easings ? easings[ options.easing ] : easings._default; // the syntax syntax = ' ' + options.duration + 'ms' + ' cubic-bezier(' + easing.join(',') + ')'; // add a tiny timeout so that the browsers catches any css changes before animating window.setTimeout( (function(elem, endEvent, to, syntax) { return function() { // attach the end event elem.one(endEvent, (function( elem ) { return function() { // clear the animation clearStyle(elem); // run the complete method options.complete.call(elem[0]); }; }( elem ))); // do the webkit translate3d for better performance on iOS if( Galleria.WEBKIT && Galleria.TOUCH ) { revert = {}; form = [0,0,0]; $.each( ['left', 'top'], function(i, m) { if ( m in to ) { form[ i ] = ( Utils.parseValue( to[ m ] ) - Utils.parseValue(elem.css( m )) ) + 'px'; revert[ m ] = to[ m ]; delete to[ m ]; } }); if ( form[0] || form[1]) { elem.data('revert', revert); strings.push('-webkit-transform' + syntax); // 3d animate setStyle( elem, 'translate3d(' + form.join(',') + ')', 'transform'); } } // push the animation props $.each(to, function( p, val ) { strings.push(p + syntax); }); // set the animation styles setStyle( elem, strings.join(',') ); // animate elem.css( to ); }; }(elem, endEvent, to, syntax)), 2); }; }()), removeAlpha : function( elem ) { if ( IE < 9 && elem ) { var style = elem.style, currentStyle = elem.currentStyle, filter = currentStyle && currentStyle.filter || style.filter || ""; if ( /alpha/.test( filter ) ) { style.filter = filter.replace( /alpha\([^)]*\)/i, '' ); } } }, forceStyles : function( elem, styles ) { elem = $(elem); if ( elem.attr( 'style' ) ) { elem.data( 'styles', elem.attr( 'style' ) ).removeAttr( 'style' ); } elem.css( styles ); }, revertStyles : function() { $.each( Utils.array( arguments ), function( i, elem ) { elem = $( elem ); elem.removeAttr( 'style' ); elem.attr('style',''); // "fixes" webkit bug if ( elem.data( 'styles' ) ) { elem.attr( 'style', elem.data('styles') ).data( 'styles', null ); } }); }, moveOut : function( elem ) { Utils.forceStyles( elem, { position: 'absolute', left: -10000 }); }, moveIn : function() { Utils.revertStyles.apply( Utils, Utils.array( arguments ) ); }, elem : function( elem ) { if (elem instanceof $) { return { $: elem, dom: elem[0] }; } else { return { $: $(elem), dom: elem }; } }, hide : function( elem, speed, callback ) { callback = callback || F; var el = Utils.elem( elem ), $elem = el.$; elem = el.dom; // save the value if not exist if (! $elem.data('opacity') ) { $elem.data('opacity', $elem.css('opacity') ); } // always hide var style = { opacity: 0 }; if (speed) { var complete = IE < 9 && elem ? function() { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; } else { $elem.css( style ); } } }, show : function( elem, speed, callback ) { callback = callback || F; var el = Utils.elem( elem ), $elem = el.$; elem = el.dom; // bring back saved opacity var saved = parseFloat( $elem.data('opacity') ) || 1, style = { opacity: saved }; // animate or toggle if (speed) { if ( IE < 9 ) { $elem.css('opacity', 0); elem.style.visibility = 'visible'; } var complete = IE < 9 && elem ? function() { if ( style.opacity == 1 ) { Utils.removeAlpha( elem ); } callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && style.opacity == 1 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'visible'; } else { $elem.css( style ); } } }, // enhanced click for mobile devices // we bind a touchend and hijack any click event in the bubble // then we execute the click directly and save it in a separate data object for later optimizeTouch: (function() { var node, evs, fakes, travel, evt = {}, handler = function( e ) { e.preventDefault(); evt = $.extend({}, e, true); }, attach = function() { this.evt = evt; }, fake = function() { this.handler.call(node, this.evt); }; return function( elem ) { $(elem).bind('touchend', function( e ) { node = e.target; travel = true; while( node.parentNode && node != e.currentTarget && travel ) { evs = $(node).data('events'); fakes = $(node).data('fakes'); if (evs && 'click' in evs) { travel = false; e.preventDefault(); // fake the click and save the event object $(node).click(handler).click(); // remove the faked click evs.click.pop(); // attach the faked event $.each( evs.click, attach); // save the faked clicks in a new data object $(node).data('fakes', evs.click); // remove all clicks delete evs.click; } else if ( fakes ) { travel = false; e.preventDefault(); // fake all clicks $.each( fakes, fake ); } // bubble node = node.parentNode; } }); }; }()), addTimer : function() { _timeouts.add.apply( _timeouts, Utils.array( arguments ) ); return this; }, clearTimer : function() { _timeouts.clear.apply( _timeouts, Utils.array( arguments ) ); return this; }, wait : function(options) { options = $.extend({ until : FALSE, success : F, error : function() { Galleria.raise('Could not complete wait function.'); }, timeout: 3000 }, options); var start = Utils.timestamp(), elapsed, now, fn = function() { now = Utils.timestamp(); elapsed = now - start; if ( options.until( elapsed ) ) { options.success(); return false; } if (typeof options.timeout == 'number' && now >= start + options.timeout) { options.error(); return false; } window.setTimeout(fn, 10); }; window.setTimeout(fn, 10); }, toggleQuality : function( img, force ) { if ( ( IE !== 7 && IE !== 8 ) || !img || img.nodeName.toUpperCase() != 'IMG' ) { return; } if ( typeof force === 'undefined' ) { force = img.style.msInterpolationMode === 'nearest-neighbor'; } img.style.msInterpolationMode = force ? 'bicubic' : 'nearest-neighbor'; }, insertStyleTag : function( styles ) { var style = doc.createElement( 'style' ); DOM().head.appendChild( style ); if ( style.styleSheet ) { // IE style.styleSheet.cssText = styles; } else { var cssText = doc.createTextNode( styles ); style.appendChild( cssText ); } }, // a loadscript method that works for local scripts loadScript: function( url, callback ) { var done = false, script = $('<scr'+'ipt>').attr({ src: url, async: true }).get(0); // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') ) { done = true; // Handle memory leak in IE script.onload = script.onreadystatechange = null; if (typeof callback === 'function') { callback.call( this, this ); } } }; DOM().head.appendChild( script ); }, // parse anything into a number parseValue: function( val ) { if (typeof val === 'number') { return val; } else if (typeof val === 'string') { var arr = val.match(/\-?\d|\./g); return arr && arr.constructor === Array ? arr.join('')*1 : 0; } else { return 0; } }, // timestamp abstraction timestamp: function() { return new Date().getTime(); }, // this is pretty crap, but works for now // it will add a callback, but it can't guarantee that the styles can be fetched // using getComputedStyle further checking needed, possibly a dummy element loadCSS : function( href, id, callback ) { var link, ready = false, length, lastChance = function() { var fake = new Image(); fake.onload = fake.onerror = function(e) { fake = null; ready = true; }; fake.src = href; }; // look for manual css $('link[rel=stylesheet]').each(function() { if ( new RegExp( href ).test( this.href ) ) { link = this; return false; } }); if ( typeof id === 'function' ) { callback = id; id = undef; } callback = callback || F; // dirty // if already present, return if ( link ) { callback.call( link, link ); return link; } // save the length of stylesheets to check against length = doc.styleSheets.length; // check for existing id if( $('#'+id).length ) { $('#'+id).attr('href', href); length--; ready = true; } else { link = $( '<link>' ).attr({ rel: 'stylesheet', href: href, id: id }).get(0); window.setTimeout(function() { var styles = $('link[rel="stylesheet"], style'); if ( styles.length ) { styles.get(0).parentNode.insertBefore( link, styles[0] ); } else { DOM().head.appendChild( link ); } if ( IE ) { // IE has a limit of 31 stylesheets in one document if( length >= 31 ) { Galleria.raise( 'You have reached the browser stylesheet limit (31)', true ); return; } link.onreadystatechange = function(e) { if ( !ready && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') ) { ready = true; } }; } else { // final test via ajax var dum = doc.createElement('a'), loc = window.location; dum.href = href; if ( !( /file/.test( loc.protocol ) ) && loc.hostname == dum.hostname && loc.port == dum.port && loc.protocol == dum.protocol ) { // Same origin policy should apply $.ajax({ url: href, success: function() { ready = true; }, error: lastChance }); } else { lastChance(); } } }, 10); } if ( typeof callback === 'function' ) { Utils.wait({ until: function() { return ready && doc.styleSheets.length > length; }, success: function() { window.setTimeout( function() { callback.call( link, link ); }, 100); }, error: function() { Galleria.raise( 'Theme CSS could not load', true ); }, timeout: 10000 }); } return link; } }; }()), // the transitions holder _transitions = (function() { var _slide = function(params, complete, fade, door) { var easing = this.getOptions('easing'), distance = this.getStageWidth(), from = { left: distance * ( params.rewind ? -1 : 1 ) }, to = { left: 0 }; if ( fade ) { from.opacity = 0; to.opacity = 1; } else { from.opacity = 1; } $(params.next).css(from); Utils.animate(params.next, to, { duration: params.speed, complete: (function( elems ) { return function() { complete(); elems.css({ left: 0 }); }; }( $( params.next ).add( params.prev ) )), queue: false, easing: easing }); if (door) { params.rewind = !params.rewind; } if (params.prev) { from = { left: 0 }; to = { left: distance * ( params.rewind ? 1 : -1 ) }; if ( fade ) { from.opacity = 1; to.opacity = 0; } $(params.prev).css(from); Utils.animate(params.prev, to, { duration: params.speed, queue: false, easing: easing, complete: function() { $(this).css('opacity', 0); } }); } }; return { fade: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }).show(); Utils.animate(params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); if (params.prev) { $(params.prev).css('opacity',1).show(); Utils.animate(params.prev, { opacity: 0 },{ duration: params.speed }); } }, flash: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }); if (params.prev) { Utils.animate( params.prev, { opacity: 0 },{ duration: params.speed/2, complete: function() { Utils.animate( params.next, { opacity:1 },{ duration: params.speed, complete: complete }); } }); } else { Utils.animate( params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); } }, pulse: function(params, complete) { if (params.prev) { $(params.prev).hide(); } $(params.next).css({ opacity: 0, left: 0 }).show(); Utils.animate(params.next, { opacity:1 },{ duration: params.speed, complete: complete }); }, slide: function(params, complete) { _slide.apply( this, Utils.array( arguments ) ); }, fadeslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [true] ) ); }, doorslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [false, true] ) ); } }; }()); /** The main Galleria class @class @constructor @example var gallery = new Galleria(); @author http://aino.se @requires jQuery */ Galleria = function() { var self = this; // internal options this._options = {}; // flag for controlling play/pause this._playing = false; // internal interval for slideshow this._playtime = 5000; // internal variable for the currently active image this._active = null; // the internal queue, arrayified this._queue = { length: 0 }; // the internal data array this._data = []; // the internal dom collection this._dom = {}; // the internal thumbnails array this._thumbnails = []; // the internal layers array this._layers = []; // internal init flag this._initialized = false; // internal firstrun flag this._firstrun = false; // global stagewidth/height this._stageWidth = 0; this._stageHeight = 0; // target holder this._target = undef; // instance id this._id = parseInt(Math.random()*10000, 10); // add some elements var divs = 'container stage images image-nav image-nav-left image-nav-right ' + 'info info-text info-title info-description ' + 'thumbnails thumbnails-list thumbnails-container thumb-nav-left thumb-nav-right ' + 'loader counter tooltip', spans = 'current total'; $.each( divs.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId ); }); $.each( spans.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId, 'span' ); }); // the internal keyboard object // keeps reference of the keybinds and provides helper methods for binding keys var keyboard = this._keyboard = { keys : { 'UP': 38, 'DOWN': 40, 'LEFT': 37, 'RIGHT': 39, 'RETURN': 13, 'ESCAPE': 27, 'BACKSPACE': 8, 'SPACE': 32 }, map : {}, bound: false, press: function(e) { var key = e.keyCode || e.which; if ( key in keyboard.map && typeof keyboard.map[key] === 'function' ) { keyboard.map[key].call(self, e); } }, attach: function(map) { var key, up; for( key in map ) { if ( map.hasOwnProperty( key ) ) { up = key.toUpperCase(); if ( up in keyboard.keys ) { keyboard.map[ keyboard.keys[up] ] = map[key]; } else { keyboard.map[ up ] = map[key]; } } } if ( !keyboard.bound ) { keyboard.bound = true; $doc.bind('keydown', keyboard.press); } }, detach: function() { keyboard.bound = false; keyboard.map = {}; $doc.unbind('keydown', keyboard.press); } }; // internal controls for keeping track of active / inactive images var controls = this._controls = { 0: undef, 1: undef, active : 0, swap : function() { controls.active = controls.active ? 0 : 1; }, getActive : function() { return controls[ controls.active ]; }, getNext : function() { return controls[ 1 - controls.active ]; } }; // internal carousel object var carousel = this._carousel = { // shortcuts next: self.$('thumb-nav-right'), prev: self.$('thumb-nav-left'), // cache the width width: 0, // track the current position current: 0, // cache max value max: 0, // save all hooks for each width in an array hooks: [], // update the carousel // you can run this method anytime, f.ex on window.resize update: function() { var w = 0, h = 0, hooks = [0]; $.each( self._thumbnails, function( i, thumb ) { if ( thumb.ready ) { w += thumb.outerWidth || $( thumb.container ).outerWidth( true ); hooks[ i+1 ] = w; h = Math.max( h, thumb.outerHeight || $( thumb.container).outerHeight( true ) ); } }); self.$( 'thumbnails' ).css({ width: w, height: h }); carousel.max = w; carousel.hooks = hooks; carousel.width = self.$( 'thumbnails-list' ).width(); carousel.setClasses(); self.$( 'thumbnails-container' ).toggleClass( 'galleria-carousel', w > carousel.width ); // one extra calculation carousel.width = self.$( 'thumbnails-list' ).width(); // todo: fix so the carousel moves to the left }, bindControls: function() { var i; carousel.next.bind( 'click', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i < carousel.hooks.length; i++ ) { if ( carousel.hooks[i] - carousel.hooks[ carousel.current ] > carousel.width ) { carousel.set(i - 2); break; } } } else { carousel.set( carousel.current + self._options.carouselSteps); } }); carousel.prev.bind( 'click', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i >= 0; i-- ) { if ( carousel.hooks[ carousel.current ] - carousel.hooks[i] > carousel.width ) { carousel.set( i + 2 ); break; } else if ( i === 0 ) { carousel.set( 0 ); break; } } } else { carousel.set( carousel.current - self._options.carouselSteps ); } }); }, // calculate and set positions set: function( i ) { i = Math.max( i, 0 ); while ( carousel.hooks[i - 1] + carousel.width >= carousel.max && i >= 0 ) { i--; } carousel.current = i; carousel.animate(); }, // get the last position getLast: function(i) { return ( i || carousel.current ) - 1; }, // follow the active image follow: function(i) { //don't follow if position fits if ( i === 0 || i === carousel.hooks.length - 2 ) { carousel.set( i ); return; } // calculate last position var last = carousel.current; while( carousel.hooks[last] - carousel.hooks[ carousel.current ] < carousel.width && last <= carousel.hooks.length ) { last ++; } // set position if ( i - 1 < carousel.current ) { carousel.set( i - 1 ); } else if ( i + 2 > last) { carousel.set( i - last + carousel.current + 2 ); } }, // helper for setting disabled classes setClasses: function() { carousel.prev.toggleClass( 'disabled', !carousel.current ); carousel.next.toggleClass( 'disabled', carousel.hooks[ carousel.current ] + carousel.width >= carousel.max ); }, // the animation method animate: function(to) { carousel.setClasses(); var num = carousel.hooks[ carousel.current ] * -1; if ( isNaN( num ) ) { return; } Utils.animate(self.get( 'thumbnails' ), { left: num },{ duration: self._options.carouselSpeed, easing: self._options.easing, queue: false }); } }; // tooltip control // added in 1.2 var tooltip = this._tooltip = { initialized : false, open: false, timer: 'tooltip' + self._id, swapTimer: 'swap' + self._id, init: function() { tooltip.initialized = true; var css = '.galleria-tooltip{padding:3px 8px;max-width:50%;background:#ffe;color:#000;z-index:3;position:absolute;font-size:11px;line-height:1.3' + 'opacity:0;box-shadow:0 0 2px rgba(0,0,0,.4);-moz-box-shadow:0 0 2px rgba(0,0,0,.4);-webkit-box-shadow:0 0 2px rgba(0,0,0,.4);}'; Utils.insertStyleTag(css); self.$( 'tooltip' ).css('opacity', 0.8); Utils.hide( self.get('tooltip') ); }, // move handler move: function( e ) { var mouseX = self.getMousePosition(e).x, mouseY = self.getMousePosition(e).y, $elem = self.$( 'tooltip' ), x = mouseX, y = mouseY, height = $elem.outerHeight( true ) + 1, width = $elem.outerWidth( true ), limitY = height + 15; var maxX = self.$( 'container').width() - width - 2, maxY = self.$( 'container').height() - height - 2; if ( !isNaN(x) && !isNaN(y) ) { x += 10; y -= 30; x = Math.max( 0, Math.min( maxX, x ) ); y = Math.max( 0, Math.min( maxY, y ) ); if( mouseY < limitY ) { y = limitY; } $elem.css({ left: x, top: y }); } }, // bind elements to the tooltip // you can bind multiple elementIDs using { elemID : function } or { elemID : string } // you can also bind single DOM elements using bind(elem, string) bind: function( elem, value ) { // todo: revise if alternative tooltip is needed for mobile devices if (Galleria.TOUCH) { return; } if (! tooltip.initialized ) { tooltip.init(); } var hover = function( elem, value) { tooltip.define( elem, value ); $( elem ).hover(function() { Utils.clearTimer( tooltip.swapTimer ); self.$('container').unbind( 'mousemove', tooltip.move ).bind( 'mousemove', tooltip.move ).trigger( 'mousemove' ); tooltip.show( elem ); Utils.addTimer( tooltip.timer, function() { self.$( 'tooltip' ).stop().show().animate({ opacity:1 }); tooltip.open = true; }, tooltip.open ? 0 : 500); }, function() { self.$( 'container' ).unbind( 'mousemove', tooltip.move ); Utils.clearTimer( tooltip.timer ); self.$( 'tooltip' ).stop().animate({ opacity: 0 }, 200, function() { self.$( 'tooltip' ).hide(); Utils.addTimer( tooltip.swapTimer, function() { tooltip.open = false; }, 1000); }); }).click(function() { $( this ).trigger( 'mouseout' ); }); }; if ( typeof value === 'string' ) { hover( ( elem in self._dom ? self.get( elem ) : elem ), value ); } else { // asume elemID here $.each( elem, function( elemID, val ) { hover( self.get(elemID), val ); }); } }, show: function( elem ) { elem = $( elem in self._dom ? self.get(elem) : elem ); var text = elem.data( 'tt' ), mouseup = function( e ) { // attach a tiny settimeout to make sure the new tooltip is filled window.setTimeout( (function( ev ) { return function() { tooltip.move( ev ); }; }( e )), 10); elem.unbind( 'mouseup', mouseup ); }; text = typeof text === 'function' ? text() : text; if ( ! text ) { return; } self.$( 'tooltip' ).html( text.replace(/\s/, '&nbsp;') ); // trigger mousemove on mouseup in case of click elem.bind( 'mouseup', mouseup ); }, define: function( elem, value ) { // we store functions, not strings if (typeof value !== 'function') { var s = value; value = function() { return s; }; } elem = $( elem in self._dom ? self.get(elem) : elem ).data('tt', value); tooltip.show( elem ); } }; // internal fullscreen control var fullscreen = this._fullscreen = { scrolled: 0, crop: undef, transition: undef, active: false, keymap: self._keyboard.map, // The native fullscreen handler os: { callback: F, support: (function() { var html = DOM().html; return html.requestFullscreen || html.mozRequestFullScreen || html.webkitRequestFullScreen; }()), enter: function( callback ) { fullscreen.os.callback = callback || F; var html = DOM().html; if ( html.requestFullscreen ) { html.requestFullscreen(); } else if ( html.mozRequestFullScreen ) { html.mozRequestFullScreen(); } else if ( html.webkitRequestFullScreen ) { html.webkitRequestFullScreen(); } }, exit: function( callback ) { fullscreen.os.callback = callback || F; if ( doc.exitFullscreen ) { doc.exitFullscreen(); } else if ( doc.mozCancelFullScreen ) { doc.mozCancelFullScreen(); } else if ( doc.webkitCancelFullScreen ) { doc.webkitCancelFullScreen(); } }, listen: function() { if ( !fullscreen.os.support ) { return; } var handler = function() { if ( doc.fullscreen || doc.mozFullScreen || doc.webkitIsFullScreen ) { fullscreen._enter( fullscreen.os.callback ); } else { fullscreen._exit( fullscreen.os.callback ); } }; doc.addEventListener( 'fullscreenchange', handler, false ); doc.addEventListener( 'mozfullscreenchange', handler, false ); doc.addEventListener( 'webkitfullscreenchange', handler, false ); } }, enter: function( callback ) { if ( self._options.trueFullscreen && fullscreen.os.support ) { fullscreen.os.enter( callback ); } else { fullscreen._enter( callback ); } }, _enter: function( callback ) { fullscreen.active = true; // hide the image until rescale is complete Utils.hide( self.getActiveImage() ); self.$( 'container' ).addClass( 'fullscreen' ); fullscreen.scrolled = $win.scrollTop(); // begin styleforce Utils.forceStyles(self.get('container'), { position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', zIndex: 10000 }); var htmlbody = { height: '100%', overflow: 'hidden', margin:0, padding:0 }, data = self.getData(), options = self._options; Utils.forceStyles( DOM().html, htmlbody ); Utils.forceStyles( DOM().body, htmlbody ); // temporarily attach some keys // save the old ones first in a cloned object fullscreen.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: self.exitFullscreen, right: self.next, left: self.prev }); // temporarily save the crop fullscreen.crop = options.imageCrop; // set fullscreen options if ( options.fullscreenCrop != undef ) { options.imageCrop = options.fullscreenCrop; } // swap to big image if it's different from the display image if ( data && data.big && data.image !== data.big ) { var big = new Galleria.Picture(), cached = big.isCached( data.big ), index = self.getIndex(), thumb = self._thumbnails[ index ]; self.trigger( { type: Galleria.LOADSTART, cached: cached, rewind: false, index: index, imageTarget: self.getActiveImage(), thumbTarget: thumb, galleriaData: data }); big.load( data.big, function( big ) { self._scaleImage( big, { complete: function( big ) { self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: index, rewind: false, imageTarget: big.image, thumbTarget: thumb }); var image = self._controls.getActive().image; if ( image ) { $( image ).width( big.image.width ).height( big.image.height ) .attr( 'style', $( big.image ).attr('style') ) .attr( 'src', big.image.src ); } } }); }); } // init the first rescale and attach callbacks self.rescale(function() { Utils.addTimer(false, function() { // show the image after 50 ms Utils.show( self.getActiveImage() ); if (typeof callback === 'function') { callback.call( self ); } }, 100); self.trigger( Galleria.FULLSCREEN_ENTER ); }); // bind the scaling to the resize event $win.resize( function() { fullscreen.scale(); } ); }, scale : function() { self.rescale(); }, exit: function( callback ) { if ( self._options.trueFullscreen && fullscreen.os.support ) { fullscreen.os.exit( callback ); } else { fullscreen._exit( callback ); } }, _exit: function( callback ) { fullscreen.active = false; Utils.hide( self.getActiveImage() ); self.$('container').removeClass( 'fullscreen' ); // revert all styles Utils.revertStyles( self.get('container'), DOM().html, DOM().body ); // scroll back window.scrollTo(0, fullscreen.scrolled); // detach all keyboard events and apply the old keymap self.detachKeyboard(); self.attachKeyboard( fullscreen.keymap ); // bring back cached options self._options.imageCrop = fullscreen.crop; //self._options.transition = fullscreen.transition; // return to original image var big = self.getData().big, image = self._controls.getActive().image; if ( !self.getData().iframe && image && big && big == image.src ) { window.setTimeout(function(src) { return function() { image.src = src; }; }( self.getData().image ), 1 ); } self.rescale(function() { Utils.addTimer(false, function() { // show the image after 50 ms Utils.show( self.getActiveImage() ); if ( typeof callback === 'function' ) { callback.call( self ); } $win.trigger( 'resize' ); }, 50); self.trigger( Galleria.FULLSCREEN_EXIT ); }); $win.unbind('resize', fullscreen.scale); } }; // invoke the native listeners fullscreen.os.listen(); // the internal idle object for controlling idle states var idle = this._idle = { timer: 'idle' + self._id, trunk: [], bound: false, add: function(elem, to) { if (!elem) { return; } if (!idle.bound) { idle.addEvent(); } elem = $(elem); var from = {}, style; for ( style in to ) { if ( to.hasOwnProperty( style ) ) { from[ style ] = elem.css( style ); } } elem.data('idle', { from: from, to: to, complete: true, busy: false }); idle.addTimer(); idle.trunk.push(elem); }, remove: function(elem) { elem = jQuery(elem); $.each(idle.trunk, function(i, el) { if ( el && el.length && !el.not(elem).length ) { self._idle.show(elem); self._idle.trunk.splice(i, 1); } }); if (!idle.trunk.length) { idle.removeEvent(); Utils.clearTimer( idle.timer ); } }, addEvent : function() { idle.bound = true; self.$('container').bind('mousemove click', idle.showAll ); }, removeEvent : function() { idle.bound = false; self.$('container').unbind('mousemove click', idle.showAll ); }, addTimer : function() { Utils.addTimer( idle.timer, function() { idle.hide(); }, self._options.idleTime ); }, hide : function() { if ( !self._options.idleMode || self.getIndex() === false || self.getData().iframe ) { return; } self.trigger( Galleria.IDLE_ENTER ); $.each( idle.trunk, function(i, elem) { var data = elem.data('idle'); if (! data) { return; } elem.data('idle').complete = false; Utils.animate( elem, data.to, { duration: self._options.idleSpeed }); }); }, showAll : function() { Utils.clearTimer( idle.timer ); $.each( idle.trunk, function( i, elem ) { idle.show( elem ); }); }, show: function(elem) { var data = elem.data('idle'); if (!data.busy && !data.complete) { data.busy = true; self.trigger( Galleria.IDLE_EXIT ); Utils.clearTimer( idle.timer ); Utils.animate( elem, data.from, { duration: self._options.idleSpeed/2, complete: function() { $(this).data('idle').busy = false; $(this).data('idle').complete = true; } }); } idle.addTimer(); } }; // internal lightbox object // creates a predesigned lightbox for simple popups of images in galleria var lightbox = this._lightbox = { width : 0, height : 0, initialized : false, active : null, image : null, elems : {}, keymap: false, init : function() { // trigger the event self.trigger( Galleria.LIGHTBOX_OPEN ); if ( lightbox.initialized ) { return; } lightbox.initialized = true; // create some elements to work with var elems = 'overlay box content shadow title info close prevholder prev nextholder next counter image', el = {}, op = self._options, css = '', abs = 'position:absolute;', prefix = 'lightbox-', cssMap = { overlay: 'position:fixed;display:none;opacity:'+op.overlayOpacity+';filter:alpha(opacity='+(op.overlayOpacity*100)+ ');top:0;left:0;width:100%;height:100%;background:'+op.overlayBackground+';z-index:99990', box: 'position:fixed;display:none;width:400px;height:400px;top:50%;left:50%;margin-top:-200px;margin-left:-200px;z-index:99991', shadow: abs+'background:#000;width:100%;height:100%;', content: abs+'background-color:#fff;top:10px;left:10px;right:10px;bottom:10px;overflow:hidden', info: abs+'bottom:10px;left:10px;right:10px;color:#444;font:11px/13px arial,sans-serif;height:13px', close: abs+'top:10px;right:10px;height:20px;width:20px;background:#fff;text-align:center;cursor:pointer;color:#444;font:16px/22px arial,sans-serif;z-index:99999', image: abs+'top:10px;left:10px;right:10px;bottom:30px;overflow:hidden;display:block;', prevholder: abs+'width:50%;top:0;bottom:40px;cursor:pointer;', nextholder: abs+'width:50%;top:0;bottom:40px;right:-1px;cursor:pointer;', prev: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;left:20px;display:none;text-align:center;color:#000;font:bold 16px/36px arial,sans-serif', next: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;right:20px;left:auto;display:none;font:bold 16px/36px arial,sans-serif;text-align:center;color:#000', title: 'float:left', counter: 'float:right;margin-left:8px;' }, hover = function(elem) { return elem.hover( function() { $(this).css( 'color', '#bbb' ); }, function() { $(this).css( 'color', '#444' ); } ); }, appends = {}; // IE8 fix for IE's transparent background event "feature" if ( IE && IE > 7 ) { cssMap.nextholder += 'background:#000;filter:alpha(opacity=0);'; cssMap.prevholder += 'background:#000;filter:alpha(opacity=0);'; } // create and insert CSS $.each(cssMap, function( key, value ) { css += '.galleria-'+prefix+key+'{'+value+'}'; }); css += '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'prevholder,'+ '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'nextholder{'+ 'width:100px;height:100px;top:50%;margin-top:-70px}'; Utils.insertStyleTag( css ); // create the elements $.each(elems.split(' '), function( i, elemId ) { self.addElement( 'lightbox-' + elemId ); el[ elemId ] = lightbox.elems[ elemId ] = self.get( 'lightbox-' + elemId ); }); // initiate the image lightbox.image = new Galleria.Picture(); // append the elements $.each({ box: 'shadow content close prevholder nextholder', info: 'title counter', content: 'info image', prevholder: 'prev', nextholder: 'next' }, function( key, val ) { var arr = []; $.each( val.split(' '), function( i, prop ) { arr.push( prefix + prop ); }); appends[ prefix+key ] = arr; }); self.append( appends ); $( el.image ).append( lightbox.image.container ); $( DOM().body ).append( el.overlay, el.box ); Utils.optimizeTouch( el.box ); // add the prev/next nav and bind some controls hover( $( el.close ).bind( 'click', lightbox.hide ).html('&#215;') ); $.each( ['Prev','Next'], function(i, dir) { var $d = $( el[ dir.toLowerCase() ] ).html( /v/.test( dir ) ? '&#8249;&nbsp;' : '&nbsp;&#8250;' ), $e = $( el[ dir.toLowerCase()+'holder'] ); $e.bind( 'click', function() { lightbox[ 'show' + dir ](); }); // IE7 and touch devices will simply show the nav if ( IE < 8 || Galleria.TOUCH ) { $d.show(); return; } $e.hover( function() { $d.show(); }, function(e) { $d.stop().fadeOut( 200 ); }); }); $( el.overlay ).bind( 'click', lightbox.hide ); // the lightbox animation is slow on ipad if ( Galleria.IPAD ) { self._options.lightboxTransitionSpeed = 0; } }, rescale: function(event) { // calculate var width = Math.min( $win.width()-40, lightbox.width ), height = Math.min( $win.height()-60, lightbox.height ), ratio = Math.min( width / lightbox.width, height / lightbox.height ), destWidth = Math.round( lightbox.width * ratio ) + 40, destHeight = Math.round( lightbox.height * ratio ) + 60, to = { width: destWidth, height: destHeight, 'margin-top': Math.ceil( destHeight / 2 ) *- 1, 'margin-left': Math.ceil( destWidth / 2 ) *- 1 }; // if rescale event, don't animate if ( event ) { $( lightbox.elems.box ).css( to ); } else { $( lightbox.elems.box ).animate( to, { duration: self._options.lightboxTransitionSpeed, easing: self._options.easing, complete: function() { var image = lightbox.image, speed = self._options.lightboxFadeSpeed; self.trigger({ type: Galleria.LIGHTBOX_IMAGE, imageTarget: image.image }); $( image.container ).show(); $( image.image ).animate({ opacity: 1 }, speed); Utils.show( lightbox.elems.info, speed ); } }); } }, hide: function() { // remove the image lightbox.image.image = null; $win.unbind('resize', lightbox.rescale); $( lightbox.elems.box ).hide(); Utils.hide( lightbox.elems.info ); self.detachKeyboard(); self.attachKeyboard( lightbox.keymap ); lightbox.keymap = false; Utils.hide( lightbox.elems.overlay, 200, function() { $( this ).hide().css( 'opacity', self._options.overlayOpacity ); self.trigger( Galleria.LIGHTBOX_CLOSE ); }); }, showNext: function() { lightbox.show( self.getNext( lightbox.active ) ); }, showPrev: function() { lightbox.show( self.getPrev( lightbox.active ) ); }, show: function(index) { lightbox.active = index = typeof index === 'number' ? index : self.getIndex() || 0; if ( !lightbox.initialized ) { lightbox.init(); } // temporarily attach some keys // save the old ones first in a cloned object if ( !lightbox.keymap ) { lightbox.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: lightbox.hide, right: lightbox.showNext, left: lightbox.showPrev }); } $win.unbind('resize', lightbox.rescale ); var data = self.getData(index), total = self.getDataLength(), n = self.getNext( index ), ndata, p, i; Utils.hide( lightbox.elems.info ); try { for ( i = self._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = self.getData( n ); p.preload( 'big' in ndata ? ndata.big : ndata.image ); n = self.getNext( n ); } } catch(e) {} lightbox.image.isIframe = !!data.iframe; $(lightbox.elems.box).toggleClass( 'iframe', !!data.iframe ); lightbox.image.load( data.iframe || data.big || data.image, function( image ) { lightbox.width = image.isIframe ? $(window).width() : image.original.width; lightbox.height = image.isIframe ? $(window).height() : image.original.height; $( image.image ).css({ width: image.isIframe ? '100%' : '100.1%', height: image.isIframe ? '100%' : '100.1%', top: 0, zIndex: 99998, opacity: 0, visibility: 'visible' }); lightbox.elems.title.innerHTML = data.title || ''; lightbox.elems.counter.innerHTML = (index + 1) + ' / ' + total; $win.resize( lightbox.rescale ); lightbox.rescale(); }); $( lightbox.elems.overlay ).show().css( 'visibility', 'visible' ); $( lightbox.elems.box ).show(); } }; return this; }; // end Galleria constructor Galleria.prototype = { // bring back the constructor reference constructor: Galleria, /** Use this function to initialize the gallery and start loading. Should only be called once per instance. @param {HTMLElement} target The target element @param {Object} options The gallery options @returns Instance */ init: function( target, options ) { var self = this; options = _legacyOptions( options ); // save the original ingredients this._original = { target: target, options: options, data: null }; // save the target here this._target = this._dom.target = target.nodeName ? target : $( target ).get(0); // save the original content for destruction this._original.html = this._target.innerHTML; // push the instance _instances.push( this ); // raise error if no target is detected if ( !this._target ) { Galleria.raise('Target not found', true); return; } // apply options this._options = { autoplay: false, carousel: true, carouselFollow: true, carouselSpeed: 400, carouselSteps: 'auto', clicknext: false, dailymotion: { foreground: '%23EEEEEE', highlight: '%235BCEC5', background: '%23222222', logo: 0, hideInfos: 1 }, dataConfig : function( elem ) { return {}; }, dataSelector: 'img', dataSource: this._target, debug: undef, dummy: undef, // 1.2.5 easing: 'galleria', extend: function(options) {}, fullscreenCrop: undef, // 1.2.5 fullscreenDoubleTap: true, // 1.2.4 toggles fullscreen on double-tap for touch devices fullscreenTransition: undef, // 1.2.6 height: 0, idleMode: true, // 1.2.4 toggles idleMode idleTime: 3000, idleSpeed: 200, imageCrop: false, imageMargin: 0, imagePan: false, imagePanSmoothness: 12, imagePosition: '50%', imageTimeout: undef, // 1.2.5 initialTransition: undef, // 1.2.4, replaces transitionInitial keepSource: false, layerFollow: true, // 1.2.5 lightbox: false, // 1.2.3 lightboxFadeSpeed: 200, lightboxTransitionSpeed: 200, linkSourceImages: true, maxScaleRatio: undef, minScaleRatio: undef, overlayOpacity: 0.85, overlayBackground: '#0b0b0b', pauseOnInteraction: true, popupLinks: false, preload: 2, queue: true, responsive: false, show: 0, showInfo: true, showCounter: true, showImagenav: true, swipe: true, // 1.2.4 thumbCrop: true, thumbEventType: 'click', thumbFit: true, thumbMargin: 0, thumbQuality: 'auto', thumbnails: true, touchTransition: undef, // 1.2.6 transition: 'fade', transitionInitial: undef, // legacy, deprecate in 1.3. Use initialTransition instead. transitionSpeed: 400, trueFullscreen: true, // 1.2.7 useCanvas: false, // 1.2.4 vimeo: { title: 0, byline: 0, portrait: 0, color: 'aaaaaa' }, wait: 5000, // 1.2.7 width: 'auto', youtube: { modestbranding: 1, autohide: 1, color: 'white', hd: 1, rel: 0, showinfo: 0 } }; // legacy support for transitionInitial this._options.initialTransition = this._options.initialTransition || this._options.transitionInitial; // turn off debug if ( options && options.debug === false ) { DEBUG = false; } // set timeout if ( options && typeof options.imageTimeout === 'number' ) { TIMEOUT = options.imageTimeout; } // set dummy if ( options && typeof options.dummy === 'string' ) { DUMMY = options.dummy; } // hide all content $( this._target ).children().hide(); // now we just have to wait for the theme... if ( typeof Galleria.theme === 'object' ) { this._init(); } else { // push the instance into the pool and run it when the theme is ready _pool.push( this ); } return this; }, // this method should only be called once per instance // for manipulation of data, use the .load method _init: function() { var self = this, options = this._options; if ( this._initialized ) { Galleria.raise( 'Init failed: Gallery instance already initialized.' ); return this; } this._initialized = true; if ( !Galleria.theme ) { Galleria.raise( 'Init failed: No theme found.', true ); return this; } // merge the theme & caller options $.extend( true, options, Galleria.theme.defaults, this._original.options, Galleria.configure.options ); // check for canvas support (function( can ) { if ( !( 'getContext' in can ) ) { can = null; return; } _canvas = _canvas || { elem: can, context: can.getContext( '2d' ), cache: {}, length: 0 }; }( doc.createElement( 'canvas' ) ) ); // bind the gallery to run when data is ready this.bind( Galleria.DATA, function() { // Warn for quirks mode if ( Galleria.QUIRK ) { Galleria.raise('Your page is in Quirks mode, Galleria may not render correctly. Please validate your HTML.'); } // save the new data this._original.data = this._data; // lets show the counter here this.get('total').innerHTML = this.getDataLength(); // cache the container var $container = this.$( 'container' ); // the gallery is ready, let's just wait for the css var num = { width: 0, height: 0 }; var testHeight = function() { return self.$( 'stage' ).height(); }; // check container and thumbnail height Utils.wait({ until: function() { // keep trying to get the value num = self._getWH(); $container.width( num.width ).height( num.height ); return testHeight() && num.width && num.height > 50; }, success: function() { self._width = num.width; self._height = num.height; // for some strange reason, webkit needs a single setTimeout to play ball if ( Galleria.WEBKIT ) { window.setTimeout( function() { self._run(); }, 1); } else { self._run(); } }, error: function() { // Height was probably not set, raise hard errors if ( testHeight() ) { Galleria.raise('Could not extract sufficient width/height of the gallery container. Traced measures: width:' + num.width + 'px, height: ' + num.height + 'px.', true); } else { Galleria.raise('Could not extract a stage height from the CSS. Traced height: ' + testHeight() + 'px.', true); } }, timeout: typeof this._options.wait == 'number' ? this._options.wait : false }); }); // build the gallery frame this.append({ 'info-text' : ['info-title', 'info-description'], 'info' : ['info-text'], 'image-nav' : ['image-nav-right', 'image-nav-left'], 'stage' : ['images', 'loader', 'counter', 'image-nav'], 'thumbnails-list' : ['thumbnails'], 'thumbnails-container' : ['thumb-nav-left', 'thumbnails-list', 'thumb-nav-right'], 'container' : ['stage', 'thumbnails-container', 'info', 'tooltip'] }); Utils.hide( this.$( 'counter' ).append( this.get( 'current' ), doc.createTextNode(' / '), this.get( 'total' ) ) ); this.setCounter('&#8211;'); Utils.hide( self.get('tooltip') ); // add a notouch class on the container to prevent unwanted :hovers on touch devices this.$( 'container' ).addClass( Galleria.TOUCH ? 'touch' : 'notouch' ); // add images to the controls $.each( new Array(2), function( i ) { // create a new Picture instance var image = new Galleria.Picture(); // apply some styles, create & prepend overlay $( image.container ).css({ position: 'absolute', top: 0, left: 0 }).prepend( self._layers[i] = $( Utils.create('galleria-layer') ).css({ position: 'absolute', top:0, left:0, right:0, bottom:0, zIndex:2 })[0] ); // append the image self.$( 'images' ).append( image.container ); // reload the controls self._controls[i] = image; }); // some forced generic styling this.$( 'images' ).css({ position: 'relative', top: 0, left: 0, width: '100%', height: '100%' }); this.$( 'thumbnails, thumbnails-list' ).css({ overflow: 'hidden', position: 'relative' }); // bind image navigation arrows this.$( 'image-nav-right, image-nav-left' ).bind( 'click', function(e) { // tune the clicknext option if ( options.clicknext ) { e.stopPropagation(); } // pause if options is set if ( options.pauseOnInteraction ) { self.pause(); } // navigate var fn = /right/.test( this.className ) ? 'next' : 'prev'; self[ fn ](); }); // hide controls if chosen to $.each( ['info','counter','image-nav'], function( i, el ) { if ( options[ 'show' + el.substr(0,1).toUpperCase() + el.substr(1).replace(/-/,'') ] === false ) { Utils.moveOut( self.get( el.toLowerCase() ) ); } }); // load up target content this.load(); // now it's usually safe to remove the content // IE will never stop loading if we remove it, so let's keep it hidden for IE (it's usually fast enough anyway) if ( !options.keepSource && !IE ) { this._target.innerHTML = ''; } // re-append the errors, if they happened before clearing if ( this.get( 'errors' ) ) { this.appendChild( 'target', 'errors' ); } // append the gallery frame this.appendChild( 'target', 'container' ); // parse the carousel on each thumb load if ( options.carousel ) { var count = 0, show = options.show; this.bind( Galleria.THUMBNAIL, function() { this.updateCarousel(); if ( ++count == this.getDataLength() && typeof show == 'number' && show > 0 ) { this._carousel.follow( show ); } }); } // bind window resize for responsiveness if ( options.responsive ) { $win.bind( 'resize', function() { if ( !self.isFullscreen() ) { self.resize(); } }); } // bind swipe gesture if ( options.swipe ) { (function( images ) { var swipeStart = [0,0], swipeStop = [0,0], limitX = 30, limitY = 100, multi = false, tid = 0, data, ev = { start: 'touchstart', move: 'touchmove', stop: 'touchend' }, getData = function(e) { return e.originalEvent.touches ? e.originalEvent.touches[0] : e; }, moveHandler = function( e ) { if ( e.originalEvent.touches && e.originalEvent.touches.length > 1 ) { return; } data = getData( e ); swipeStop = [ data.pageX, data.pageY ]; if ( !swipeStart[0] ) { swipeStart = swipeStop; } if ( Math.abs( swipeStart[0] - swipeStop[0] ) > 10 ) { e.preventDefault(); } }, upHandler = function( e ) { images.unbind( ev.move, moveHandler ); // if multitouch (possibly zooming), abort if ( ( e.originalEvent.touches && e.originalEvent.touches.length ) || multi ) { multi = !multi; return; } if ( Utils.timestamp() - tid < 1000 && Math.abs( swipeStart[0] - swipeStop[0] ) > limitX && Math.abs( swipeStart[1] - swipeStop[1] ) < limitY ) { e.preventDefault(); self[ swipeStart[0] > swipeStop[0] ? 'next' : 'prev' ](); } swipeStart = swipeStop = [0,0]; }; images.bind(ev.start, function(e) { if ( e.originalEvent.touches && e.originalEvent.touches.length > 1 ) { return; } data = getData(e); tid = Utils.timestamp(); swipeStart = swipeStop = [ data.pageX, data.pageY ]; images.bind(ev.move, moveHandler ).one(ev.stop, upHandler); }); }( self.$( 'images' ) )); // double-tap/click fullscreen toggle if ( options.fullscreenDoubleTap ) { this.$( 'stage' ).bind( 'touchstart', (function() { var last, cx, cy, lx, ly, now, getData = function(e) { return e.originalEvent.touches ? e.originalEvent.touches[0] : e; }; return function(e) { now = Galleria.utils.timestamp(); cx = getData(e).pageX; cy = getData(e).pageY; if ( ( now - last < 500 ) && ( cx - lx < 20) && ( cy - ly < 20) ) { self.toggleFullscreen(); e.preventDefault(); self.$( 'stage' ).unbind( 'touchend', arguments.callee ); return; } last = now; lx = cx; ly = cy; }; }())); } } // optimize touch for container Utils.optimizeTouch( this.get( 'container' ) ); // bind the ons $.each( Galleria.on.binds, function(i, bind) { self.bind( bind.type, bind.callback ); }); return this; }, // parse width & height from CSS or options _getWH : function() { var $container = this.$( 'container' ), $target = this.$( 'target' ), self = this, num = {}, arr; $.each(['width', 'height'], function( i, m ) { // first check if options is set if ( self._options[ m ] && typeof self._options[ m ] === 'number') { num[ m ] = self._options[ m ]; } else { arr = [ Utils.parseValue( $container.css( m ) ), // the container css height Utils.parseValue( $target.css( m ) ), // the target css height $container[ m ](), // the container jQuery method $target[ m ]() // the target jQuery method ]; // if first time, include the min-width & min-height if ( !self[ '_'+m ] ) { arr.splice(arr.length, Utils.parseValue( $container.css( 'min-'+m ) ), Utils.parseValue( $target.css( 'min-'+m ) ) ); } // else extract the measures from different sources and grab the highest value num[ m ] = Math.max.apply( Math, arr ); } }); // allow setting a height ratio instead of exact value // useful when doing responsive galleries if ( self._options.height && self._options.height < 2 ) { num.height = num.width * self._options.height; } return num; }, // Creates the thumbnails and carousel // can be used at any time, f.ex when the data object is manipulated _createThumbnails : function() { this.get( 'total' ).innerHTML = this.getDataLength(); var i, src, thumb, data, special, $container, self = this, o = this._options, // get previously active thumbnail, if exists active = (function() { var a = self.$('thumbnails').find('.active'); if ( !a.length ) { return false; } return a.find('img').attr('src'); }()), // cache the thumbnail option optval = typeof o.thumbnails === 'string' ? o.thumbnails.toLowerCase() : null, // move some data into the instance // for some reason, jQuery cant handle css(property) when zooming in FF, breaking the gallery // so we resort to getComputedStyle for browsers who support it getStyle = function( prop ) { return doc.defaultView && doc.defaultView.getComputedStyle ? doc.defaultView.getComputedStyle( thumb.container, null )[ prop ] : $container.css( prop ); }, fake = function(image, index, container) { return function() { $( container ).append( image ); self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: image, index: index, galleriaData: self.getData( index ) }); }; }, onThumbEvent = function( e ) { // pause if option is set if ( o.pauseOnInteraction ) { self.pause(); } // extract the index from the data var index = $( e.currentTarget ).data( 'index' ); if ( self.getIndex() !== index ) { self.show( index ); } e.preventDefault(); }, onThumbLoad = function( thumb ) { // scale when ready thumb.scale({ width: thumb.data.width, height: thumb.data.height, crop: o.thumbCrop, margin: o.thumbMargin, canvas: o.useCanvas, complete: function( thumb ) { // shrink thumbnails to fit var top = ['left', 'top'], arr = ['Width', 'Height'], m, css, data = self.getData( thumb.index ), special = data.thumb.split(':'); // calculate shrinked positions $.each(arr, function( i, measure ) { m = measure.toLowerCase(); if ( (o.thumbCrop !== true || o.thumbCrop === m ) && o.thumbFit ) { css = {}; css[ m ] = thumb[ m ]; $( thumb.container ).css( css ); css = {}; css[ top[ i ] ] = 0; $( thumb.image ).css( css ); } // cache outer measures thumb[ 'outer' + measure ] = $( thumb.container )[ 'outer' + measure ]( true ); }); // set high quality if downscale is moderate Utils.toggleQuality( thumb.image, o.thumbQuality === true || ( o.thumbQuality === 'auto' && thumb.original.width < thumb.width * 3 ) ); // get "special" thumbs from provider if( data.iframe && special.length == 2 && special[0] in _video ) { _video[ special[0] ].getThumb( special[1], (function(img) { return function(src) { img.src = src; }; }( thumb.image ) )); } // trigger the THUMBNAIL event self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: thumb.image, index: thumb.data.order, galleriaData: self.getData( thumb.data.order ) }); } }); }; this._thumbnails = []; this.$( 'thumbnails' ).empty(); // loop through data and create thumbnails for( i = 0; this._data[ i ]; i++ ) { data = this._data[ i ]; if ( o.thumbnails === true && (data.thumb || data.image) ) { // add a new Picture instance thumb = new Galleria.Picture(i); // save the index thumb.index = i; // get source from thumb or image src = data.thumb || data.image; // append the thumbnail this.$( 'thumbnails' ).append( thumb.container ); // cache the container $container = $( thumb.container ); thumb.data = { width : Utils.parseValue( getStyle( 'width' ) ), height : Utils.parseValue( getStyle( 'height' ) ), order : i }; // grab & reset size for smoother thumbnail loads if ( o.thumbFit && o.thumbCrop !== true ) { $container.css( { width: 'auto', height: 'auto' } ); } else { $container.css( { width: thumb.data.width, height: thumb.data.height } ); } // load the thumbnail special = src.split(':'); if ( special.length == 2 && special[0] in _video ) { thumb.load('data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw%3D%3D', { height: thumb.data.height, width: thumb.data.height*1.25 }, onThumbLoad); } else { thumb.load( src, onThumbLoad ); } // preload all images here if ( o.preload === 'all' ) { thumb.preload( data.image ); } // create empty spans if thumbnails is set to 'empty' } else if ( data.iframe || optval === 'empty' || optval === 'numbers' ) { thumb = { container: Utils.create( 'galleria-image' ), image: Utils.create( 'img', 'span' ), ready: true }; // create numbered thumbnails if ( optval === 'numbers' ) { $( thumb.image ).text( i + 1 ); } if( data.iframe ) { $( thumb.image ).addClass('iframe'); } this.$( 'thumbnails' ).append( thumb.container ); // we need to "fake" a loading delay before we append and trigger // 50+ should be enough window.setTimeout( ( fake )( thumb.image, i, thumb.container ), 50 + ( i*20 ) ); // create null object to silent errors } else { thumb = { container: null, image: null }; } // add events for thumbnails // you can control the event type using thumb_event_type // we'll add the same event to the source if it's kept $( thumb.container ).add( o.keepSource && o.linkSourceImages ? data.original : null ) .data('index', i).bind( o.thumbEventType, onThumbEvent ); if (active === src) { $( thumb.container ).addClass( 'active' ); } this._thumbnails.push( thumb ); } }, // the internal _run method should be called after loading data into galleria // makes sure the gallery has proper measurements before postrun & ready _run : function() { var self = this; self._createThumbnails(); // make sure we have a stageHeight && stageWidth Utils.wait({ timeout: 10000, until: function() { // Opera crap if ( Galleria.OPERA ) { self.$( 'stage' ).css( 'display', 'inline-block' ); } self._stageWidth = self.$( 'stage' ).width(); self._stageHeight = self.$( 'stage' ).height(); return( self._stageWidth && self._stageHeight > 50 ); // what is an acceptable height? }, success: function() { // save the instance _galleries.push( self ); // postrun some stuff after the gallery is ready // show counter Utils.show( self.get('counter') ); // bind carousel nav if ( self._options.carousel ) { self._carousel.bindControls(); } // start autoplay if ( self._options.autoplay ) { self.pause(); if ( typeof self._options.autoplay === 'number' ) { self._playtime = self._options.autoplay; } self.trigger( Galleria.PLAY ); self._playing = true; } // if second load, just do the show and return if ( self._firstrun ) { if ( typeof self._options.show === 'number' ) { self.show( self._options.show ); } return; } self._firstrun = true; // initialize the History plugin if ( Galleria.History ) { // bind the show method Galleria.History.change(function( value ) { // if ID is NaN, the user pressed back from the first image // return to previous address if ( isNaN( value ) ) { window.history.go(-1); // else show the image } else { self.show( value, undef, true ); } }); } self.trigger( Galleria.READY ); // call the theme init method Galleria.theme.init.call( self, self._options ); // Trigger Galleria.ready $.each( Galleria.ready.callbacks, function() { this.call( self, self._options ); }); // call the extend option self._options.extend.call( self, self._options ); // show the initial image // first test for permalinks in history if ( /^[0-9]{1,4}$/.test( HASH ) && Galleria.History ) { self.show( HASH, undef, true ); } else if( self._data[ self._options.show ] ) { self.show( self._options.show ); } }, error: function() { Galleria.raise('Stage width or height is too small to show the gallery. Traced measures: width:' + self._stageWidth + 'px, height: ' + self._stageHeight + 'px.', true); } }); }, /** Loads data into the gallery. You can call this method on an existing gallery to reload the gallery with new data. @param {Array|string} [source] Optional JSON array of data or selector of where to find data in the document. Defaults to the Galleria target or dataSource option. @param {string} [selector] Optional element selector of what elements to parse. Defaults to 'img'. @param {Function} [config] Optional function to modify the data extraction proceedure from the selector. See the dataConfig option for more information. @returns Instance */ load : function( source, selector, config ) { var self = this; // empty the data array this._data = []; // empty the thumbnails this._thumbnails = []; this.$('thumbnails').empty(); // shorten the arguments if ( typeof selector === 'function' ) { config = selector; selector = null; } // use the source set by target source = source || this._options.dataSource; // use selector set by option selector = selector || this._options.dataSelector; // use the dataConfig set by option config = config || this._options.dataConfig; // if source is a true object, make it into an array if( /^function Object/.test( source.constructor ) ) { source = [source]; } // check if the data is an array already if ( source.constructor === Array ) { if ( this.validate( source ) ) { this._data = source; this._parseData().trigger( Galleria.DATA ); } else { Galleria.raise( 'Load failed: JSON Array not valid.' ); } return this; } // add .video and .iframe to the selector (1.2.7) selector += ',.video,.iframe'; // loop through images and set data $( source ).find( selector ).each( function( i, elem ) { elem = $( elem ); var data = {}, parent = elem.parent(), href = parent.attr( 'href' ), rel = parent.attr( 'rel' ); if( href && ( elem[0].nodeName == 'IMG' || elem.hasClass('video') ) && _videoTest( href ) ) { data.video = href; } else if( href && elem.hasClass('iframe') ) { data.iframe = href; } else { data.image = data.big = href; } if ( rel ) { data.big = rel; } // alternative extraction from HTML5 data attribute, added in 1.2.7 $.each( 'big title description link layer'.split(' '), function( i, val ) { if ( elem.data(val) ) { data[ val ] = elem.data(val); } }); // mix default extractions with the hrefs and config // and push it into the data array self._data.push( $.extend({ title: elem.attr('title') || '', thumb: elem.attr('src'), image: elem.attr('src'), big: elem.attr('src'), description: elem.attr('alt') || '', link: elem.attr('longdesc'), original: elem.get(0) // saved as a reference }, data, config( elem ) ) ); }); // trigger the DATA event and return if ( this.getDataLength() ) { this._parseData().trigger( Galleria.DATA ); } else { Galleria.raise('Load failed: no data found.'); } return this; }, // make sure the data works properly _parseData : function() { var self = this, current; $.each( this._data, function( i, data ) { current = self._data[ i ]; // copy image as thumb if no thumb exists if ( 'thumb' in data === false ) { current.thumb = data.image; } // copy image as big image if no biggie exists if ( !'big' in data ) { current.big = data.image; } // parse video if ( 'video' in data ) { var result = _videoTest( data.video ); if ( result ) { current.iframe = _video[ result.provider ].embed( result.id ) + (function() { // add options if ( typeof self._options[ result.provider ] == 'object' ) { var str = '?', arr = []; $.each( self._options[ result.provider ], function( key, val ) { arr.push( key + '=' + val ); }); // small youtube specifics, perhaps move to _video later if ( result.provider == 'youtube' ) { arr = ['wmode=opaque'].concat(arr); } return str + arr.join('&'); } return ''; }()); delete current.video; if( !('thumb' in current) || !current.thumb ) { current.thumb = result.provider+':'+result.id; } } } }); return this; }, /** Destroy the Galleria instance and recover the original content @example this.destroy(); @returns Instance */ destroy: function() { this.get('target').innerHTML = this._original.html; return this; }, /** Adds and/or removes images from the gallery Works just like Array.splice https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice @example this.splice( 2, 4 ); // removes 4 images after the second image @returns Instance */ splice: function() { var self = this, args = Utils.array( arguments ); window.setTimeout(function() { protoArray.splice.apply( self._data, args ); self._parseData()._createThumbnails(); },2); return self; }, /** Append images to the gallery Works just like Array.push https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push @example this.push({ image: 'image1.jpg' }); // appends the image to the gallery @returns Instance */ push: function() { var self = this, args = Utils.array( arguments ); window.setTimeout(function() { protoArray.push.apply( self._data, args ); self._parseData()._createThumbnails(); },2); return self; }, _getActive: function() { return this._controls.getActive(); }, validate : function( data ) { // todo: validate a custom data array return true; }, /** Bind any event to Galleria @param {string} type The Event type to listen for @param {Function} fn The function to execute when the event is triggered @example this.bind( 'image', function() { Galleria.log('image shown') }); @returns Instance */ bind : function(type, fn) { // allow 'image' instead of Galleria.IMAGE type = _patchEvent( type ); this.$( 'container' ).bind( type, this.proxy(fn) ); return this; }, /** Unbind any event to Galleria @param {string} type The Event type to forget @returns Instance */ unbind : function(type) { type = _patchEvent( type ); this.$( 'container' ).unbind( type ); return this; }, /** Manually trigger a Galleria event @param {string} type The Event to trigger @returns Instance */ trigger : function( type ) { type = typeof type === 'object' ? $.extend( type, { scope: this } ) : { type: _patchEvent( type ), scope: this }; this.$( 'container' ).trigger( type ); return this; }, /** Assign an "idle state" to any element. The idle state will be applied after a certain amount of idle time Useful to hide f.ex navigation when the gallery is inactive @param {HTMLElement|string} elem The Dom node or selector to apply the idle state to @param {Object} styles the CSS styles to apply @example addIdleState( this.get('image-nav'), { opacity: 0 }); @example addIdleState( '.galleria-image-nav', { top: -200 }); @returns Instance */ addIdleState: function( elem, styles ) { this._idle.add.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Removes any idle state previously set using addIdleState() @param {HTMLElement|string} elem The Dom node or selector to remove the idle state from. @returns Instance */ removeIdleState: function( elem ) { this._idle.remove.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Force Galleria to enter idle mode. @returns Instance */ enterIdleMode: function() { this._idle.hide(); return this; }, /** Force Galleria to exit idle mode. @returns Instance */ exitIdleMode: function() { this._idle.showAll(); return this; }, /** Enter FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ enterFullscreen: function( callback ) { this._fullscreen.enter.apply( this, Utils.array( arguments ) ); return this; }, /** Exits FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ exitFullscreen: function( callback ) { this._fullscreen.exit.apply( this, Utils.array( arguments ) ); return this; }, /** Toggle FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied or removed. @returns Instance */ toggleFullscreen: function( callback ) { this._fullscreen[ this.isFullscreen() ? 'exit' : 'enter'].apply( this, Utils.array( arguments ) ); return this; }, /** Adds a tooltip to any element. You can also call this method with an object as argument with elemID:value pairs to apply tooltips to (see examples) @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @example this.bindTooltip( this.get('thumbnails'), 'My thumbnails'); @example this.bindTooltip( this.get('thumbnails'), function() { return 'My thumbs' }); @example this.bindTooltip( { image_nav: 'Navigation' }); @returns Instance */ bindTooltip: function( elem, value ) { this._tooltip.bind.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Note: this method is deprecated. Use refreshTooltip() instead. Redefine a tooltip. Use this if you want to re-apply a tooltip value to an already bound tooltip element. @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @returns Instance */ defineTooltip: function( elem, value ) { this._tooltip.define.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Refresh a tooltip value. Use this if you want to change the tooltip value at runtime, f.ex if you have a play/pause toggle. @param {HTMLElement} elem The DOM Node that has a tooltip that should be refreshed @returns Instance */ refreshTooltip: function( elem ) { this._tooltip.show.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Open a pre-designed lightbox with the currently active image. You can control some visuals using gallery options. @returns Instance */ openLightbox: function() { this._lightbox.show.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Close the lightbox. @returns Instance */ closeLightbox: function() { this._lightbox.hide.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Get the currently active image element. @returns {HTMLElement} The image element */ getActiveImage: function() { return this._getActive().image || undef; }, /** Get the currently active thumbnail element. @returns {HTMLElement} The thumbnail element */ getActiveThumb: function() { return this._thumbnails[ this._active ].image || undef; }, /** Get the mouse position relative to the gallery container @param e The mouse event @example var gallery = this; $(document).mousemove(function(e) { console.log( gallery.getMousePosition(e).x ); }); @returns {Object} Object with x & y of the relative mouse postion */ getMousePosition : function(e) { return { x: e.pageX - this.$( 'container' ).offset().left, y: e.pageY - this.$( 'container' ).offset().top }; }, /** Adds a panning effect to the image @param [img] The optional image element. If not specified it takes the currently active image @returns Instance */ addPan : function( img ) { if ( this._options.imageCrop === false ) { return; } img = $( img || this.getActiveImage() ); // define some variables and methods var self = this, x = img.width() / 2, y = img.height() / 2, destX = parseInt( img.css( 'left' ), 10 ), destY = parseInt( img.css( 'top' ), 10 ), curX = destX || 0, curY = destY || 0, distX = 0, distY = 0, active = false, ts = Utils.timestamp(), cache = 0, move = 0, // positions the image position = function( dist, cur, pos ) { if ( dist > 0 ) { move = Math.round( Math.max( dist * -1, Math.min( 0, cur ) ) ); if ( cache !== move ) { cache = move; if ( IE === 8 ) { // scroll is faster for IE img.parent()[ 'scroll' + pos ]( move * -1 ); } else { var css = {}; css[ pos.toLowerCase() ] = move; img.css(css); } } } }, // calculates mouse position after 50ms calculate = function(e) { if (Utils.timestamp() - ts < 50) { return; } active = true; x = self.getMousePosition(e).x; y = self.getMousePosition(e).y; }, // the main loop to check loop = function(e) { if (!active) { return; } distX = img.width() - self._stageWidth; distY = img.height() - self._stageHeight; destX = x / self._stageWidth * distX * -1; destY = y / self._stageHeight * distY * -1; curX += ( destX - curX ) / self._options.imagePanSmoothness; curY += ( destY - curY ) / self._options.imagePanSmoothness; position( distY, curY, 'Top' ); position( distX, curX, 'Left' ); }; // we need to use scroll in IE8 to speed things up if ( IE === 8 ) { img.parent().scrollTop( curY * -1 ).scrollLeft( curX * -1 ); img.css({ top: 0, left: 0 }); } // unbind and bind event this.$( 'stage' ).unbind( 'mousemove', calculate ).bind( 'mousemove', calculate ); // loop the loop Utils.addTimer( 'pan' + self._id, loop, 50, true); return this; }, /** Brings the scope into any callback @param fn The callback to bring the scope into @param [scope] Optional scope to bring @example $('#fullscreen').click( this.proxy(function() { this.enterFullscreen(); }) ) @returns {Function} Return the callback with the gallery scope */ proxy : function( fn, scope ) { if ( typeof fn !== 'function' ) { return F; } scope = scope || this; return function() { return fn.apply( scope, Utils.array( arguments ) ); }; }, /** Removes the panning effect set by addPan() @returns Instance */ removePan: function() { // todo: doublecheck IE8 this.$( 'stage' ).unbind( 'mousemove' ); Utils.clearTimer( 'pan' + this._id ); return this; }, /** Adds an element to the Galleria DOM array. When you add an element here, you can access it using element ID in many API calls @param {string} id The element ID you wish to use. You can add many elements by adding more arguments. @example addElement('mybutton'); @example addElement('mybutton','mylink'); @returns Instance */ addElement : function( id ) { var dom = this._dom; $.each( Utils.array(arguments), function( i, blueprint ) { dom[ blueprint ] = Utils.create( 'galleria-' + blueprint ); }); return this; }, /** Attach keyboard events to Galleria @param {Object} map The map object of events. Possible keys are 'UP', 'DOWN', 'LEFT', 'RIGHT', 'RETURN', 'ESCAPE', 'BACKSPACE', and 'SPACE'. @example this.attachKeyboard({ right: this.next, left: this.prev, up: function() { console.log( 'up key pressed' ) } }); @returns Instance */ attachKeyboard : function( map ) { this._keyboard.attach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Detach all keyboard events to Galleria @returns Instance */ detachKeyboard : function() { this._keyboard.detach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Fast helper for appending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be appended @param {string} childID the element ID that should be appended @example this.addElement('myElement'); this.appendChild( 'info', 'myElement' ); @returns Instance */ appendChild : function( parentID, childID ) { this.$( parentID ).append( this.get( childID ) || childID ); return this; }, /** Fast helper for prepending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be prepended @param {string} childID the element ID that should be prepended @example this.addElement('myElement'); this.prependChild( 'info', 'myElement' ); @returns Instance */ prependChild : function( parentID, childID ) { this.$( parentID ).prepend( this.get( childID ) || childID ); return this; }, /** Remove an element by blueprint @param {string} elemID The element to be removed. You can remove multiple elements by adding arguments. @returns Instance */ remove : function( elemID ) { this.$( Utils.array( arguments ).join(',') ).remove(); return this; }, // a fast helper for building dom structures // leave this out of the API for now append : function( data ) { var i, j; for( i in data ) { if ( data.hasOwnProperty( i ) ) { if ( data[i].constructor === Array ) { for( j = 0; data[i][j]; j++ ) { this.appendChild( i, data[i][j] ); } } else { this.appendChild( i, data[i] ); } } } return this; }, // an internal helper for scaling according to options _scaleImage : function( image, options ) { image = image || this._controls.getActive(); // janpub (JH) fix: // image might be unselected yet // e.g. when external logics rescales the gallery on window resize events if( !image ) { return; } var self = this, complete, scaleLayer = function( img ) { $( img.container ).children(':first').css({ top: Math.max(0, Utils.parseValue( img.image.style.top )), left: Math.max(0, Utils.parseValue( img.image.style.left )), width: Utils.parseValue( img.image.width ), height: Utils.parseValue( img.image.height ) }); }; options = $.extend({ width: this._stageWidth, height: this._stageHeight, crop: this._options.imageCrop, max: this._options.maxScaleRatio, min: this._options.minScaleRatio, margin: this._options.imageMargin, position: this._options.imagePosition }, options ); if ( this._options.layerFollow && this._options.imageCrop !== true ) { if ( typeof options.complete == 'function' ) { complete = options.complete; options.complete = function() { complete.call( image, image ); scaleLayer( image ); }; } else { options.complete = scaleLayer; } } else { $( image.container ).children(':first').css({ top: 0, left: 0 }); } image.scale( options ); return this; }, /** Updates the carousel, useful if you resize the gallery and want to re-check if the carousel nav is needed. @returns Instance */ updateCarousel : function() { this._carousel.update(); return this; }, /** Resize the entire gallery container @param {Object} [measures] Optional object with width/height specified @param {Function} [complete] The callback to be called when the scaling is complete @returns Instance */ resize : function( measures, complete ) { if ( typeof measures == 'function' ) { complete = measures; measures = undef; } measures = $.extend( { width:0, height:0 }, measures ); var self = this, $container = this.$( 'container' ), aspect = this._options.responsive == 'aspect' && ( !measures.width || !measures.height ), ratio; $.each( measures, function( m, val ) { if ( !val ) { $container[ m ]( 'auto' ); measures[ m ] = self._getWH()[ m ]; } }); // experimental aspect option, not documented yet. Use ratio-based height instead! if ( aspect ) { ratio = Math.min( measures.width/this._width, measures.height/this._height ); } $.each( measures, function( m, val ) { $container[ m ]( ratio ? ratio * self[ '_' + m ] : val ); }); return this.rescale( complete ); }, /** Rescales the gallery @param {number} width The target width @param {number} height The target height @param {Function} complete The callback to be called when the scaling is complete @returns Instance */ rescale : function( width, height, complete ) { var self = this; // allow rescale(fn) if ( typeof width === 'function' ) { complete = width; width = undef; } var scale = function() { // set stagewidth self._stageWidth = width || self.$( 'stage' ).width(); self._stageHeight = height || self.$( 'stage' ).height(); // scale the active image self._scaleImage(); if ( self._options.carousel ) { self.updateCarousel(); } self.trigger( Galleria.RESCALE ); if ( typeof complete === 'function' ) { complete.call( self ); } }; if ( Galleria.WEBKIT && !Galleria.TOUCH && !width && !height ) { Utils.addTimer( false, scale, 10 );// webkit is too fast } else { scale.call( self ); } return this; }, /** Refreshes the gallery. Useful if you change image options at runtime and want to apply the changes to the active image. @returns Instance */ refreshImage : function() { this._scaleImage(); if ( this._options.imagePan ) { this.addPan(); } return this; }, /** Shows an image by index @param {number|boolean} index The index to show @param {Boolean} rewind A boolean that should be true if you want the transition to go back @returns Instance */ show : function( index, rewind, _history ) { // do nothing if index is false or queue is false and transition is in progress if ( index === false || ( !this._options.queue && this._queue.stalled ) ) { return; } index = Math.max( 0, Math.min( parseInt( index, 10 ), this.getDataLength() - 1 ) ); rewind = typeof rewind !== 'undefined' ? !!rewind : index < this.getIndex(); _history = _history || false; // do the history thing and return if ( !_history && Galleria.History ) { Galleria.History.set( index.toString() ); return; } this._active = index; protoArray.push.call( this._queue, { index : index, rewind : rewind }); if ( !this._queue.stalled ) { this._show(); } return this; }, // the internal _show method does the actual showing _show : function() { // shortcuts var self = this, queue = this._queue[ 0 ], data = this.getData( queue.index ); if ( !data ) { return; } var src = data.iframe || ( this.isFullscreen() && 'big' in data ? data.big : data.image ), // use big image if fullscreen mode active = this._controls.getActive(), next = this._controls.getNext(), cached = next.isCached( src ), thumb = this._thumbnails[ queue.index ], mousetrigger = function() { $( next.image ).trigger( 'mouseup' ); }; // to be fired when loading & transition is complete: var complete = (function( data, next, active, queue, thumb ) { return function() { var win; // remove stalled self._queue.stalled = false; // optimize quality Utils.toggleQuality( next.image, self._options.imageQuality ); // remove old layer self._layers[ self._controls.active ].innerHTML = ''; // swap $( active.container ).css({ zIndex: 0, opacity: 0 }).show(); if( active.isIframe ) { $( active.container ).find( 'iframe' ).remove(); } self.$('container').toggleClass('iframe', !!data.iframe); $( next.container ).css({ zIndex: 1, left: 0, top: 0 }).show(); self._controls.swap(); // add pan according to option if ( self._options.imagePan ) { self.addPan( next.image ); } // make the image link or add lightbox // link takes precedence over lightbox if both are detected if ( data.link || self._options.lightbox || self._options.clicknext ) { $( next.image ).css({ cursor: 'pointer' }).bind( 'mouseup', function() { // clicknext if ( self._options.clicknext && !Galleria.TOUCH ) { if ( self._options.pauseOnInteraction ) { self.pause(); } self.next(); return; } // popup link if ( data.link ) { if ( self._options.popupLinks ) { win = window.open( data.link, '_blank' ); } else { window.location.href = data.link; } return; } if ( self._options.lightbox ) { self.openLightbox(); } }); } // remove the queued image protoArray.shift.call( self._queue ); // if we still have images in the queue, show it if ( self._queue.length ) { self._show(); } // check if we are playing self._playCheck(); // trigger IMAGE event self.trigger({ type: Galleria.IMAGE, index: queue.index, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); }; }( data, next, active, queue, thumb )); // let the carousel follow if ( this._options.carousel && this._options.carouselFollow ) { this._carousel.follow( queue.index ); } // preload images if ( this._options.preload ) { var p, i, n = this.getNext(), ndata; try { for ( i = this._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = self.getData( n ); p.preload( this.isFullscreen() && 'big' in ndata ? ndata.big : ndata.image ); n = self.getNext( n ); } } catch(e) {} } // show the next image, just in case Utils.show( next.container ); next.isIframe = !!data.iframe; // add active classes $( self._thumbnails[ queue.index ].container ) .addClass( 'active' ) .siblings( '.active' ) .removeClass( 'active' ); // trigger the LOADSTART event self.trigger( { type: Galleria.LOADSTART, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); // begin loading the next image next.load( src, function( next ) { // add layer HTML var layer = $( self._layers[ 1-self._controls.active ] ).html( data.layer || '' ).hide(); self._scaleImage( next, { complete: function( next ) { // toggle low quality for IE if ( 'image' in active ) { Utils.toggleQuality( active.image, false ); } Utils.toggleQuality( next.image, false ); // stall the queue self._queue.stalled = true; // remove the image panning, if applied // TODO: rethink if this is necessary self.removePan(); // set the captions and counter self.setInfo( queue.index ); self.setCounter( queue.index ); // show the layer now if ( data.layer ) { layer.show(); // inherit click events set on image if ( data.link || self._options.lightbox || self._options.clicknext ) { layer.css( 'cursor', 'pointer' ).unbind( 'mouseup' ).mouseup( mousetrigger ); } } // trigger the LOADFINISH event self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: self._thumbnails[ queue.index ].image, galleriaData: self.getData( queue.index ) }); var transition = self._options.transition; // can JavaScript loop through objects in order? yes. $.each({ initial: active.image === null, touch: Galleria.TOUCH, fullscreen: self.isFullscreen() }, function( type, arg ) { if ( arg && self._options[ type + 'Transition' ] !== undef ) { transition = self._options[ type + 'Transition' ]; return false; } }); // validate the transition if ( transition in _transitions === false ) { complete(); } else { var params = { prev: active.container, next: next.container, rewind: queue.rewind, speed: self._options.transitionSpeed || 400 }; // call the transition function and send some stuff _transitions[ transition ].call(self, params, complete ); } } }); }); }, /** Gets the next index @param {number} [base] Optional starting point @returns {number} the next index, or the first if you are at the first (looping) */ getNext : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === this.getDataLength() - 1 ? 0 : base + 1; }, /** Gets the previous index @param {number} [base] Optional starting point @returns {number} the previous index, or the last if you are at the first (looping) */ getPrev : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === 0 ? this.getDataLength() - 1 : base - 1; }, /** Shows the next image in line @returns Instance */ next : function() { if ( this.getDataLength() > 1 ) { this.show( this.getNext(), false ); } return this; }, /** Shows the previous image in line @returns Instance */ prev : function() { if ( this.getDataLength() > 1 ) { this.show( this.getPrev(), true ); } return this; }, /** Retrieve a DOM element by element ID @param {string} elemId The delement ID to fetch @returns {HTMLElement} The elements DOM node or null if not found. */ get : function( elemId ) { return elemId in this._dom ? this._dom[ elemId ] : null; }, /** Retrieve a data object @param {number} index The data index to retrieve. If no index specified it will take the currently active image @returns {Object} The data object */ getData : function( index ) { return index in this._data ? this._data[ index ] : this._data[ this._active ]; }, /** Retrieve the number of data items @returns {number} The data length */ getDataLength : function() { return this._data.length; }, /** Retrieve the currently active index @returns {number|boolean} The active index or false if none found */ getIndex : function() { return typeof this._active === 'number' ? this._active : false; }, /** Retrieve the stage height @returns {number} The stage height */ getStageHeight : function() { return this._stageHeight; }, /** Retrieve the stage width @returns {number} The stage width */ getStageWidth : function() { return this._stageWidth; }, /** Retrieve the option @param {string} key The option key to retrieve. If no key specified it will return all options in an object. @returns option or options */ getOptions : function( key ) { return typeof key === 'undefined' ? this._options : this._options[ key ]; }, /** Set options to the instance. You can set options using a key & value argument or a single object argument (see examples) @param {string} key The option key @param {string} value the the options value @example setOptions( 'autoplay', true ) @example setOptions({ autoplay: true }); @returns Instance */ setOptions : function( key, value ) { if ( typeof key === 'object' ) { $.extend( this._options, key ); } else { this._options[ key ] = value; } return this; }, /** Starts playing the slideshow @param {number} delay Sets the slideshow interval in milliseconds. If you set it once, you can just call play() and get the same interval the next time. @returns Instance */ play : function( delay ) { this._playing = true; this._playtime = delay || this._playtime; this._playCheck(); this.trigger( Galleria.PLAY ); return this; }, /** Stops the slideshow if currently playing @returns Instance */ pause : function() { this._playing = false; this.trigger( Galleria.PAUSE ); return this; }, /** Toggle between play and pause events. @param {number} delay Sets the slideshow interval in milliseconds. @returns Instance */ playToggle : function( delay ) { return ( this._playing ) ? this.pause() : this.play( delay ); }, /** Checks if the gallery is currently playing @returns {Boolean} */ isPlaying : function() { return this._playing; }, /** Checks if the gallery is currently in fullscreen mode @returns {Boolean} */ isFullscreen : function() { return this._fullscreen.active; }, _playCheck : function() { var self = this, played = 0, interval = 20, now = Utils.timestamp(), timer_id = 'play' + this._id; if ( this._playing ) { Utils.clearTimer( timer_id ); var fn = function() { played = Utils.timestamp() - now; if ( played >= self._playtime && self._playing ) { Utils.clearTimer( timer_id ); self.next(); return; } if ( self._playing ) { // trigger the PROGRESS event self.trigger({ type: Galleria.PROGRESS, percent: Math.ceil( played / self._playtime * 100 ), seconds: Math.floor( played / 1000 ), milliseconds: played }); Utils.addTimer( timer_id, fn, interval ); } }; Utils.addTimer( timer_id, fn, interval ); } }, /** Modify the slideshow delay @param {number} delay the number of milliseconds between slides, @returns Instance */ setPlaytime: function( delay ) { this._playtime = delay; return this; }, setIndex: function( val ) { this._active = val; return this; }, /** Manually modify the counter @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index @returns Instance */ setCounter: function( index ) { if ( typeof index === 'number' ) { index++; } else if ( typeof index === 'undefined' ) { index = this.getIndex()+1; } this.get( 'current' ).innerHTML = index; if ( IE ) { // weird IE bug var count = this.$( 'counter' ), opacity = count.css( 'opacity' ); if ( parseInt( opacity, 10 ) === 1) { Utils.removeAlpha( count[0] ); } else { this.$( 'counter' ).css( 'opacity', opacity ); } } return this; }, /** Manually set captions @param {number} [index] Optional data index to fectch and apply as caption, if no index found it assumes the currently active index @returns Instance */ setInfo : function( index ) { var self = this, data = this.getData( index ); $.each( ['title','description'], function( i, type ) { var elem = self.$( 'info-' + type ); if ( !!data[type] ) { elem[ data[ type ].length ? 'show' : 'hide' ]().html( data[ type ] ); } else { elem.empty().hide(); } }); return this; }, /** Checks if the data contains any captions @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index. @returns {boolean} */ hasInfo : function( index ) { var check = 'title description'.split(' '), i; for ( i = 0; check[i]; i++ ) { if ( !!this.getData( index )[ check[i] ] ) { return true; } } return false; }, jQuery : function( str ) { var self = this, ret = []; $.each( str.split(','), function( i, elemId ) { elemId = $.trim( elemId ); if ( self.get( elemId ) ) { ret.push( elemId ); } }); var jQ = $( self.get( ret.shift() ) ); $.each( ret, function( i, elemId ) { jQ = jQ.add( self.get( elemId ) ); }); return jQ; }, /** Converts element IDs into a jQuery collection You can call for multiple IDs separated with commas. @param {string} str One or more element IDs (comma-separated) @returns jQuery @example this.$('info,container').hide(); */ $ : function( str ) { return this.jQuery.apply( this, Utils.array( arguments ) ); } }; // End of Galleria prototype // Add events as static variables $.each( _events, function( i, ev ) { // legacy events var type = /_/.test( ev ) ? ev.replace( /_/g, '' ) : ev; Galleria[ ev.toUpperCase() ] = 'galleria.'+type; } ); $.extend( Galleria, { // Browser helpers IE9: IE === 9, IE8: IE === 8, IE7: IE === 7, IE6: IE === 6, IE: IE, WEBKIT: /webkit/.test( NAV ), CHROME: /chrome/.test( NAV ), SAFARI: /safari/.test( NAV ) && !(/chrome/.test( NAV )), QUIRK: ( IE && doc.compatMode && doc.compatMode === "BackCompat" ), MAC: /mac/.test( navigator.platform.toLowerCase() ), OPERA: !!window.opera, IPHONE: /iphone/.test( NAV ), IPAD: /ipad/.test( NAV ), ANDROID: /android/.test( NAV ), TOUCH: ('ontouchstart' in doc) }); // Galleria static methods /** Adds a theme that you can use for your Gallery @param {Object} theme Object that should contain all your theme settings. <ul> <li>name - name of the theme</li> <li>author - name of the author</li> <li>css - css file name (not path)</li> <li>defaults - default options to apply, including theme-specific options</li> <li>init - the init function</li> </ul> @returns {Object} theme */ Galleria.addTheme = function( theme ) { // make sure we have a name if ( !theme.name ) { Galleria.raise('No theme name specified'); } if ( typeof theme.defaults !== 'object' ) { theme.defaults = {}; } else { theme.defaults = _legacyOptions( theme.defaults ); } var css = false, reg; if ( typeof theme.css === 'string' ) { // look for manually added CSS $('link').each(function( i, link ) { reg = new RegExp( theme.css ); if ( reg.test( link.href ) ) { // we found the css css = true; // the themeload trigger _themeLoad( theme ); return false; } }); // else look for the absolute path and load the CSS dynamic if ( !css ) { $('script').each(function( i, script ) { // look for the theme script reg = new RegExp( 'galleria\\.' + theme.name.toLowerCase() + '\\.' ); if( reg.test( script.src )) { // we have a match css = script.src.replace(/[^\/]*$/, '') + theme.css; Utils.addTimer( "css", function() { Utils.loadCSS( css, 'galleria-theme', function() { // the themeload trigger _themeLoad( theme ); }); }, 1); } }); } if ( !css ) { Galleria.raise('No theme CSS loaded'); } } else { // pass _themeLoad( theme ); } return theme; }; /** loadTheme loads a theme js file and attaches a load event to Galleria @param {string} src The relative path to the theme source file @param {Object} [options] Optional options you want to apply @returns Galleria */ Galleria.loadTheme = function( src, options ) { var loaded = false, length = _galleries.length, err = window.setTimeout( function() { Galleria.raise( "Theme at " + src + " could not load, check theme path.", true ); }, 5000 ); // first clear the current theme, if exists Galleria.theme = undef; // load the theme Utils.loadScript( src, function() { window.clearTimeout( err ); // check for existing galleries and reload them with the new theme if ( length ) { // temporary save the new galleries var refreshed = []; // refresh all instances // when adding a new theme to an existing gallery, all options will be resetted but the data will be kept // you can apply new options as a second argument $.each( Galleria.get(), function(i, instance) { // mix the old data and options into the new instance var op = $.extend( instance._original.options, { data_source: instance._data }, options); // remove the old container instance.$('container').remove(); // create a new instance var g = new Galleria(); // move the id g._id = instance._id; // initialize the new instance g.init( instance._original.target, op ); // push the new instance refreshed.push( g ); }); // now overwrite the old holder with the new instances _galleries = refreshed; } }); return Galleria; }; /** Retrieves a Galleria instance. @param {number} [index] Optional index to retrieve. If no index is supplied, the method will return all instances in an array. @returns Instance or Array of instances */ Galleria.get = function( index ) { if ( !!_instances[ index ] ) { return _instances[ index ]; } else if ( typeof index !== 'number' ) { return _instances; } else { Galleria.raise('Gallery index ' + index + ' not found'); } }; /** Configure Galleria options via a static function. The options will be applied to all instances @param {string|object} key The options to apply or a key @param [value] If key is a string, this is the value @returns Galleria */ Galleria.configure = function( key, value ) { var opts = {}; if( typeof key == 'string' && value ) { opts[key] = value; key = opts; } else { $.extend( opts, key ); } Galleria.configure.options = opts; $.each( Galleria.get(), function(i, instance) { instance.setOptions( opts ); }); return Galleria; }; Galleria.configure.options = {}; /** Bind a Galleria event to the gallery @param {string} type A string representing the galleria event @param {function} callback The function that should run when the event is triggered @returns Galleria */ Galleria.on = function( type, callback ) { if ( !type ) { return; } Galleria.on.binds.push({ type: type, callback: callback || F }); $.each( Galleria.get(), function(i, instance) { instance.bind( type, callback ); }); return Galleria; }; Galleria.on.binds = []; /** Run Galleria Alias for $(selector).galleria(options) @param {string} selector A selector of element(s) to intialize galleria to @param {object} options The options to apply @returns Galleria */ Galleria.run = function( selector, options ) { $( selector || '#galleria' ).galleria( options ); return Galleria; }; /** Creates a transition to be used in your gallery @param {string} name The name of the transition that you will use as an option @param {Function} fn The function to be executed in the transition. The function contains two arguments, params and complete. Use the params Object to integrate the transition, and then call complete when you are done. @returns Galleria */ Galleria.addTransition = function( name, fn ) { _transitions[name] = fn; return Galleria; }; /** The Galleria utilites */ Galleria.utils = Utils; /** A helper metod for cross-browser logging. It uses the console log if available otherwise it falls back to alert @example Galleria.log("hello", document.body, [1,2,3]); */ Galleria.log = (function() { if( 'console' in window && 'log' in window.console ) { return window.console.log; } else { return function() { window.alert( Utils.array( arguments ).join(', ') ); }; } }()); /** A ready method for adding callbacks when a gallery is ready Each method is call before the extend option for every instance @param {function} callback The function to call @returns Galleria */ Galleria.ready = function( fn ) { $.each( _galleries, function( i, gallery ) { fn.call( gallery, gallery._options ); }); Galleria.ready.callbacks.push( fn ); return Galleria; }; Galleria.ready.callbacks = []; /** Method for raising errors @param {string} msg The message to throw @param {boolean} [fatal] Set this to true to override debug settings and display a fatal error */ Galleria.raise = function( msg, fatal ) { var type = fatal ? 'Fatal error' : 'Error', self = this, css = { color: '#fff', position: 'absolute', top: 0, left: 0, zIndex: 100000 }, echo = function( msg ) { var html = '<div style="padding:4px;margin:0 0 2px;background:#' + ( fatal ? '811' : '222' ) + '";>' + ( fatal ? '<strong>' + type + ': </strong>' : '' ) + msg + '</div>'; $.each( _instances, function() { var cont = this.$( 'errors' ), target = this.$( 'target' ); if ( !cont.length ) { target.css( 'position', 'relative' ); cont = this.addElement( 'errors' ).appendChild( 'target', 'errors' ).$( 'errors' ).css(css); } cont.append( html ); }); if ( !_instances.length ) { $('<div>').css( $.extend( css, { position: 'fixed' } ) ).append( html ).appendTo( DOM().body ); } }; // if debug is on, display errors and throw exception if fatal if ( DEBUG ) { echo( msg ); if ( fatal ) { throw new Error(type + ': ' + msg); } // else just echo a silent generic error if fatal } else if ( fatal ) { if ( _hasError ) { return; } _hasError = true; fatal = false; echo( 'Gallery could not load.' ); } }; // Add the version Galleria.version = VERSION; /** A method for checking what version of Galleria the user has installed and throws a readable error if the user needs to upgrade. Useful when building plugins that requires a certain version to function. @param {number} version The minimum version required @param {string} [msg] Optional message to display. If not specified, Galleria will throw a generic error. @returns Galleria */ Galleria.requires = function( version, msg ) { msg = msg || 'You need to upgrade Galleria to version ' + version + ' to use one or more components.'; if ( Galleria.version < version ) { Galleria.raise(msg, true); } return Galleria; }; /** Adds preload, cache, scale and crop functionality @constructor @requires jQuery @param {number} [id] Optional id to keep track of instances */ Galleria.Picture = function( id ) { // save the id this.id = id || null; // the image should be null until loaded this.image = null; // Create a new container this.container = Utils.create('galleria-image'); // add container styles $( this.container ).css({ overflow: 'hidden', position: 'relative' // for IE Standards mode }); // saves the original measurements this.original = { width: 0, height: 0 }; // flag when the image is ready this.ready = false; // flag for iframe Picture this.isIframe = false; }; Galleria.Picture.prototype = { // the inherited cache object cache: {}, // show the image on stage show: function() { Utils.show( this.image ); }, // hide the image hide: function() { Utils.moveOut( this.image ); }, clear: function() { this.image = null; }, /** Checks if an image is in cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns {boolean} */ isCached: function( src ) { return !!this.cache[src]; }, /** Preloads an image into the cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns Galleria.Picture */ preload: function( src ) { $( new Image() ).load((function(src, cache) { return function() { cache[ src ] = src; }; }( src, this.cache ))).attr( 'src', src ); }, /** Loads an image and call the callback when ready. Will also add the image to cache. @param {string} src The image source path, ex '/path/to/img.jpg' @param {Object} [size] The forced size of the image, defined as an object { width: xx, height:xx } @param {Function} callback The function to be executed when the image is loaded & scaled @returns The image container (jQuery object) */ load: function(src, size, callback) { if ( typeof size == 'function' ) { callback = size; size = null; } if( this.isIframe ) { var id = 'if'+new Date().getTime(); this.image = $('<iframe>', { src: src, frameborder: 0, id: id, allowfullscreen: true, css: { visibility: 'hidden' } })[0]; $( this.container ).find( 'iframe,img' ).remove(); this.container.appendChild( this.image ); $('#'+id).load( (function( self, callback ) { return function() { window.setTimeout(function() { $( self.image ).css( 'visibility', 'visible' ); if( typeof callback == 'function' ) { callback.call( self, self ); } }, 10); }; }( this, callback ))); return this.container; } this.image = new Image(); var i = 0, reload = false, resort = false, // some jquery cache $container = $( this.container ), $image = $( this.image ), // the onload method onload = (function( self, callback, src ) { return function() { var complete = function() { $( this ).unbind( 'load' ); // save the original size self.original = size || { height: this.height, width: this.width }; self.container.appendChild( this ); self.cache[ src ] = src; // will override old cache if (typeof callback == 'function' ) { window.setTimeout(function() { callback.call( self, self ); },1); } }; // Delay the callback to "fix" the Adblock Bug // http://code.google.com/p/adblockforchrome/issues/detail?id=3701 if ( ( !this.width || !this.height ) ) { window.setTimeout( (function( img ) { return function() { if ( img.width && img.height ) { complete.call( img ); } else { // last resort, this should never happen but just in case it does... if ( !resort ) { $(new Image()).load( onload ).attr( 'src', img.src ); resort = true; } else { Galleria.raise('Could not extract width/height from image: ' + img.src + '. Traced measures: width:' + img.width + 'px, height: ' + img.height + 'px.'); } } }; }( this )), 2); } else { complete.call( this ); } }; }( this, callback, src )); // remove any previous images $container.find( 'iframe,img' ).remove(); // append the image $image.css( 'display', 'block'); // hide it for now Utils.hide( this.image ); // remove any max/min scaling $.each('minWidth minHeight maxWidth maxHeight'.split(' '), function(i, prop) { $image.css(prop, (/min/.test(prop) ? '0' : 'none')); }); if ( this.cache[ src ] ) { // quick load on cache $image.load( onload ).attr( 'src', src ); return this.container; } // begin load and insert in cache when done $image.load( onload ).error( function() { if ( !reload ) { reload = true; // reload the image with a timestamp window.setTimeout((function(image, src) { return function() { image.attr('src', src + '?' + Utils.timestamp() ); }; }( $(this), src )), 50); } else { // apply the dummy image if it exists if ( DUMMY ) { $( this ).attr( 'src', DUMMY ); } else { Galleria.raise('Image not found: ' + src); } } }).attr( 'src', src ); // return the container return this.container; }, /** Scales and crops the image @param {Object} options The method takes an object with a number of options: <ul> <li>width - width of the container</li> <li>height - height of the container</li> <li>min - minimum scale ratio</li> <li>max - maximum scale ratio</li> <li>margin - distance in pixels from the image border to the container</li> <li>complete - a callback that fires when scaling is complete</li> <li>position - positions the image, works like the css background-image property.</li> <li>crop - defines how to crop. Can be true, false, 'width' or 'height'</li> <li>canvas - set to true to try a canvas-based rescale</li> </ul> @returns The image container object (jQuery) */ scale: function( options ) { var self = this; // extend some defaults options = $.extend({ width: 0, height: 0, min: undef, max: undef, margin: 0, complete: F, position: 'center', crop: false, canvas: false }, options); if( this.isIframe ) { $( this.image ).width( options.width ).height( options.height ).removeAttr( 'width' ).removeAttr( 'height' ); $( this.container ).width( options.width ).height( options.height) ; options.complete.call(self, self); try { if( this.image.contentWindow ) { $( this.image.contentWindow ).trigger('resize'); } } catch(e) {} return this.container; } // return the element if no image found if (!this.image) { return this.container; } // store locale variables var width, height, $container = $( self.container ), data; // wait for the width/height Utils.wait({ until: function() { width = options.width || $container.width() || Utils.parseValue( $container.css('width') ); height = options.height || $container.height() || Utils.parseValue( $container.css('height') ); return width && height; }, success: function() { // calculate some cropping var newWidth = ( width - options.margin * 2 ) / self.original.width, newHeight = ( height - options.margin * 2 ) / self.original.height, min = Math.min( newWidth, newHeight ), max = Math.max( newWidth, newHeight ), cropMap = { 'true' : max, 'width' : newWidth, 'height': newHeight, 'false' : min, 'landscape': self.original.width > self.original.height ? max : min, 'portrait': self.original.width < self.original.height ? max : min }, ratio = cropMap[ options.crop.toString() ], canvasKey = ''; // allow max_scale_ratio if ( options.max ) { ratio = Math.min( options.max, ratio ); } // allow min_scale_ratio if ( options.min ) { ratio = Math.max( options.min, ratio ); } $.each( ['width','height'], function( i, m ) { $( self.image )[ m ]( self[ m ] = self.image[ m ] = Math.round( self.original[ m ] * ratio ) ); }); $( self.container ).width( width ).height( height ); if ( options.canvas && _canvas ) { _canvas.elem.width = self.width; _canvas.elem.height = self.height; canvasKey = self.image.src + ':' + self.width + 'x' + self.height; self.image.src = _canvas.cache[ canvasKey ] || (function( key ) { _canvas.context.drawImage(self.image, 0, 0, self.original.width*ratio, self.original.height*ratio); try { data = _canvas.elem.toDataURL(); _canvas.length += data.length; _canvas.cache[ key ] = data; return data; } catch( e ) { return self.image.src; } }( canvasKey ) ); } // calculate image_position var pos = {}, mix = {}, getPosition = function(value, measure, margin) { var result = 0; if (/\%/.test(value)) { var flt = parseInt( value, 10 ) / 100, m = self.image[ measure ] || $( self.image )[ measure ](); result = Math.ceil( m * -1 * flt + margin * flt ); } else { result = Utils.parseValue( value ); } return result; }, positionMap = { 'top': { top: 0 }, 'left': { left: 0 }, 'right': { left: '100%' }, 'bottom': { top: '100%' } }; $.each( options.position.toLowerCase().split(' '), function( i, value ) { if ( value === 'center' ) { value = '50%'; } pos[i ? 'top' : 'left'] = value; }); $.each( pos, function( i, value ) { if ( positionMap.hasOwnProperty( value ) ) { $.extend( mix, positionMap[ value ] ); } }); pos = pos.top ? $.extend( pos, mix ) : mix; pos = $.extend({ top: '50%', left: '50%' }, pos); // apply position $( self.image ).css({ position : 'absolute', top : getPosition(pos.top, 'height', height), left : getPosition(pos.left, 'width', width) }); // show the image self.show(); // flag ready and call the callback self.ready = true; options.complete.call( self, self ); }, error: function() { Galleria.raise('Could not scale image: '+self.image.src); }, timeout: 1000 }); return this; } }; // our own easings $.extend( $.easing, { galleria: function (_, t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t*t + b; } return c/2*((t-=2)*t*t + 2) + b; }, galleriaIn: function (_, t, b, c, d) { return c*(t/=d)*t + b; }, galleriaOut: function (_, t, b, c, d) { return -c *(t/=d)*(t-2) + b; } }); // the plugin initializer $.fn.galleria = function( options ) { var selector = this.selector; // try domReady if element not found if ( !$(this).length ) { $(function() { if ( $( selector ).length ) { // if found on domReady, go ahead $( selector ).galleria( options ); } else { // if not, try fetching the element for 5 secs, then raise a warning. Galleria.utils.wait({ until: function() { return $( selector ).length; }, success: function() { $( selector ).galleria( options ); }, error: function() { Galleria.raise('Init failed: Galleria could not find the element "'+selector+'".'); }, timeout: 5000 }); } }); return this; } return this.each(function() { // fail silent if already run if ( !$.data(this, 'galleria') ) { $.data( this, 'galleria', new Galleria().init( this, options ) ); } }); }; // phew }( jQuery ) );
JavaScript
/** * Galleria Classic Theme 2012-04-04 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function($) { /*global jQuery, Galleria */ Galleria.addTheme({ name: 'classic', author: 'Galleria', css: 'galleria.classic.css', defaults: { transition: 'slide', thumbCrop: 'height', // set this to false if you want to show the caption all the time: _toggleInfo: true }, init: function(options) { Galleria.requires(1.25, 'This version of Classic theme requires Galleria 1.2.5 or later'); // add some elements this.addElement('info-link','info-close'); this.append({ 'info' : ['info-link','info-close'] }); // cache some stuff var info = this.$('info-link,info-close,info-text'), touch = Galleria.TOUCH, click = touch ? 'touchstart' : 'click'; // show loader & counter with opacity this.$('loader,counter').show().css('opacity', 0.4); // some stuff for non-touch browsers if (! touch ) { this.addIdleState( this.get('image-nav-left'), { left:-50 }); this.addIdleState( this.get('image-nav-right'), { right:-50 }); this.addIdleState( this.get('counter'), { opacity:0 }); } // toggle info if ( options._toggleInfo === true ) { info.bind( click, function() { info.toggle(); }); } else { info.show(); this.$('info-link, info-close').hide(); } // bind some stuff this.bind('thumbnail', function(e) { if (! touch ) { // fade thumbnails $(e.thumbTarget).css('opacity', 0.6).parent().hover(function() { $(this).not('.active').children().stop().fadeTo(100, 1); }, function() { $(this).not('.active').children().stop().fadeTo(400, 0.6); }); if ( e.index === this.getIndex() ) { $(e.thumbTarget).css('opacity',1); } } else { $(e.thumbTarget).css('opacity', this.getIndex() ? 1 : 0.6); } }); this.bind('loadstart', function(e) { if (!e.cached) { this.$('loader').show().fadeTo(200, 0.4); } this.$('info').toggle( this.hasInfo() ); $(e.thumbTarget).css('opacity',1).parent().siblings().children().css('opacity', 0.6); }); this.bind('loadfinish', function(e) { this.$('loader').fadeOut(200); }); } }); }(jQuery));
JavaScript
/** * @preserve Galleria Twelve Theme 2011-06-09 * http://galleria.aino.se * * Copyright (c) 2011, Aino */ /*global jQuery, Galleria */ (function($) { Galleria.addTheme({ name: 'twelve', author: 'Galleria', css: 'galleria.twelve.css', defaults: { transition: 'pulse', transitionSpeed: 500, imageCrop: true, thumbCrop: true, carousel: false, // theme specific defaults: _locale: { show_thumbnails: 'Show thumbnails', hide_thumbnails: 'Hide thumbnails', play: 'Play slideshow', pause: 'Pause slideshow', enter_fullscreen: 'Enter fullscreen', exit_fullscreen: 'Exit fullscreen', popout_image: 'Popout image', showing_image: 'Showing image %s of %s' }, _showFullscreen: true, _showPopout: true, _showProgress: true, _showTooltip: true }, init: function(options) { // add some elements this.addElement('bar','fullscreen','play','popout','thumblink','s1','s2','s3','s4','progress'); this.append({ 'stage' : 'progress', 'container': ['bar','tooltip'], 'bar' : ['fullscreen','play','popout','thumblink','info','s1','s2','s3','s4'] }); this.prependChild('info','counter'); // copy the scope var gallery = this, // cache some stuff thumbs = this.$('thumbnails-container'), thumb_link = this.$('thumblink'), fs_link = this.$('fullscreen'), play_link = this.$('play'), pop_link = this.$('popout'), bar = this.$('bar'), progress = this.$('progress'), transition = options.transition, lang = options._locale, // statics OPEN = false, FULLSCREEN = false, PLAYING = !!options.autoplay, CONTINUE = false, // helper functions scaleThumbs = function() { thumbs.height( gallery.getStageHeight() ).width( gallery.getStageWidth() ).css('top', OPEN ? 0 : gallery.getStageHeight()+30 ); }, toggleThumbs = function(e) { if (OPEN && CONTINUE) { gallery.play(); } else { CONTINUE = PLAYING; gallery.pause(); } Galleria.utils.animate( thumbs, { top: OPEN ? gallery.getStageHeight()+30 : 0 } , { easing:'galleria', duration:400, complete: function() { gallery.defineTooltip('thumblink', OPEN ? lang.show_thumbnails : lang.hide_thumbnails); thumb_link[OPEN ? 'removeClass' : 'addClass']('open'); OPEN = !OPEN; } }); }; // scale the thumbnail container scaleThumbs(); // bind the tooltips if (options._showTooltip) { gallery.bindTooltip({ 'thumblink': lang.show_thumbnails, 'fullscreen': lang.enter_fullscreen, 'play': lang.play, 'popout': lang.popout_image, 'caption': function() { var data = gallery.getData(); var str = ''; if (data) { if (data.title && data.title.length) { str+='<strong>'+data.title+'</strong>'; } if (data.description && data.description.length) { str+='<br>'+data.description; } } return str; }, 'counter': function() { return lang.showing_image.replace( /\%s/, gallery.getIndex() + 1 ).replace( /\%s/, gallery.getDataLength() ); } }); } if ( !options.showInfo ) { this.$( 'info' ).hide(); } // bind galleria events this.bind( 'play', function() { PLAYING = true; play_link.addClass('playing'); }); this.bind( 'pause', function() { PLAYING = false; play_link.removeClass('playing'); progress.width(0); }); if (options._showProgress) { this.bind( 'progress', function(e) { progress.width( e.percent/100 * this.getStageWidth() ); }); } this.bind( 'loadstart', function(e) { if (!e.cached) { this.$('loader').show(); } }); this.bind( 'loadfinish', function(e) { progress.width(0); this.$('loader').hide(); this.refreshTooltip('counter','caption'); }); this.bind( 'thumbnail', function(e) { $(e.thumbTarget).hover(function() { gallery.setInfo(e.thumbOrder); gallery.setCounter(e.thumbOrder); }, function() { gallery.setInfo(); gallery.setCounter(); }).click(function() { toggleThumbs(); }); }); this.bind( 'fullscreen_enter', function(e) { FULLSCREEN = true; gallery.setOptions('transition', false); fs_link.addClass('open'); bar.css('bottom',0); this.defineTooltip('fullscreen', lang.exit_fullscreen); if ( !Galleria.TOUCH ) { this.addIdleState(bar, { bottom: -31 }); } }); this.bind( 'fullscreen_exit', function(e) { FULLSCREEN = false; Galleria.utils.clearTimer('bar'); gallery.setOptions('transition',transition); fs_link.removeClass('open'); bar.css('bottom',0); this.defineTooltip('fullscreen', lang.enter_fullscreen); if ( !Galleria.TOUCH ) { this.removeIdleState(bar, { bottom:-31 }); } }); this.bind( 'rescale', scaleThumbs); if ( !Galleria.TOUCH ) { // STB //this.addIdleState(this.get('image-nav-left'), {left:-36}); //this.addIdleState(this.get('image-nav-right'), {right:-36}); } // bind thumblink thumb_link.click( toggleThumbs ); // bind popup if (options._showPopout) { pop_link.click(function(e) { gallery.openLightbox(); e.preventDefault(); }); } else { pop_link.remove(); if (options._showFullscreen) { this.$('s4').remove(); this.$('info').css('right',40); fs_link.css('right',0); } } // bind play button play_link.click(function() { gallery.defineTooltip('play', PLAYING ? lang.play : lang.pause); if (PLAYING) { gallery.pause(); } else { if (OPEN) { thumb_link.click(); } gallery.play(); } }); // bind fullscreen if (options._showFullscreen) { fs_link.click(function() { if (FULLSCREEN) { gallery.exitFullscreen(); } else { gallery.enterFullscreen(); } }); } else { fs_link.remove(); if (options._show_popout) { this.$('s4').remove(); this.$('info').css('right',40); pop_link.css('right',0); } } if (!options._showFullscreen && !options._showPopout) { this.$('s3,s4').remove(); this.$('info').css('right',10); } if (options.autoplay) { this.trigger( 'play' ); } } }); }( jQuery ));
JavaScript
/** * Galleria v 1.2.8 2012-08-09 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function( $ ) { /*global jQuery, navigator, Galleria:true, Image */ // some references var undef, window = this, doc = window.document, $doc = $( doc ), $win = $( window ), // native prototypes protoArray = Array.prototype, // internal constants VERSION = 1.28, DEBUG = true, TIMEOUT = 30000, DUMMY = false, NAV = navigator.userAgent.toLowerCase(), HASH = window.location.hash.replace(/#\//, ''), F = function(){}, FALSE = function() { return false; }, IE = (function() { var v = 3, div = doc.createElement( 'div' ), all = div.getElementsByTagName( 'i' ); do { div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->'; } while ( all[0] ); return v > 4 ? v : undef; }() ), DOM = function() { return { html: doc.documentElement, body: doc.body, head: doc.getElementsByTagName('head')[0], title: doc.title }; }, // list of Galleria events _eventlist = 'data ready thumbnail loadstart loadfinish image play pause progress ' + 'fullscreen_enter fullscreen_exit idle_enter idle_exit rescale ' + 'lightbox_open lightbox_close lightbox_image', _events = (function() { var evs = []; $.each( _eventlist.split(' '), function( i, ev ) { evs.push( ev ); // legacy events if ( /_/.test( ev ) ) { evs.push( ev.replace( /_/g, '' ) ); } }); return evs; }()), // legacy options // allows the old my_setting syntax and converts it to camel case _legacyOptions = function( options ) { var n; if ( typeof options !== 'object' ) { // return whatever it was... return options; } $.each( options, function( key, value ) { if ( /^[a-z]+_/.test( key ) ) { n = ''; $.each( key.split('_'), function( i, k ) { n += i > 0 ? k.substr( 0, 1 ).toUpperCase() + k.substr( 1 ) : k; }); options[ n ] = value; delete options[ key ]; } }); return options; }, _patchEvent = function( type ) { // allow 'image' instead of Galleria.IMAGE if ( $.inArray( type, _events ) > -1 ) { return Galleria[ type.toUpperCase() ]; } return type; }, // video providers _video = { youtube: { reg: /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&amp;(?:amp;)?)*v(?:&lt;[A-Z]+&gt;)?=([0-9a-zA-Z\-\_]+))/i, embed: function(id) { return 'http://www.youtube.com/embed/'+id; }, getThumb: function( id, success, fail ) { fail = fail || F; $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + id + '?v=2&alt=json-in-script&callback=?', function(data) { try { success( data.entry.media$group.media$thumbnail[0].url ); } catch(e) { fail(); } }).error(fail); } }, vimeo: { reg: /https?:\/\/(?:www\.)?(vimeo\.com)\/(?:hd#)?([0-9]+)/i, embed: function(id) { return 'http://player.vimeo.com/video/'+id; }, getThumb: function( id, success, fail ) { fail = fail || F; $.getJSON('http://vimeo.com/api/v2/video/' + id + '.json?callback=?', function(data) { try { success( data[0].thumbnail_medium ); } catch(e) { fail(); } }).error(fail); } }, dailymotion: { reg: /https?:\/\/(?:www\.)?(dailymotion\.com)\/video\/([^_]+)/, embed: function(id) { return 'http://www.dailymotion.com/embed/video/'+id; }, getThumb: function( id, success, fail ) { fail = fail || F; $.getJSON('https://api.dailymotion.com/video/'+id+'?fields=thumbnail_medium_url&callback=?', function(data) { try { success( data.thumbnail_medium_url ); } catch(e) { fail(); } }).error(fail); } } }, // utility for testing the video URL and getting the video ID _videoTest = function( url ) { var match; for ( var v in _video ) { match = url && url.match( _video[v].reg ); if( match && match.length ) { return { id: match[2], provider: v }; } } return false; }, // native fullscreen handler _nativeFullscreen = { support: (function() { var html = DOM().html; return html.requestFullscreen || html.mozRequestFullScreen || html.webkitRequestFullScreen; }()), callback: F, enter: function( instance, callback ) { this.instance = instance; this.callback = callback || F; var html = DOM().html; if ( html.requestFullscreen ) { html.requestFullscreen(); } else if ( html.mozRequestFullScreen ) { html.mozRequestFullScreen(); } else if ( html.webkitRequestFullScreen ) { html.webkitRequestFullScreen(); } }, exit: function( callback ) { this.callback = callback || F; if ( doc.exitFullscreen ) { doc.exitFullscreen(); } else if ( doc.mozCancelFullScreen ) { doc.mozCancelFullScreen(); } else if ( doc.webkitCancelFullScreen ) { doc.webkitCancelFullScreen(); } }, instance: null, listen: function() { if ( !this.support ) { return; } var handler = function() { if ( !_nativeFullscreen.instance ) { return; } var fs = _nativeFullscreen.instance._fullscreen; if ( doc.fullscreen || doc.mozFullScreen || doc.webkitIsFullScreen ) { fs._enter( _nativeFullscreen.callback ); } else { fs._exit( _nativeFullscreen.callback ); } }; doc.addEventListener( 'fullscreenchange', handler, false ); doc.addEventListener( 'mozfullscreenchange', handler, false ); doc.addEventListener( 'webkitfullscreenchange', handler, false ); } }, // the internal gallery holder _galleries = [], // the internal instance holder _instances = [], // flag for errors _hasError = false, // canvas holder _canvas = false, // instance pool, holds the galleries until themeLoad is triggered _pool = [], // themeLoad trigger _themeLoad = function( theme ) { Galleria.theme = theme; // run the instances we have in the pool $.each( _pool, function( i, instance ) { if ( !instance._initialized ) { instance._init.call( instance ); } }); }, // the Utils singleton Utils = (function() { return { // legacy support for clearTimer clearTimer: function( id ) { $.each( Galleria.get(), function() { this.clearTimer( id ); }); }, // legacy support for addTimer addTimer: function( id ) { $.each( Galleria.get(), function() { this.addTimer( id ); }); }, array : function( obj ) { return protoArray.slice.call(obj, 0); }, create : function( className, nodeName ) { nodeName = nodeName || 'div'; var elem = doc.createElement( nodeName ); elem.className = className; return elem; }, getScriptPath : function( src ) { // the currently executing script is always the last src = src || $('script:last').attr('src'); var slices = src.split('/'); if (slices.length == 1) { return ''; } slices.pop(); return slices.join('/') + '/'; }, // CSS3 transitions, added in 1.2.4 animate : (function() { // detect transition var transition = (function( style ) { var props = 'transition WebkitTransition MozTransition OTransition'.split(' '), i; // disable css3 animations in opera until stable if ( window.opera ) { return false; } for ( i = 0; props[i]; i++ ) { if ( typeof style[ props[ i ] ] !== 'undefined' ) { return props[ i ]; } } return false; }(( doc.body || doc.documentElement).style )); // map transitionend event var endEvent = { MozTransition: 'transitionend', OTransition: 'oTransitionEnd', WebkitTransition: 'webkitTransitionEnd', transition: 'transitionend' }[ transition ]; // map bezier easing conversions var easings = { _default: [0.25, 0.1, 0.25, 1], galleria: [0.645, 0.045, 0.355, 1], galleriaIn: [0.55, 0.085, 0.68, 0.53], galleriaOut: [0.25, 0.46, 0.45, 0.94], ease: [0.25, 0, 0.25, 1], linear: [0.25, 0.25, 0.75, 0.75], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }; // function for setting transition css for all browsers var setStyle = function( elem, value, suffix ) { var css = {}; suffix = suffix || 'transition'; $.each( 'webkit moz ms o'.split(' '), function() { css[ '-' + this + '-' + suffix ] = value; }); elem.css( css ); }; // clear styles var clearStyle = function( elem ) { setStyle( elem, 'none', 'transition' ); if ( Galleria.WEBKIT && Galleria.TOUCH ) { setStyle( elem, 'translate3d(0,0,0)', 'transform' ); if ( elem.data('revert') ) { elem.css( elem.data('revert') ); elem.data('revert', null); } } }; // various variables var change, strings, easing, syntax, revert, form, css; // the actual animation method return function( elem, to, options ) { // extend defaults options = $.extend({ duration: 400, complete: F, stop: false }, options); // cache jQuery instance elem = $( elem ); if ( !options.duration ) { elem.css( to ); options.complete.call( elem[0] ); return; } // fallback to jQuery's animate if transition is not supported if ( !transition ) { elem.animate(to, options); return; } // stop if ( options.stop ) { // clear the animation elem.unbind( endEvent ); clearStyle( elem ); } // see if there is a change change = false; $.each( to, function( key, val ) { css = elem.css( key ); if ( Utils.parseValue( css ) != Utils.parseValue( val ) ) { change = true; } // also add computed styles for FF elem.css( key, css ); }); if ( !change ) { window.setTimeout( function() { options.complete.call( elem[0] ); }, options.duration ); return; } // the css strings to be applied strings = []; // the easing bezier easing = options.easing in easings ? easings[ options.easing ] : easings._default; // the syntax syntax = ' ' + options.duration + 'ms' + ' cubic-bezier(' + easing.join(',') + ')'; // add a tiny timeout so that the browsers catches any css changes before animating window.setTimeout( (function(elem, endEvent, to, syntax) { return function() { // attach the end event elem.one(endEvent, (function( elem ) { return function() { // clear the animation clearStyle(elem); // run the complete method options.complete.call(elem[0]); }; }( elem ))); // do the webkit translate3d for better performance on iOS if( Galleria.WEBKIT && Galleria.TOUCH ) { revert = {}; form = [0,0,0]; $.each( ['left', 'top'], function(i, m) { if ( m in to ) { form[ i ] = ( Utils.parseValue( to[ m ] ) - Utils.parseValue(elem.css( m )) ) + 'px'; revert[ m ] = to[ m ]; delete to[ m ]; } }); if ( form[0] || form[1]) { elem.data('revert', revert); strings.push('-webkit-transform' + syntax); // 3d animate setStyle( elem, 'translate3d(' + form.join(',') + ')', 'transform'); } } // push the animation props $.each(to, function( p, val ) { strings.push(p + syntax); }); // set the animation styles setStyle( elem, strings.join(',') ); // animate elem.css( to ); }; }(elem, endEvent, to, syntax)), 2); }; }()), removeAlpha : function( elem ) { if ( IE < 9 && elem ) { var style = elem.style, currentStyle = elem.currentStyle, filter = currentStyle && currentStyle.filter || style.filter || ""; if ( /alpha/.test( filter ) ) { style.filter = filter.replace( /alpha\([^)]*\)/i, '' ); } } }, forceStyles : function( elem, styles ) { elem = $(elem); if ( elem.attr( 'style' ) ) { elem.data( 'styles', elem.attr( 'style' ) ).removeAttr( 'style' ); } elem.css( styles ); }, revertStyles : function() { $.each( Utils.array( arguments ), function( i, elem ) { elem = $( elem ); elem.removeAttr( 'style' ); elem.attr('style',''); // "fixes" webkit bug if ( elem.data( 'styles' ) ) { elem.attr( 'style', elem.data('styles') ).data( 'styles', null ); } }); }, moveOut : function( elem ) { Utils.forceStyles( elem, { position: 'absolute', left: -10000 }); }, moveIn : function() { Utils.revertStyles.apply( Utils, Utils.array( arguments ) ); }, elem : function( elem ) { if (elem instanceof $) { return { $: elem, dom: elem[0] }; } else { return { $: $(elem), dom: elem }; } }, hide : function( elem, speed, callback ) { callback = callback || F; var el = Utils.elem( elem ), $elem = el.$; elem = el.dom; // save the value if not exist if (! $elem.data('opacity') ) { $elem.data('opacity', $elem.css('opacity') ); } // always hide var style = { opacity: 0 }; if (speed) { var complete = IE < 9 && elem ? function() { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; } else { $elem.css( style ); } } }, show : function( elem, speed, callback ) { callback = callback || F; var el = Utils.elem( elem ), $elem = el.$; elem = el.dom; // bring back saved opacity var saved = parseFloat( $elem.data('opacity') ) || 1, style = { opacity: saved }; // animate or toggle if (speed) { if ( IE < 9 ) { $elem.css('opacity', 0); elem.style.visibility = 'visible'; } var complete = IE < 9 && elem ? function() { if ( style.opacity == 1 ) { Utils.removeAlpha( elem ); } callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && style.opacity == 1 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'visible'; } else { $elem.css( style ); } } }, // enhanced click for mobile devices // we bind a touchend and hijack any click event in the bubble // then we execute the click directly and save it in a separate data object for later optimizeTouch: (function() { var node, evs, fakes, travel, evt = {}, handler = function( e ) { e.preventDefault(); evt = $.extend({}, e, true); }, attach = function() { this.evt = evt; }, fake = function() { this.handler.call(node, this.evt); }; return function( elem ) { $(elem).bind('touchend', function( e ) { node = e.target; travel = true; while( node.parentNode && node != e.currentTarget && travel ) { evs = $(node).data('events'); fakes = $(node).data('fakes'); if (evs && 'click' in evs) { travel = false; e.preventDefault(); // fake the click and save the event object $(node).click(handler).click(); // remove the faked click evs.click.pop(); // attach the faked event $.each( evs.click, attach); // save the faked clicks in a new data object $(node).data('fakes', evs.click); // remove all clicks delete evs.click; } else if ( fakes ) { travel = false; e.preventDefault(); // fake all clicks $.each( fakes, fake ); } // bubble node = node.parentNode; } }); }; }()), wait : function(options) { options = $.extend({ until : FALSE, success : F, error : function() { Galleria.raise('Could not complete wait function.'); }, timeout: 3000 }, options); var start = Utils.timestamp(), elapsed, now, fn = function() { now = Utils.timestamp(); elapsed = now - start; if ( options.until( elapsed ) ) { options.success(); return false; } if (typeof options.timeout == 'number' && now >= start + options.timeout) { options.error(); return false; } window.setTimeout(fn, 10); }; window.setTimeout(fn, 10); }, toggleQuality : function( img, force ) { if ( ( IE !== 7 && IE !== 8 ) || !img || img.nodeName.toUpperCase() != 'IMG' ) { return; } if ( typeof force === 'undefined' ) { force = img.style.msInterpolationMode === 'nearest-neighbor'; } img.style.msInterpolationMode = force ? 'bicubic' : 'nearest-neighbor'; }, insertStyleTag : function( styles ) { var style = doc.createElement( 'style' ); DOM().head.appendChild( style ); if ( style.styleSheet ) { // IE style.styleSheet.cssText = styles; } else { var cssText = doc.createTextNode( styles ); style.appendChild( cssText ); } }, // a loadscript method that works for local scripts loadScript: function( url, callback ) { var done = false, script = $('<scr'+'ipt>').attr({ src: url, async: true }).get(0); // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') ) { done = true; // Handle memory leak in IE script.onload = script.onreadystatechange = null; if (typeof callback === 'function') { callback.call( this, this ); } } }; DOM().head.appendChild( script ); }, // parse anything into a number parseValue: function( val ) { if (typeof val === 'number') { return val; } else if (typeof val === 'string') { var arr = val.match(/\-?\d|\./g); return arr && arr.constructor === Array ? arr.join('')*1 : 0; } else { return 0; } }, // timestamp abstraction timestamp: function() { return new Date().getTime(); }, loadCSS : function( href, id, callback ) { var link, length; // look for manual css $('link[rel=stylesheet]').each(function() { if ( new RegExp( href ).test( this.href ) ) { link = this; return false; } }); if ( typeof id === 'function' ) { callback = id; id = undef; } callback = callback || F; // dirty // if already present, return if ( link ) { callback.call( link, link ); return link; } // save the length of stylesheets to check against length = doc.styleSheets.length; // check for existing id if( $( '#' + id ).length ) { $( '#' + id ).attr( 'href', href ); length--; } else { link = $( '<link>' ).attr({ rel: 'stylesheet', href: href, id: id }).get(0); var styles = $('link[rel="stylesheet"], style'); if ( styles.length ) { styles.get(0).parentNode.insertBefore( link, styles[0] ); } else { DOM().head.appendChild( link ); } if ( IE ) { // IE has a limit of 31 stylesheets in one document if( length >= 31 ) { Galleria.raise( 'You have reached the browser stylesheet limit (31)', true ); return; } } } if ( typeof callback === 'function' ) { // First check for dummy element (new in 1.2.8) var $loader = $('<s>').attr( 'id', 'galleria-loader' ).hide().appendTo( DOM().body ); Utils.wait({ until: function() { return $loader.height() == 1; }, success: function() { $loader.remove(); callback.call( link, link ); }, error: function() { $loader.remove(); // If failed, tell the dev to download the latest theme Galleria.raise( 'Theme CSS could not load after 20 sec. Please download the latest theme at http://galleria.io/customer/', true ); }, timeout: 20000 }); } return link; } }; }()), // the transitions holder _transitions = (function() { var _slide = function(params, complete, fade, door) { var easing = this.getOptions('easing'), distance = this.getStageWidth(), from = { left: distance * ( params.rewind ? -1 : 1 ) }, to = { left: 0 }; if ( fade ) { from.opacity = 0; to.opacity = 1; } else { from.opacity = 1; } $(params.next).css(from); Utils.animate(params.next, to, { duration: params.speed, complete: (function( elems ) { return function() { complete(); elems.css({ left: 0 }); }; }( $( params.next ).add( params.prev ) )), queue: false, easing: easing }); if (door) { params.rewind = !params.rewind; } if (params.prev) { from = { left: 0 }; to = { left: distance * ( params.rewind ? 1 : -1 ) }; if ( fade ) { from.opacity = 1; to.opacity = 0; } $(params.prev).css(from); Utils.animate(params.prev, to, { duration: params.speed, queue: false, easing: easing, complete: function() { $(this).css('opacity', 0); } }); } }; return { active: false, init: function( effect, params, complete ) { if ( _transitions.effects.hasOwnProperty( effect ) ) { _transitions.effects[ effect ].call( this, params, complete ); } }, effects: { fade: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }).show(); Utils.animate(params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); if (params.prev) { $(params.prev).css('opacity',1).show(); Utils.animate(params.prev, { opacity: 0 },{ duration: params.speed }); } }, flash: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }); if (params.prev) { Utils.animate( params.prev, { opacity: 0 },{ duration: params.speed/2, complete: function() { Utils.animate( params.next, { opacity:1 },{ duration: params.speed, complete: complete }); } }); } else { Utils.animate( params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); } }, pulse: function(params, complete) { if (params.prev) { $(params.prev).hide(); } $(params.next).css({ opacity: 0, left: 0 }).show(); Utils.animate(params.next, { opacity:1 },{ duration: params.speed, complete: complete }); }, slide: function(params, complete) { _slide.apply( this, Utils.array( arguments ) ); }, fadeslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [true] ) ); }, doorslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [false, true] ) ); } } }; }()); _nativeFullscreen.listen(); /** The main Galleria class @class @constructor @example var gallery = new Galleria(); @author http://aino.se @requires jQuery */ Galleria = function() { var self = this; // internal options this._options = {}; // flag for controlling play/pause this._playing = false; // internal interval for slideshow this._playtime = 5000; // internal variable for the currently active image this._active = null; // the internal queue, arrayified this._queue = { length: 0 }; // the internal data array this._data = []; // the internal dom collection this._dom = {}; // the internal thumbnails array this._thumbnails = []; // the internal layers array this._layers = []; // internal init flag this._initialized = false; // internal firstrun flag this._firstrun = false; // global stagewidth/height this._stageWidth = 0; this._stageHeight = 0; // target holder this._target = undef; // bind hashes this._binds = []; // instance id this._id = parseInt(Math.random()*10000, 10); // add some elements var divs = 'container stage images image-nav image-nav-left image-nav-right ' + 'info info-text info-title info-description ' + 'thumbnails thumbnails-list thumbnails-container thumb-nav-left thumb-nav-right ' + 'loader counter tooltip', spans = 'current total'; $.each( divs.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId ); }); $.each( spans.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId, 'span' ); }); // the internal keyboard object // keeps reference of the keybinds and provides helper methods for binding keys var keyboard = this._keyboard = { keys : { 'UP': 38, 'DOWN': 40, 'LEFT': 37, 'RIGHT': 39, 'RETURN': 13, 'ESCAPE': 27, 'BACKSPACE': 8, 'SPACE': 32 }, map : {}, bound: false, press: function(e) { var key = e.keyCode || e.which; if ( key in keyboard.map && typeof keyboard.map[key] === 'function' ) { keyboard.map[key].call(self, e); } }, attach: function(map) { var key, up; for( key in map ) { if ( map.hasOwnProperty( key ) ) { up = key.toUpperCase(); if ( up in keyboard.keys ) { keyboard.map[ keyboard.keys[up] ] = map[key]; } else { keyboard.map[ up ] = map[key]; } } } if ( !keyboard.bound ) { keyboard.bound = true; $doc.bind('keydown', keyboard.press); } }, detach: function() { keyboard.bound = false; keyboard.map = {}; $doc.unbind('keydown', keyboard.press); } }; // internal controls for keeping track of active / inactive images var controls = this._controls = { 0: undef, 1: undef, active : 0, swap : function() { controls.active = controls.active ? 0 : 1; }, getActive : function() { return controls[ controls.active ]; }, getNext : function() { return controls[ 1 - controls.active ]; } }; // internal carousel object var carousel = this._carousel = { // shortcuts next: self.$('thumb-nav-right'), prev: self.$('thumb-nav-left'), // cache the width width: 0, // track the current position current: 0, // cache max value max: 0, // save all hooks for each width in an array hooks: [], // update the carousel // you can run this method anytime, f.ex on window.resize update: function() { var w = 0, h = 0, hooks = [0]; $.each( self._thumbnails, function( i, thumb ) { if ( thumb.ready ) { w += thumb.outerWidth || $( thumb.container ).outerWidth( true ); hooks[ i+1 ] = w; h = Math.max( h, thumb.outerHeight || $( thumb.container).outerHeight( true ) ); } }); self.$( 'thumbnails' ).css({ width: w, height: h }); carousel.max = w; carousel.hooks = hooks; carousel.width = self.$( 'thumbnails-list' ).width(); carousel.setClasses(); self.$( 'thumbnails-container' ).toggleClass( 'galleria-carousel', w > carousel.width ); // one extra calculation carousel.width = self.$( 'thumbnails-list' ).width(); // todo: fix so the carousel moves to the left }, bindControls: function() { var i; carousel.next.bind( 'click', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i < carousel.hooks.length; i++ ) { if ( carousel.hooks[i] - carousel.hooks[ carousel.current ] > carousel.width ) { carousel.set(i - 2); break; } } } else { carousel.set( carousel.current + self._options.carouselSteps); } }); carousel.prev.bind( 'click', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i >= 0; i-- ) { if ( carousel.hooks[ carousel.current ] - carousel.hooks[i] > carousel.width ) { carousel.set( i + 2 ); break; } else if ( i === 0 ) { carousel.set( 0 ); break; } } } else { carousel.set( carousel.current - self._options.carouselSteps ); } }); }, // calculate and set positions set: function( i ) { i = Math.max( i, 0 ); while ( carousel.hooks[i - 1] + carousel.width >= carousel.max && i >= 0 ) { i--; } carousel.current = i; carousel.animate(); }, // get the last position getLast: function(i) { return ( i || carousel.current ) - 1; }, // follow the active image follow: function(i) { //don't follow if position fits if ( i === 0 || i === carousel.hooks.length - 2 ) { carousel.set( i ); return; } // calculate last position var last = carousel.current; while( carousel.hooks[last] - carousel.hooks[ carousel.current ] < carousel.width && last <= carousel.hooks.length ) { last ++; } // set position if ( i - 1 < carousel.current ) { carousel.set( i - 1 ); } else if ( i + 2 > last) { carousel.set( i - last + carousel.current + 2 ); } }, // helper for setting disabled classes setClasses: function() { carousel.prev.toggleClass( 'disabled', !carousel.current ); carousel.next.toggleClass( 'disabled', carousel.hooks[ carousel.current ] + carousel.width >= carousel.max ); }, // the animation method animate: function(to) { carousel.setClasses(); var num = carousel.hooks[ carousel.current ] * -1; if ( isNaN( num ) ) { return; } Utils.animate(self.get( 'thumbnails' ), { left: num },{ duration: self._options.carouselSpeed, easing: self._options.easing, queue: false }); } }; // tooltip control // added in 1.2 var tooltip = this._tooltip = { initialized : false, open: false, timer: 'tooltip' + self._id, swapTimer: 'swap' + self._id, init: function() { tooltip.initialized = true; var css = '.galleria-tooltip{padding:3px 8px;max-width:50%;background:#ffe;color:#000;z-index:3;position:absolute;font-size:11px;line-height:1.3;' + 'opacity:0;box-shadow:0 0 2px rgba(0,0,0,.4);-moz-box-shadow:0 0 2px rgba(0,0,0,.4);-webkit-box-shadow:0 0 2px rgba(0,0,0,.4);}'; Utils.insertStyleTag(css); self.$( 'tooltip' ).css({ opacity: 0.8, visibility: 'visible', display: 'none' }); }, // move handler move: function( e ) { var mouseX = self.getMousePosition(e).x, mouseY = self.getMousePosition(e).y, $elem = self.$( 'tooltip' ), x = mouseX, y = mouseY, height = $elem.outerHeight( true ) + 1, width = $elem.outerWidth( true ), limitY = height + 15; var maxX = self.$( 'container').width() - width - 2, maxY = self.$( 'container').height() - height - 2; if ( !isNaN(x) && !isNaN(y) ) { x += 10; y -= 30; x = Math.max( 0, Math.min( maxX, x ) ); y = Math.max( 0, Math.min( maxY, y ) ); if( mouseY < limitY ) { y = limitY; } $elem.css({ left: x, top: y }); } }, // bind elements to the tooltip // you can bind multiple elementIDs using { elemID : function } or { elemID : string } // you can also bind single DOM elements using bind(elem, string) bind: function( elem, value ) { // todo: revise if alternative tooltip is needed for mobile devices if (Galleria.TOUCH) { return; } if (! tooltip.initialized ) { tooltip.init(); } var mouseout = function() { self.$( 'container' ).unbind( 'mousemove', tooltip.move ); self.clearTimer( tooltip.timer ); self.$( 'tooltip' ).stop().animate({ opacity: 0 }, 200, function() { self.$( 'tooltip' ).hide(); self.addTimer( tooltip.swapTimer, function() { tooltip.open = false; }, 1000); }); }; var hover = function( elem, value) { tooltip.define( elem, value ); $( elem ).hover(function() { self.clearTimer( tooltip.swapTimer ); self.$('container').unbind( 'mousemove', tooltip.move ).bind( 'mousemove', tooltip.move ).trigger( 'mousemove' ); tooltip.show( elem ); self.addTimer( tooltip.timer, function() { self.$( 'tooltip' ).stop().show().animate({ opacity: 1 }); tooltip.open = true; }, tooltip.open ? 0 : 500); }, mouseout).click(mouseout); }; if ( typeof value === 'string' ) { hover( ( elem in self._dom ? self.get( elem ) : elem ), value ); } else { // asume elemID here $.each( elem, function( elemID, val ) { hover( self.get(elemID), val ); }); } }, show: function( elem ) { elem = $( elem in self._dom ? self.get(elem) : elem ); var text = elem.data( 'tt' ), mouseup = function( e ) { // attach a tiny settimeout to make sure the new tooltip is filled window.setTimeout( (function( ev ) { return function() { tooltip.move( ev ); }; }( e )), 10); elem.unbind( 'mouseup', mouseup ); }; text = typeof text === 'function' ? text() : text; if ( ! text ) { return; } self.$( 'tooltip' ).html( text.replace(/\s/, '&nbsp;') ); // trigger mousemove on mouseup in case of click elem.bind( 'mouseup', mouseup ); }, define: function( elem, value ) { // we store functions, not strings if (typeof value !== 'function') { var s = value; value = function() { return s; }; } elem = $( elem in self._dom ? self.get(elem) : elem ).data('tt', value); tooltip.show( elem ); } }; // internal fullscreen control var fullscreen = this._fullscreen = { scrolled: 0, crop: undef, transition: undef, active: false, keymap: self._keyboard.map, parseCallback: function( callback, enter ) { return _transitions.active ? function() { if ( typeof callback == 'function' ) { callback(); } var active = self._controls.getActive(), next = self._controls.getNext(); self._scaleImage( next ); self._scaleImage( active ); if ( enter && self._options.trueFullscreen ) { // Firefox bug, revise later $( active.container ).add( next.container ).trigger( 'transitionend' ); } } : callback; }, enter: function( callback ) { callback = fullscreen.parseCallback( callback, true ); if ( self._options.trueFullscreen && _nativeFullscreen.support ) { _nativeFullscreen.enter( self, callback ); } else { fullscreen._enter( callback ); } }, _enter: function( callback ) { fullscreen.active = true; // hide the image until rescale is complete Utils.hide( self.getActiveImage() ); self.$( 'container' ).addClass( 'fullscreen' ); fullscreen.scrolled = $win.scrollTop(); // begin styleforce Utils.forceStyles(self.get('container'), { position: 'fixed', top: 0, left: 0, width: '100%', height: '100%', zIndex: 10000 }); var htmlbody = { height: '100%', overflow: 'hidden', margin:0, padding:0 }, data = self.getData(), options = self._options; Utils.forceStyles( DOM().html, htmlbody ); Utils.forceStyles( DOM().body, htmlbody ); // temporarily attach some keys // save the old ones first in a cloned object fullscreen.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: self.exitFullscreen, right: self.next, left: self.prev }); // temporarily save the crop fullscreen.crop = options.imageCrop; // set fullscreen options if ( options.fullscreenCrop != undef ) { options.imageCrop = options.fullscreenCrop; } // swap to big image if it's different from the display image if ( data && data.big && data.image !== data.big ) { var big = new Galleria.Picture(), cached = big.isCached( data.big ), index = self.getIndex(), thumb = self._thumbnails[ index ]; self.trigger( { type: Galleria.LOADSTART, cached: cached, rewind: false, index: index, imageTarget: self.getActiveImage(), thumbTarget: thumb, galleriaData: data }); big.load( data.big, function( big ) { self._scaleImage( big, { complete: function( big ) { self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: index, rewind: false, imageTarget: big.image, thumbTarget: thumb }); var image = self._controls.getActive().image; if ( image ) { $( image ).width( big.image.width ).height( big.image.height ) .attr( 'style', $( big.image ).attr('style') ) .attr( 'src', big.image.src ); } } }); }); } // init the first rescale and attach callbacks self.rescale(function() { self.addTimer(false, function() { // show the image after 50 ms Utils.show( self.getActiveImage() ); if (typeof callback === 'function') { callback.call( self ); } }, 100); self.trigger( Galleria.FULLSCREEN_ENTER ); }); // bind the scaling to the resize event $win.resize( function() { fullscreen.scale(); } ); }, scale : function() { self.rescale(); }, exit: function( callback ) { callback = fullscreen.parseCallback( callback ); if ( self._options.trueFullscreen && _nativeFullscreen.support ) { _nativeFullscreen.exit( callback ); } else { fullscreen._exit( callback ); } }, _exit: function( callback ) { fullscreen.active = false; Utils.hide( self.getActiveImage() ); self.$('container').removeClass( 'fullscreen' ); // revert all styles Utils.revertStyles( self.get('container'), DOM().html, DOM().body ); // scroll back window.scrollTo(0, fullscreen.scrolled); // detach all keyboard events and apply the old keymap self.detachKeyboard(); self.attachKeyboard( fullscreen.keymap ); // bring back cached options self._options.imageCrop = fullscreen.crop; //self._options.transition = fullscreen.transition; // return to original image var big = self.getData().big, image = self._controls.getActive().image; if ( !self.getData().iframe && image && big && big == image.src ) { window.setTimeout(function(src) { return function() { image.src = src; }; }( self.getData().image ), 1 ); } self.rescale(function() { self.addTimer(false, function() { // show the image after 50 ms Utils.show( self.getActiveImage() ); if ( typeof callback === 'function' ) { callback.call( self ); } $win.trigger( 'resize' ); }, 50); self.trigger( Galleria.FULLSCREEN_EXIT ); }); $win.unbind('resize', fullscreen.scale); } }; // the internal idle object for controlling idle states var idle = this._idle = { trunk: [], bound: false, active: false, add: function(elem, to, from, hide) { if (!elem) { return; } if (!idle.bound) { idle.addEvent(); } elem = $(elem); if ( typeof from == 'boolean' ) { hide = from; from = {}; } from = from || {}; var extract = {}, style; for ( style in to ) { if ( to.hasOwnProperty( style ) ) { extract[ style ] = elem.css( style ); } } elem.data('idle', { from: $.extend( extract, from ), to: to, complete: true, busy: false }); if ( !hide ) { idle.addTimer(); } else { elem.css( to ); } idle.trunk.push(elem); }, remove: function(elem) { elem = $(elem); $.each(idle.trunk, function(i, el) { if ( el && el.length && !el.not(elem).length ) { elem.css( elem.data( 'idle' ).from ); idle.trunk.splice(i, 1); } }); if (!idle.trunk.length) { idle.removeEvent(); self.clearTimer( idle.timer ); } }, addEvent : function() { idle.bound = true; self.$('container').bind( 'mousemove click', idle.showAll ); if ( self._options.idleMode == 'hover' ) { self.$('container').bind( 'mouseleave', idle.hide ); } }, removeEvent : function() { idle.bound = false; self.$('container').bind( 'mousemove click', idle.showAll ); if ( self._options.idleMode == 'hover' ) { self.$('container').unbind( 'mouseleave', idle.hide ); } }, addTimer : function() { if( self._options.idleMode == 'hover' ) { return; } self.addTimer( 'idle', function() { idle.hide(); }, self._options.idleTime ); }, hide : function() { if ( !self._options.idleMode || self.getIndex() === false || self.getData().iframe ) { return; } self.trigger( Galleria.IDLE_ENTER ); var len = idle.trunk.length; $.each( idle.trunk, function(i, elem) { var data = elem.data('idle'); if (! data) { return; } elem.data('idle').complete = false; Utils.animate( elem, data.to, { duration: self._options.idleSpeed, complete: function() { if ( i == len-1 ) { idle.active = false; } } }); }); }, showAll : function() { self.clearTimer( 'idle' ); $.each( idle.trunk, function( i, elem ) { idle.show( elem ); }); }, show: function(elem) { var data = elem.data('idle'); if ( !idle.active || ( !data.busy && !data.complete ) ) { data.busy = true; self.trigger( Galleria.IDLE_EXIT ); self.clearTimer( 'idle' ); Utils.animate( elem, data.from, { duration: self._options.idleSpeed/2, complete: function() { idle.active = true; $(elem).data('idle').busy = false; $(elem).data('idle').complete = true; } }); } idle.addTimer(); } }; // internal lightbox object // creates a predesigned lightbox for simple popups of images in galleria var lightbox = this._lightbox = { width : 0, height : 0, initialized : false, active : null, image : null, elems : {}, keymap: false, init : function() { // trigger the event self.trigger( Galleria.LIGHTBOX_OPEN ); if ( lightbox.initialized ) { return; } lightbox.initialized = true; // create some elements to work with var elems = 'overlay box content shadow title info close prevholder prev nextholder next counter image', el = {}, op = self._options, css = '', abs = 'position:absolute;', prefix = 'lightbox-', cssMap = { overlay: 'position:fixed;display:none;opacity:'+op.overlayOpacity+';filter:alpha(opacity='+(op.overlayOpacity*100)+ ');top:0;left:0;width:100%;height:100%;background:'+op.overlayBackground+';z-index:99990', box: 'position:fixed;display:none;width:400px;height:400px;top:50%;left:50%;margin-top:-200px;margin-left:-200px;z-index:99991', shadow: abs+'background:#000;width:100%;height:100%;', content: abs+'background-color:#fff;top:10px;left:10px;right:10px;bottom:10px;overflow:hidden', info: abs+'bottom:10px;left:10px;right:10px;color:#444;font:11px/13px arial,sans-serif;height:13px', close: abs+'top:10px;right:10px;height:20px;width:20px;background:#fff;text-align:center;cursor:pointer;color:#444;font:16px/22px arial,sans-serif;z-index:99999', image: abs+'top:10px;left:10px;right:10px;bottom:30px;overflow:hidden;display:block;', prevholder: abs+'width:50%;top:0;bottom:40px;cursor:pointer;', nextholder: abs+'width:50%;top:0;bottom:40px;right:-1px;cursor:pointer;', prev: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;left:20px;display:none;text-align:center;color:#000;font:bold 16px/36px arial,sans-serif', next: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;right:20px;left:auto;display:none;font:bold 16px/36px arial,sans-serif;text-align:center;color:#000', title: 'float:left', counter: 'float:right;margin-left:8px;' }, hover = function(elem) { return elem.hover( function() { $(this).css( 'color', '#bbb' ); }, function() { $(this).css( 'color', '#444' ); } ); }, appends = {}; // IE8 fix for IE's transparent background event "feature" if ( IE && IE > 7 ) { cssMap.nextholder += 'background:#000;filter:alpha(opacity=0);'; cssMap.prevholder += 'background:#000;filter:alpha(opacity=0);'; } // create and insert CSS $.each(cssMap, function( key, value ) { css += '.galleria-'+prefix+key+'{'+value+'}'; }); css += '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'prevholder,'+ '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'nextholder{'+ 'width:100px;height:100px;top:50%;margin-top:-70px}'; Utils.insertStyleTag( css ); // create the elements $.each(elems.split(' '), function( i, elemId ) { self.addElement( 'lightbox-' + elemId ); el[ elemId ] = lightbox.elems[ elemId ] = self.get( 'lightbox-' + elemId ); }); // initiate the image lightbox.image = new Galleria.Picture(); // append the elements $.each({ box: 'shadow content close prevholder nextholder', info: 'title counter', content: 'info image', prevholder: 'prev', nextholder: 'next' }, function( key, val ) { var arr = []; $.each( val.split(' '), function( i, prop ) { arr.push( prefix + prop ); }); appends[ prefix+key ] = arr; }); self.append( appends ); $( el.image ).append( lightbox.image.container ); $( DOM().body ).append( el.overlay, el.box ); Utils.optimizeTouch( el.box ); // add the prev/next nav and bind some controls hover( $( el.close ).bind( 'click', lightbox.hide ).html('&#215;') ); $.each( ['Prev','Next'], function(i, dir) { var $d = $( el[ dir.toLowerCase() ] ).html( /v/.test( dir ) ? '&#8249;&nbsp;' : '&nbsp;&#8250;' ), $e = $( el[ dir.toLowerCase()+'holder'] ); $e.bind( 'click', function() { lightbox[ 'show' + dir ](); }); // IE7 and touch devices will simply show the nav if ( IE < 8 || Galleria.TOUCH ) { $d.show(); return; } $e.hover( function() { $d.show(); }, function(e) { $d.stop().fadeOut( 200 ); }); }); $( el.overlay ).bind( 'click', lightbox.hide ); // the lightbox animation is slow on ipad if ( Galleria.IPAD ) { self._options.lightboxTransitionSpeed = 0; } }, rescale: function(event) { // calculate var width = Math.min( $win.width()-40, lightbox.width ), height = Math.min( $win.height()-60, lightbox.height ), ratio = Math.min( width / lightbox.width, height / lightbox.height ), destWidth = Math.round( lightbox.width * ratio ) + 40, destHeight = Math.round( lightbox.height * ratio ) + 60, to = { width: destWidth, height: destHeight, 'margin-top': Math.ceil( destHeight / 2 ) *- 1, 'margin-left': Math.ceil( destWidth / 2 ) *- 1 }; // if rescale event, don't animate if ( event ) { $( lightbox.elems.box ).css( to ); } else { $( lightbox.elems.box ).animate( to, { duration: self._options.lightboxTransitionSpeed, easing: self._options.easing, complete: function() { var image = lightbox.image, speed = self._options.lightboxFadeSpeed; self.trigger({ type: Galleria.LIGHTBOX_IMAGE, imageTarget: image.image }); $( image.container ).show(); $( image.image ).animate({ opacity: 1 }, speed); Utils.show( lightbox.elems.info, speed ); } }); } }, hide: function() { // remove the image lightbox.image.image = null; $win.unbind('resize', lightbox.rescale); $( lightbox.elems.box ).hide(); Utils.hide( lightbox.elems.info ); self.detachKeyboard(); self.attachKeyboard( lightbox.keymap ); lightbox.keymap = false; Utils.hide( lightbox.elems.overlay, 200, function() { $( this ).hide().css( 'opacity', self._options.overlayOpacity ); self.trigger( Galleria.LIGHTBOX_CLOSE ); }); }, showNext: function() { lightbox.show( self.getNext( lightbox.active ) ); }, showPrev: function() { lightbox.show( self.getPrev( lightbox.active ) ); }, show: function(index) { lightbox.active = index = typeof index === 'number' ? index : self.getIndex() || 0; if ( !lightbox.initialized ) { lightbox.init(); } // temporarily attach some keys // save the old ones first in a cloned object if ( !lightbox.keymap ) { lightbox.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: lightbox.hide, right: lightbox.showNext, left: lightbox.showPrev }); } $win.unbind('resize', lightbox.rescale ); var data = self.getData(index), total = self.getDataLength(), n = self.getNext( index ), ndata, p, i; Utils.hide( lightbox.elems.info ); try { for ( i = self._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = self.getData( n ); p.preload( 'big' in ndata ? ndata.big : ndata.image ); n = self.getNext( n ); } } catch(e) {} lightbox.image.isIframe = !!data.iframe; $(lightbox.elems.box).toggleClass( 'iframe', !!data.iframe ); lightbox.image.load( data.iframe || data.big || data.image, function( image ) { lightbox.width = image.isIframe ? $(window).width() : image.original.width; lightbox.height = image.isIframe ? $(window).height() : image.original.height; $( image.image ).css({ width: image.isIframe ? '100%' : '100.1%', height: image.isIframe ? '100%' : '100.1%', top: 0, zIndex: 99998, opacity: 0, visibility: 'visible' }); lightbox.elems.title.innerHTML = data.title || ''; lightbox.elems.counter.innerHTML = (index + 1) + ' / ' + total; $win.resize( lightbox.rescale ); lightbox.rescale(); }); $( lightbox.elems.overlay ).show().css( 'visibility', 'visible' ); $( lightbox.elems.box ).show(); } }; // the internal timeouts object // provides helper methods for controlling timeouts var _timer = this._timer = { trunk: {}, add: function( id, fn, delay, loop ) { id = id || new Date().getTime(); loop = loop || false; this.clear( id ); if ( loop ) { var old = fn; fn = function() { old(); _timer.add( id, fn, delay ); }; } this.trunk[ id ] = window.setTimeout( fn, delay ); }, clear: function( id ) { var del = function( i ) { window.clearTimeout( this.trunk[ i ] ); delete this.trunk[ i ]; }, i; if ( !!id && id in this.trunk ) { del.call( this, id ); } else if ( typeof id === 'undefined' ) { for ( i in this.trunk ) { if ( this.trunk.hasOwnProperty( i ) ) { del.call( this, i ); } } } } }; return this; }; // end Galleria constructor Galleria.prototype = { // bring back the constructor reference constructor: Galleria, /** Use this function to initialize the gallery and start loading. Should only be called once per instance. @param {HTMLElement} target The target element @param {Object} options The gallery options @returns Instance */ init: function( target, options ) { var self = this; options = _legacyOptions( options ); // save the original ingredients this._original = { target: target, options: options, data: null }; // save the target here this._target = this._dom.target = target.nodeName ? target : $( target ).get(0); // save the original content for destruction this._original.html = this._target.innerHTML; // push the instance _instances.push( this ); // raise error if no target is detected if ( !this._target ) { Galleria.raise('Target not found', true); return; } // apply options this._options = { autoplay: false, carousel: true, carouselFollow: true, // legacy, deprecate at 1.3 carouselSpeed: 400, carouselSteps: 'auto', clicknext: false, dailymotion: { foreground: '%23EEEEEE', highlight: '%235BCEC5', background: '%23222222', logo: 0, hideInfos: 1 }, dataConfig : function( elem ) { return {}; }, dataSelector: 'img', dataSort: false, dataSource: this._target, debug: undef, dummy: undef, // 1.2.5 easing: 'galleria', extend: function(options) {}, fullscreenCrop: undef, // 1.2.5 fullscreenDoubleTap: true, // 1.2.4 toggles fullscreen on double-tap for touch devices fullscreenTransition: undef, // 1.2.6 height: 0, idleMode: true, // 1.2.4 toggles idleMode idleTime: 3000, idleSpeed: 200, imageCrop: false, imageMargin: 0, imagePan: false, imagePanSmoothness: 12, imagePosition: '50%', imageTimeout: undef, // 1.2.5 initialTransition: undef, // 1.2.4, replaces transitionInitial keepSource: false, layerFollow: true, // 1.2.5 lightbox: false, // 1.2.3 lightboxFadeSpeed: 200, lightboxTransitionSpeed: 200, linkSourceImages: true, maxScaleRatio: undef, minScaleRatio: undef, overlayOpacity: 0.85, overlayBackground: '#0b0b0b', pauseOnInteraction: true, popupLinks: false, preload: 2, queue: true, responsive: true, show: 0, showInfo: true, showCounter: true, showImagenav: true, swipe: true, // 1.2.4 thumbCrop: true, thumbEventType: 'click', thumbFit: true, // legacy, deprecate at 1.3 thumbMargin: 0, thumbQuality: 'auto', thumbDisplayOrder: true, // 1.2.8 thumbnails: true, touchTransition: undef, // 1.2.6 transition: 'fade', transitionInitial: undef, // legacy, deprecate in 1.3. Use initialTransition instead. transitionSpeed: 400, trueFullscreen: true, // 1.2.7 useCanvas: false, // 1.2.4 vimeo: { title: 0, byline: 0, portrait: 0, color: 'aaaaaa' }, wait: 5000, // 1.2.7 width: 'auto', youtube: { modestbranding: 1, autohide: 1, color: 'white', hd: 1, rel: 0, showinfo: 0 } }; // legacy support for transitionInitial this._options.initialTransition = this._options.initialTransition || this._options.transitionInitial; // turn off debug if ( options && options.debug === false ) { DEBUG = false; } // set timeout if ( options && typeof options.imageTimeout === 'number' ) { TIMEOUT = options.imageTimeout; } // set dummy if ( options && typeof options.dummy === 'string' ) { DUMMY = options.dummy; } // hide all content $( this._target ).children().hide(); // now we just have to wait for the theme... if ( typeof Galleria.theme === 'object' ) { this._init(); } else { // push the instance into the pool and run it when the theme is ready _pool.push( this ); } return this; }, // this method should only be called once per instance // for manipulation of data, use the .load method _init: function() { var self = this, options = this._options; if ( this._initialized ) { Galleria.raise( 'Init failed: Gallery instance already initialized.' ); return this; } this._initialized = true; if ( !Galleria.theme ) { Galleria.raise( 'Init failed: No theme found.', true ); return this; } // merge the theme & caller options $.extend( true, options, Galleria.theme.defaults, this._original.options, Galleria.configure.options ); // check for canvas support (function( can ) { if ( !( 'getContext' in can ) ) { can = null; return; } _canvas = _canvas || { elem: can, context: can.getContext( '2d' ), cache: {}, length: 0 }; }( doc.createElement( 'canvas' ) ) ); // bind the gallery to run when data is ready this.bind( Galleria.DATA, function() { // Warn for quirks mode if ( Galleria.QUIRK ) { Galleria.raise('Your page is in Quirks mode, Galleria may not render correctly. Please validate your HTML.'); } // save the new data this._original.data = this._data; // lets show the counter here this.get('total').innerHTML = this.getDataLength(); // cache the container var $container = this.$( 'container' ); // set ratio if height is < 2 if ( self._options.height < 2 ) { self._ratio = self._options.height; } // the gallery is ready, let's just wait for the css var num = { width: 0, height: 0 }; var testHeight = function() { return self.$( 'stage' ).height(); }; // check container and thumbnail height Utils.wait({ until: function() { // keep trying to get the value num = self._getWH(); $container.width( num.width ).height( num.height ); return testHeight() && num.width && num.height > 50; }, success: function() { self._width = num.width; self._height = num.height; self._ratio = self._ratio || num.height/num.width; // for some strange reason, webkit needs a single setTimeout to play ball if ( Galleria.WEBKIT ) { window.setTimeout( function() { self._run(); }, 1); } else { self._run(); } }, error: function() { // Height was probably not set, raise hard errors if ( testHeight() ) { Galleria.raise('Could not extract sufficient width/height of the gallery container. Traced measures: width:' + num.width + 'px, height: ' + num.height + 'px.', true); } else { Galleria.raise('Could not extract a stage height from the CSS. Traced height: ' + testHeight() + 'px.', true); } }, timeout: typeof this._options.wait == 'number' ? this._options.wait : false }); }); // build the gallery frame this.append({ 'info-text' : ['info-title', 'info-description'], 'info' : ['info-text'], 'image-nav' : ['image-nav-right', 'image-nav-left'], 'stage' : ['images', 'loader', 'counter', 'image-nav'], 'thumbnails-list' : ['thumbnails'], 'thumbnails-container' : ['thumb-nav-left', 'thumbnails-list', 'thumb-nav-right'], 'container' : ['stage', 'thumbnails-container', 'info', 'tooltip'] }); Utils.hide( this.$( 'counter' ).append( this.get( 'current' ), doc.createTextNode(' / '), this.get( 'total' ) ) ); this.setCounter('&#8211;'); Utils.hide( self.get('tooltip') ); // add a notouch class on the container to prevent unwanted :hovers on touch devices this.$( 'container' ).addClass( Galleria.TOUCH ? 'touch' : 'notouch' ); // add images to the controls $.each( new Array(2), function( i ) { // create a new Picture instance var image = new Galleria.Picture(); // apply some styles, create & prepend overlay $( image.container ).css({ position: 'absolute', top: 0, left: 0 }).prepend( self._layers[i] = $( Utils.create('galleria-layer') ).css({ position: 'absolute', top:0, left:0, right:0, bottom:0, zIndex:2 })[0] ); // append the image self.$( 'images' ).append( image.container ); // reload the controls self._controls[i] = image; }); // some forced generic styling this.$( 'images' ).css({ position: 'relative', top: 0, left: 0, width: '100%', height: '100%' }); this.$( 'thumbnails, thumbnails-list' ).css({ overflow: 'hidden', position: 'relative' }); // bind image navigation arrows this.$( 'image-nav-right, image-nav-left' ).bind( 'click', function(e) { // tune the clicknext option if ( options.clicknext ) { e.stopPropagation(); } // pause if options is set if ( options.pauseOnInteraction ) { self.pause(); } // navigate var fn = /right/.test( this.className ) ? 'next' : 'prev'; self[ fn ](); }); // hide controls if chosen to $.each( ['info','counter','image-nav'], function( i, el ) { if ( options[ 'show' + el.substr(0,1).toUpperCase() + el.substr(1).replace(/-/,'') ] === false ) { Utils.moveOut( self.get( el.toLowerCase() ) ); } }); // load up target content this.load(); // now it's usually safe to remove the content // IE will never stop loading if we remove it, so let's keep it hidden for IE (it's usually fast enough anyway) if ( !options.keepSource && !IE ) { this._target.innerHTML = ''; } // re-append the errors, if they happened before clearing if ( this.get( 'errors' ) ) { this.appendChild( 'target', 'errors' ); } // append the gallery frame this.appendChild( 'target', 'container' ); // parse the carousel on each thumb load if ( options.carousel ) { var count = 0, show = options.show; this.bind( Galleria.THUMBNAIL, function() { this.updateCarousel(); if ( ++count == this.getDataLength() && typeof show == 'number' && show > 0 ) { this._carousel.follow( show ); } }); } // bind window resize for responsiveness if ( options.responsive ) { $win.bind( 'resize', function() { if ( !self.isFullscreen() ) { self.resize(); } }); } // bind swipe gesture if ( options.swipe ) { (function( images ) { var swipeStart = [0,0], swipeStop = [0,0], limitX = 30, limitY = 100, multi = false, tid = 0, data, ev = { start: 'touchstart', move: 'touchmove', stop: 'touchend' }, getData = function(e) { return e.originalEvent.touches ? e.originalEvent.touches[0] : e; }, moveHandler = function( e ) { if ( e.originalEvent.touches && e.originalEvent.touches.length > 1 ) { return; } data = getData( e ); swipeStop = [ data.pageX, data.pageY ]; if ( !swipeStart[0] ) { swipeStart = swipeStop; } if ( Math.abs( swipeStart[0] - swipeStop[0] ) > 10 ) { e.preventDefault(); } }, upHandler = function( e ) { images.unbind( ev.move, moveHandler ); // if multitouch (possibly zooming), abort if ( ( e.originalEvent.touches && e.originalEvent.touches.length ) || multi ) { multi = !multi; return; } if ( Utils.timestamp() - tid < 1000 && Math.abs( swipeStart[0] - swipeStop[0] ) > limitX && Math.abs( swipeStart[1] - swipeStop[1] ) < limitY ) { e.preventDefault(); self[ swipeStart[0] > swipeStop[0] ? 'next' : 'prev' ](); } swipeStart = swipeStop = [0,0]; }; images.bind(ev.start, function(e) { if ( e.originalEvent.touches && e.originalEvent.touches.length > 1 ) { return; } data = getData(e); tid = Utils.timestamp(); swipeStart = swipeStop = [ data.pageX, data.pageY ]; images.bind(ev.move, moveHandler ).one(ev.stop, upHandler); }); }( self.$( 'images' ) )); // double-tap/click fullscreen toggle if ( options.fullscreenDoubleTap ) { this.$( 'stage' ).bind( 'touchstart', (function() { var last, cx, cy, lx, ly, now, getData = function(e) { return e.originalEvent.touches ? e.originalEvent.touches[0] : e; }; return function(e) { now = Galleria.utils.timestamp(); cx = getData(e).pageX; cy = getData(e).pageY; if ( ( now - last < 500 ) && ( cx - lx < 20) && ( cy - ly < 20) ) { self.toggleFullscreen(); e.preventDefault(); self.$( 'stage' ).unbind( 'touchend', arguments.callee ); return; } last = now; lx = cx; ly = cy; }; }())); } } // optimize touch for container Utils.optimizeTouch( this.get( 'container' ) ); // bind the ons $.each( Galleria.on.binds, function(i, bind) { // check if already bound if ( $.inArray( bind.hash, self._binds ) == -1 ) { self.bind( bind.type, bind.callback ); } }); return this; }, addTimer : function() { this._timer.add.apply( this._timer, Utils.array( arguments ) ); return this; }, clearTimer : function() { this._timer.clear.apply( this._timer, Utils.array( arguments ) ); return this; }, // parse width & height from CSS or options _getWH : function() { var $container = this.$( 'container' ), $target = this.$( 'target' ), self = this, num = {}, arr; $.each(['width', 'height'], function( i, m ) { // first check if options is set if ( self._options[ m ] && typeof self._options[ m ] === 'number') { num[ m ] = self._options[ m ]; } else { arr = [ Utils.parseValue( $container.css( m ) ), // the container css height Utils.parseValue( $target.css( m ) ), // the target css height $container[ m ](), // the container jQuery method $target[ m ]() // the target jQuery method ]; // if first time, include the min-width & min-height if ( !self[ '_'+m ] ) { arr.splice(arr.length, Utils.parseValue( $container.css( 'min-'+m ) ), Utils.parseValue( $target.css( 'min-'+m ) ) ); } // else extract the measures from different sources and grab the highest value num[ m ] = Math.max.apply( Math, arr ); } }); // allow setting a height ratio instead of exact value // useful when doing responsive galleries if ( self._ratio ) { num.height = num.width * self._ratio; } return num; }, // Creates the thumbnails and carousel // can be used at any time, f.ex when the data object is manipulated // push is an optional argument with pushed images _createThumbnails : function( push ) { this.get( 'total' ).innerHTML = this.getDataLength(); var src, thumb, data, special, $container, self = this, o = this._options, i = push ? this._data.length - push.length : 0, chunk = i, thumbchunk = [], loadindex = 0, gif = IE < 8 ? 'http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif' : 'data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw%3D%3D', // get previously active thumbnail, if exists active = (function() { var a = self.$('thumbnails').find('.active'); if ( !a.length ) { return false; } return a.find('img').attr('src'); }()), // cache the thumbnail option optval = typeof o.thumbnails === 'string' ? o.thumbnails.toLowerCase() : null, // move some data into the instance // for some reason, jQuery cant handle css(property) when zooming in FF, breaking the gallery // so we resort to getComputedStyle for browsers who support it getStyle = function( prop ) { return doc.defaultView && doc.defaultView.getComputedStyle ? doc.defaultView.getComputedStyle( thumb.container, null )[ prop ] : $container.css( prop ); }, fake = function(image, index, container) { return function() { $( container ).append( image ); self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: image, index: index, galleriaData: self.getData( index ) }); }; }, onThumbEvent = function( e ) { // pause if option is set if ( o.pauseOnInteraction ) { self.pause(); } // extract the index from the data var index = $( e.currentTarget ).data( 'index' ); if ( self.getIndex() !== index ) { self.show( index ); } e.preventDefault(); }, thumbComplete = function( thumb, callback ) { $( thumb.container ).css( 'visibility', 'visible' ); self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: thumb.image, index: thumb.data.order, galleriaData: self.getData( thumb.data.order ) }); if ( typeof callback == 'function' ) { callback.call( self, thumb ); } }, onThumbLoad = function( thumb, callback ) { // scale when ready thumb.scale({ width: thumb.data.width, height: thumb.data.height, crop: o.thumbCrop, margin: o.thumbMargin, canvas: o.useCanvas, complete: function( thumb ) { // shrink thumbnails to fit var top = ['left', 'top'], arr = ['Width', 'Height'], m, css, data = self.getData( thumb.index ), special = data.thumb.split(':'); // calculate shrinked positions $.each(arr, function( i, measure ) { m = measure.toLowerCase(); if ( (o.thumbCrop !== true || o.thumbCrop === m ) && o.thumbFit ) { css = {}; css[ m ] = thumb[ m ]; $( thumb.container ).css( css ); css = {}; css[ top[ i ] ] = 0; $( thumb.image ).css( css ); } // cache outer measures thumb[ 'outer' + measure ] = $( thumb.container )[ 'outer' + measure ]( true ); }); // set high quality if downscale is moderate Utils.toggleQuality( thumb.image, o.thumbQuality === true || ( o.thumbQuality === 'auto' && thumb.original.width < thumb.width * 3 ) ); // get "special" thumbs from provider if( data.iframe && special.length == 2 && special[0] in _video ) { _video[ special[0] ].getThumb( special[1], (function(img) { return function(src) { img.src = src; thumbComplete( thumb, callback ); }; }( thumb.image ) )); } else if ( o.thumbDisplayOrder && !thumb.lazy ) { $.each( thumbchunk, function( i, th ) { if ( i === loadindex && th.ready && !th.displayed ) { loadindex++; th.displayed = true; thumbComplete( th, callback ); return; } }); } else { thumbComplete( thumb, callback ); } } }); }; if ( !push ) { this._thumbnails = []; this.$( 'thumbnails' ).empty(); } // loop through data and create thumbnails for( ; this._data[ i ]; i++ ) { data = this._data[ i ]; // get source from thumb or image src = data.thumb || data.image; if ( ( o.thumbnails === true || optval == 'lazy' ) && ( data.thumb || data.image ) ) { // add a new Picture instance thumb = new Galleria.Picture(i); // save the index thumb.index = i; // flag displayed thumb.displayed = false; // flag lazy thumb.lazy = false; // flag video thumb.video = false; // append the thumbnail this.$( 'thumbnails' ).append( thumb.container ); // cache the container $container = $( thumb.container ); // hide it $container.css( 'visibility', 'hidden' ); thumb.data = { width : Utils.parseValue( getStyle( 'width' ) ), height : Utils.parseValue( getStyle( 'height' ) ), order : i, src : src }; // grab & reset size for smoother thumbnail loads if ( o.thumbFit && o.thumbCrop !== true ) { $container.css( { width: 'auto', height: 'auto' } ); } else { $container.css( { width: thumb.data.width, height: thumb.data.height } ); } // load the thumbnail special = src.split(':'); if ( special.length == 2 && special[0] in _video ) { thumb.video = true; thumb.ready = true; thumb.load( gif, { height: thumb.data.height, width: thumb.data.height*1.25 }, onThumbLoad); } else if ( optval == 'lazy' ) { $container.addClass( 'lazy' ); thumb.lazy = true; thumb.load( gif, { height: thumb.data.height, width: thumb.data.width }); } else { thumb.load( src, onThumbLoad ); } // preload all images here if ( o.preload === 'all' ) { thumb.preload( data.image ); } // create empty spans if thumbnails is set to 'empty' } else if ( data.iframe || optval === 'empty' || optval === 'numbers' ) { thumb = { container: Utils.create( 'galleria-image' ), image: Utils.create( 'img', 'span' ), ready: true }; // create numbered thumbnails if ( optval === 'numbers' ) { $( thumb.image ).text( i + 1 ); } if ( data.iframe ) { $( thumb.image ).addClass( 'iframe' ); } this.$( 'thumbnails' ).append( thumb.container ); // we need to "fake" a loading delay before we append and trigger // 50+ should be enough window.setTimeout( ( fake )( thumb.image, i, thumb.container ), 50 + ( i*20 ) ); // create null object to silent errors } else { thumb = { container: null, image: null }; } // add events for thumbnails // you can control the event type using thumb_event_type // we'll add the same event to the source if it's kept $( thumb.container ).add( o.keepSource && o.linkSourceImages ? data.original : null ) .data('index', i).bind( o.thumbEventType, onThumbEvent ) .data('thumbload', onThumbLoad); if (active === src) { $( thumb.container ).addClass( 'active' ); } this._thumbnails.push( thumb ); } thumbchunk = this._thumbnails.slice( chunk ); return this; }, /** Lazy-loads thumbnails. You can call this method to load lazy thumbnails at run time @param {Array|Number} index Index or array of indexes of thumbnails to be loaded @param {Function} complete Callback that is called when all lazy thumbnails have been loaded @returns Instance */ lazyLoad: function( index, complete ) { var arr = index.constructor == Array ? index : [ index ], self = this, thumbnails = this.$( 'thumbnails' ).children().filter(function() { return $(this).data('lazy-src'); }), loaded = 0; $.each( arr, function(i, ind) { if ( ind > self._thumbnails.length - 1 ) { return; } var thumb = self._thumbnails[ ind ], data = thumb.data, special = data.src.split(':'), callback = function() { if ( ++loaded == arr.length && typeof complete == 'function' ) { complete.call( self ); } }, thumbload = $( thumb.container ).data( 'thumbload' ); if ( thumb.video ) { thumbload.call( self, thumb, callback ); } else { thumb.load( data.src , function( thumb ) { thumbload.call( self, thumb, callback ); }); } }); return this; }, /** Lazy-loads thumbnails in chunks. This method automatcally chops up the loading process of many thumbnails into chunks @param {Number} size Size of each chunk to be loaded @param {Number} [delay] Delay between each loads @returns Instance */ lazyLoadChunks: function( size, delay ) { var len = this.getDataLength(), i = 0, n = 0, arr = [], temp = [], self = this; delay = delay || 0; for( ; i<len; i++ ) { temp.push(i); if ( ++n == size || i == len-1 ) { arr.push( temp ); n = 0; temp = []; } } var init = function( wait ) { var a = arr.shift(); if ( a ) { window.setTimeout(function() { self.lazyLoad(a, function() { init( true ); }); }, ( delay && wait ) ? delay : 0 ); } }; init( false ); return this; }, // the internal _run method should be called after loading data into galleria // makes sure the gallery has proper measurements before postrun & ready _run : function() { var self = this; self._createThumbnails(); // make sure we have a stageHeight && stageWidth Utils.wait({ timeout: 10000, until: function() { // Opera crap if ( Galleria.OPERA ) { self.$( 'stage' ).css( 'display', 'inline-block' ); } self._stageWidth = self.$( 'stage' ).width(); self._stageHeight = self.$( 'stage' ).height(); return( self._stageWidth && self._stageHeight > 50 ); // what is an acceptable height? }, success: function() { // save the instance _galleries.push( self ); // postrun some stuff after the gallery is ready // show counter Utils.show( self.get('counter') ); // bind carousel nav if ( self._options.carousel ) { self._carousel.bindControls(); } // start autoplay if ( self._options.autoplay ) { self.pause(); if ( typeof self._options.autoplay === 'number' ) { self._playtime = self._options.autoplay; } self._playing = true; } // if second load, just do the show and return if ( self._firstrun ) { if ( self._options.autoplay ) { self.trigger( Galleria.PLAY ); } if ( typeof self._options.show === 'number' ) { self.show( self._options.show ); } return; } self._firstrun = true; // initialize the History plugin if ( Galleria.History ) { // bind the show method Galleria.History.change(function( value ) { // if ID is NaN, the user pressed back from the first image // return to previous address if ( isNaN( value ) ) { window.history.go(-1); // else show the image } else { self.show( value, undef, true ); } }); } self.trigger( Galleria.READY ); // call the theme init method Galleria.theme.init.call( self, self._options ); // Trigger Galleria.ready $.each( Galleria.ready.callbacks, function(i ,fn) { if ( typeof fn == 'function' ) { fn.call( self, self._options ); } }); // call the extend option self._options.extend.call( self, self._options ); // show the initial image // first test for permalinks in history if ( /^[0-9]{1,4}$/.test( HASH ) && Galleria.History ) { self.show( HASH, undef, true ); } else if( self._data[ self._options.show ] ) { self.show( self._options.show ); } // play trigger if ( self._options.autoplay ) { self.trigger( Galleria.PLAY ); } }, error: function() { Galleria.raise('Stage width or height is too small to show the gallery. Traced measures: width:' + self._stageWidth + 'px, height: ' + self._stageHeight + 'px.', true); } }); }, /** Loads data into the gallery. You can call this method on an existing gallery to reload the gallery with new data. @param {Array|string} [source] Optional JSON array of data or selector of where to find data in the document. Defaults to the Galleria target or dataSource option. @param {string} [selector] Optional element selector of what elements to parse. Defaults to 'img'. @param {Function} [config] Optional function to modify the data extraction proceedure from the selector. See the dataConfig option for more information. @returns Instance */ load : function( source, selector, config ) { var self = this, o = this._options; // empty the data array this._data = []; // empty the thumbnails this._thumbnails = []; this.$('thumbnails').empty(); // shorten the arguments if ( typeof selector === 'function' ) { config = selector; selector = null; } // use the source set by target source = source || o.dataSource; // use selector set by option selector = selector || o.dataSelector; // use the dataConfig set by option config = config || o.dataConfig; // if source is a true object, make it into an array if( /^function Object/.test( source.constructor ) ) { source = [source]; } // check if the data is an array already if ( source.constructor === Array ) { if ( this.validate( source ) ) { this._data = source; } else { Galleria.raise( 'Load failed: JSON Array not valid.' ); } } else { // add .video and .iframe to the selector (1.2.7) selector += ',.video,.iframe'; // loop through images and set data $( source ).find( selector ).each( function( i, elem ) { elem = $( elem ); var data = {}, parent = elem.parent(), href = parent.attr( 'href' ), rel = parent.attr( 'rel' ); if( href && ( elem[0].nodeName == 'IMG' || elem.hasClass('video') ) && _videoTest( href ) ) { data.video = href; } else if( href && elem.hasClass('iframe') ) { data.iframe = href; } else { data.image = data.big = href; } if ( rel ) { data.big = rel; } // alternative extraction from HTML5 data attribute, added in 1.2.7 $.each( 'big title description link layer'.split(' '), function( i, val ) { if ( elem.data(val) ) { data[ val ] = elem.data(val); } }); // mix default extractions with the hrefs and config // and push it into the data array self._data.push( $.extend({ title: elem.attr('title') || '', thumb: elem.attr('src'), image: elem.attr('src'), big: elem.attr('src'), description: elem.attr('alt') || '', link: elem.attr('longdesc'), original: elem.get(0) // saved as a reference }, data, config( elem ) ) ); }); } if ( typeof o.dataSort == 'function' ) { protoArray.sort.call( this._data, o.dataSort ); } else if ( o.dataSort == 'random' ) { this._data.sort( function() { return Math.round(Math.random())-0.5; }); } // trigger the DATA event and return if ( this.getDataLength() ) { this._parseData().trigger( Galleria.DATA ); } return this; }, // make sure the data works properly _parseData : function() { var self = this, current; $.each( this._data, function( i, data ) { current = self._data[ i ]; // copy image as thumb if no thumb exists if ( 'thumb' in data === false ) { current.thumb = data.image; } // copy image as big image if no biggie exists if ( !'big' in data ) { current.big = data.image; } // parse video if ( 'video' in data ) { var result = _videoTest( data.video ); if ( result ) { current.iframe = _video[ result.provider ].embed( result.id ) + (function() { // add options if ( typeof self._options[ result.provider ] == 'object' ) { var str = '?', arr = []; $.each( self._options[ result.provider ], function( key, val ) { arr.push( key + '=' + val ); }); // small youtube specifics, perhaps move to _video later if ( result.provider == 'youtube' ) { arr = ['wmode=opaque'].concat(arr); } return str + arr.join('&'); } return ''; }()); delete current.video; if( !('thumb' in current) || !current.thumb ) { current.thumb = result.provider+':'+result.id; } } } }); return this; }, /** Destroy the Galleria instance and recover the original content @example this.destroy(); @returns Instance */ destroy : function() { this.get('target').innerHTML = this._original.html; this.clearTimer(); return this; }, /** Adds and/or removes images from the gallery Works just like Array.splice https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice @example this.splice( 2, 4 ); // removes 4 images after the second image @returns Instance */ splice : function() { var self = this, args = Utils.array( arguments ); window.setTimeout(function() { protoArray.splice.apply( self._data, args ); self._parseData()._createThumbnails(); },2); return self; }, /** Append images to the gallery Works just like Array.push https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push @example this.push({ image: 'image1.jpg' }); // appends the image to the gallery @returns Instance */ push : function() { var self = this, args = Utils.array( arguments ); if ( args.length == 1 && args[0].constructor == Array ) { args = args[0]; } window.setTimeout(function() { protoArray.push.apply( self._data, args ); self._parseData()._createThumbnails( args ); },2); return self; }, _getActive: function() { return this._controls.getActive(); }, validate : function( data ) { // todo: validate a custom data array return true; }, /** Bind any event to Galleria @param {string} type The Event type to listen for @param {Function} fn The function to execute when the event is triggered @example this.bind( 'image', function() { Galleria.log('image shown') }); @returns Instance */ bind : function(type, fn) { // allow 'image' instead of Galleria.IMAGE type = _patchEvent( type ); this.$( 'container' ).bind( type, this.proxy(fn) ); return this; }, /** Unbind any event to Galleria @param {string} type The Event type to forget @returns Instance */ unbind : function(type) { type = _patchEvent( type ); this.$( 'container' ).unbind( type ); return this; }, /** Manually trigger a Galleria event @param {string} type The Event to trigger @returns Instance */ trigger : function( type ) { type = typeof type === 'object' ? $.extend( type, { scope: this } ) : { type: _patchEvent( type ), scope: this }; this.$( 'container' ).trigger( type ); return this; }, /** Assign an "idle state" to any element. The idle state will be applied after a certain amount of idle time Useful to hide f.ex navigation when the gallery is inactive @param {HTMLElement|string} elem The Dom node or selector to apply the idle state to @param {Object} styles the CSS styles to apply when in idle mode @param {Object} [from] the CSS styles to apply when in normal @param {Boolean} [hide] set to true if you want to hide it first @example addIdleState( this.get('image-nav'), { opacity: 0 }); @example addIdleState( '.galleria-image-nav', { top: -200 }, true); @returns Instance */ addIdleState: function( elem, styles, from, hide ) { this._idle.add.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Removes any idle state previously set using addIdleState() @param {HTMLElement|string} elem The Dom node or selector to remove the idle state from. @returns Instance */ removeIdleState: function( elem ) { this._idle.remove.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Force Galleria to enter idle mode. @returns Instance */ enterIdleMode: function() { this._idle.hide(); return this; }, /** Force Galleria to exit idle mode. @returns Instance */ exitIdleMode: function() { this._idle.showAll(); return this; }, /** Enter FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ enterFullscreen: function( callback ) { this._fullscreen.enter.apply( this, Utils.array( arguments ) ); return this; }, /** Exits FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ exitFullscreen: function( callback ) { this._fullscreen.exit.apply( this, Utils.array( arguments ) ); return this; }, /** Toggle FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied or removed. @returns Instance */ toggleFullscreen: function( callback ) { this._fullscreen[ this.isFullscreen() ? 'exit' : 'enter'].apply( this, Utils.array( arguments ) ); return this; }, /** Adds a tooltip to any element. You can also call this method with an object as argument with elemID:value pairs to apply tooltips to (see examples) @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @example this.bindTooltip( this.get('thumbnails'), 'My thumbnails'); @example this.bindTooltip( this.get('thumbnails'), function() { return 'My thumbs' }); @example this.bindTooltip( { image_nav: 'Navigation' }); @returns Instance */ bindTooltip: function( elem, value ) { this._tooltip.bind.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Note: this method is deprecated. Use refreshTooltip() instead. Redefine a tooltip. Use this if you want to re-apply a tooltip value to an already bound tooltip element. @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @returns Instance */ defineTooltip: function( elem, value ) { this._tooltip.define.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Refresh a tooltip value. Use this if you want to change the tooltip value at runtime, f.ex if you have a play/pause toggle. @param {HTMLElement} elem The DOM Node that has a tooltip that should be refreshed @returns Instance */ refreshTooltip: function( elem ) { this._tooltip.show.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Open a pre-designed lightbox with the currently active image. You can control some visuals using gallery options. @returns Instance */ openLightbox: function() { this._lightbox.show.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Close the lightbox. @returns Instance */ closeLightbox: function() { this._lightbox.hide.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Get the currently active image element. @returns {HTMLElement} The image element */ getActiveImage: function() { return this._getActive().image || undef; }, /** Get the currently active thumbnail element. @returns {HTMLElement} The thumbnail element */ getActiveThumb: function() { return this._thumbnails[ this._active ].image || undef; }, /** Get the mouse position relative to the gallery container @param e The mouse event @example var gallery = this; $(document).mousemove(function(e) { console.log( gallery.getMousePosition(e).x ); }); @returns {Object} Object with x & y of the relative mouse postion */ getMousePosition : function(e) { return { x: e.pageX - this.$( 'container' ).offset().left, y: e.pageY - this.$( 'container' ).offset().top }; }, /** Adds a panning effect to the image @param [img] The optional image element. If not specified it takes the currently active image @returns Instance */ addPan : function( img ) { if ( this._options.imageCrop === false ) { return; } img = $( img || this.getActiveImage() ); // define some variables and methods var self = this, x = img.width() / 2, y = img.height() / 2, destX = parseInt( img.css( 'left' ), 10 ), destY = parseInt( img.css( 'top' ), 10 ), curX = destX || 0, curY = destY || 0, distX = 0, distY = 0, active = false, ts = Utils.timestamp(), cache = 0, move = 0, // positions the image position = function( dist, cur, pos ) { if ( dist > 0 ) { move = Math.round( Math.max( dist * -1, Math.min( 0, cur ) ) ); if ( cache !== move ) { cache = move; if ( IE === 8 ) { // scroll is faster for IE img.parent()[ 'scroll' + pos ]( move * -1 ); } else { var css = {}; css[ pos.toLowerCase() ] = move; img.css(css); } } } }, // calculates mouse position after 50ms calculate = function(e) { if (Utils.timestamp() - ts < 50) { return; } active = true; x = self.getMousePosition(e).x; y = self.getMousePosition(e).y; }, // the main loop to check loop = function(e) { if (!active) { return; } distX = img.width() - self._stageWidth; distY = img.height() - self._stageHeight; destX = x / self._stageWidth * distX * -1; destY = y / self._stageHeight * distY * -1; curX += ( destX - curX ) / self._options.imagePanSmoothness; curY += ( destY - curY ) / self._options.imagePanSmoothness; position( distY, curY, 'Top' ); position( distX, curX, 'Left' ); }; // we need to use scroll in IE8 to speed things up if ( IE === 8 ) { img.parent().scrollTop( curY * -1 ).scrollLeft( curX * -1 ); img.css({ top: 0, left: 0 }); } // unbind and bind event this.$( 'stage' ).unbind( 'mousemove', calculate ).bind( 'mousemove', calculate ); // loop the loop this.addTimer( 'pan' + self._id, loop, 50, true); return this; }, /** Brings the scope into any callback @param fn The callback to bring the scope into @param [scope] Optional scope to bring @example $('#fullscreen').click( this.proxy(function() { this.enterFullscreen(); }) ) @returns {Function} Return the callback with the gallery scope */ proxy : function( fn, scope ) { if ( typeof fn !== 'function' ) { return F; } scope = scope || this; return function() { return fn.apply( scope, Utils.array( arguments ) ); }; }, /** Removes the panning effect set by addPan() @returns Instance */ removePan: function() { // todo: doublecheck IE8 this.$( 'stage' ).unbind( 'mousemove' ); this.clearTimer( 'pan' + this._id ); return this; }, /** Adds an element to the Galleria DOM array. When you add an element here, you can access it using element ID in many API calls @param {string} id The element ID you wish to use. You can add many elements by adding more arguments. @example addElement('mybutton'); @example addElement('mybutton','mylink'); @returns Instance */ addElement : function( id ) { var dom = this._dom; $.each( Utils.array(arguments), function( i, blueprint ) { dom[ blueprint ] = Utils.create( 'galleria-' + blueprint ); }); return this; }, /** Attach keyboard events to Galleria @param {Object} map The map object of events. Possible keys are 'UP', 'DOWN', 'LEFT', 'RIGHT', 'RETURN', 'ESCAPE', 'BACKSPACE', and 'SPACE'. @example this.attachKeyboard({ right: this.next, left: this.prev, up: function() { console.log( 'up key pressed' ) } }); @returns Instance */ attachKeyboard : function( map ) { this._keyboard.attach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Detach all keyboard events to Galleria @returns Instance */ detachKeyboard : function() { this._keyboard.detach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Fast helper for appending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be appended @param {string} childID the element ID that should be appended @example this.addElement('myElement'); this.appendChild( 'info', 'myElement' ); @returns Instance */ appendChild : function( parentID, childID ) { this.$( parentID ).append( this.get( childID ) || childID ); return this; }, /** Fast helper for prepending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be prepended @param {string} childID the element ID that should be prepended @example this.addElement('myElement'); this.prependChild( 'info', 'myElement' ); @returns Instance */ prependChild : function( parentID, childID ) { this.$( parentID ).prepend( this.get( childID ) || childID ); return this; }, /** Remove an element by blueprint @param {string} elemID The element to be removed. You can remove multiple elements by adding arguments. @returns Instance */ remove : function( elemID ) { this.$( Utils.array( arguments ).join(',') ).remove(); return this; }, // a fast helper for building dom structures // leave this out of the API for now append : function( data ) { var i, j; for( i in data ) { if ( data.hasOwnProperty( i ) ) { if ( data[i].constructor === Array ) { for( j = 0; data[i][j]; j++ ) { this.appendChild( i, data[i][j] ); } } else { this.appendChild( i, data[i] ); } } } return this; }, // an internal helper for scaling according to options _scaleImage : function( image, options ) { image = image || this._controls.getActive(); // janpub (JH) fix: // image might be unselected yet // e.g. when external logics rescales the gallery on window resize events if( !image ) { return; } var self = this, complete, scaleLayer = function( img ) { $( img.container ).children(':first').css({ top: Math.max(0, Utils.parseValue( img.image.style.top )), left: Math.max(0, Utils.parseValue( img.image.style.left )), width: Utils.parseValue( img.image.width ), height: Utils.parseValue( img.image.height ) }); }; options = $.extend({ width: this._stageWidth, height: this._stageHeight, crop: this._options.imageCrop, max: this._options.maxScaleRatio, min: this._options.minScaleRatio, margin: this._options.imageMargin, position: this._options.imagePosition }, options ); if ( this._options.layerFollow && this._options.imageCrop !== true ) { if ( typeof options.complete == 'function' ) { complete = options.complete; options.complete = function() { complete.call( image, image ); scaleLayer( image ); }; } else { options.complete = scaleLayer; } } else { $( image.container ).children(':first').css({ top: 0, left: 0 }); } image.scale( options ); return this; }, /** Updates the carousel, useful if you resize the gallery and want to re-check if the carousel nav is needed. @returns Instance */ updateCarousel : function() { this._carousel.update(); return this; }, /** Resize the entire gallery container @param {Object} [measures] Optional object with width/height specified @param {Function} [complete] The callback to be called when the scaling is complete @returns Instance */ resize : function( measures, complete ) { if ( typeof measures == 'function' ) { complete = measures; measures = undef; } measures = $.extend( { width:0, height:0 }, measures ); var self = this, $container = this.$( 'container' ); $.each( measures, function( m, val ) { if ( !val ) { $container[ m ]( 'auto' ); measures[ m ] = self._getWH()[ m ]; } }); $.each( measures, function( m, val ) { $container[ m ]( val ); }); return this.rescale( complete ); }, /** Rescales the gallery @param {number} width The target width @param {number} height The target height @param {Function} complete The callback to be called when the scaling is complete @returns Instance */ rescale : function( width, height, complete ) { var self = this; // allow rescale(fn) if ( typeof width === 'function' ) { complete = width; width = undef; } var scale = function() { // set stagewidth self._stageWidth = width || self.$( 'stage' ).width(); self._stageHeight = height || self.$( 'stage' ).height(); // scale the active image self._scaleImage(); if ( self._options.carousel ) { self.updateCarousel(); } self.trigger( Galleria.RESCALE ); if ( typeof complete === 'function' ) { complete.call( self ); } }; scale.call( self ); return this; }, /** Refreshes the gallery. Useful if you change image options at runtime and want to apply the changes to the active image. @returns Instance */ refreshImage : function() { this._scaleImage(); if ( this._options.imagePan ) { this.addPan(); } return this; }, /** Shows an image by index @param {number|boolean} index The index to show @param {Boolean} rewind A boolean that should be true if you want the transition to go back @returns Instance */ show : function( index, rewind, _history ) { // do nothing if index is false or queue is false and transition is in progress if ( index === false || ( !this._options.queue && this._queue.stalled ) ) { return; } index = Math.max( 0, Math.min( parseInt( index, 10 ), this.getDataLength() - 1 ) ); rewind = typeof rewind !== 'undefined' ? !!rewind : index < this.getIndex(); _history = _history || false; // do the history thing and return if ( !_history && Galleria.History ) { Galleria.History.set( index.toString() ); return; } this._active = index; protoArray.push.call( this._queue, { index : index, rewind : rewind }); if ( !this._queue.stalled ) { this._show(); } return this; }, // the internal _show method does the actual showing _show : function() { // shortcuts var self = this, queue = this._queue[ 0 ], data = this.getData( queue.index ); if ( !data ) { return; } var src = data.iframe || ( this.isFullscreen() && 'big' in data ? data.big : data.image ), // use big image if fullscreen mode active = this._controls.getActive(), next = this._controls.getNext(), cached = next.isCached( src ), thumb = this._thumbnails[ queue.index ], mousetrigger = function() { $( next.image ).trigger( 'mouseup' ); }; // to be fired when loading & transition is complete: var complete = (function( data, next, active, queue, thumb ) { return function() { var win; _transitions.active = false; // remove stalled self._queue.stalled = false; // optimize quality Utils.toggleQuality( next.image, self._options.imageQuality ); // remove old layer self._layers[ self._controls.active ].innerHTML = ''; // swap $( active.container ).css({ zIndex: 0, opacity: 0 }).show(); if( active.isIframe ) { $( active.container ).find( 'iframe' ).remove(); } self.$('container').toggleClass('iframe', !!data.iframe); $( next.container ).css({ zIndex: 1, left: 0, top: 0 }).show(); self._controls.swap(); // add pan according to option if ( self._options.imagePan ) { self.addPan( next.image ); } // make the image link or add lightbox // link takes precedence over lightbox if both are detected if ( data.link || self._options.lightbox || self._options.clicknext ) { $( next.image ).css({ cursor: 'pointer' }).bind( 'mouseup', function() { // clicknext if ( self._options.clicknext && !Galleria.TOUCH ) { if ( self._options.pauseOnInteraction ) { self.pause(); } self.next(); return; } // popup link if ( data.link ) { if ( self._options.popupLinks ) { win = window.open( data.link, '_blank' ); } else { window.location.href = data.link; } return; } if ( self._options.lightbox ) { self.openLightbox(); } }); } // remove the queued image protoArray.shift.call( self._queue ); // if we still have images in the queue, show it if ( self._queue.length ) { self._show(); } // check if we are playing self._playCheck(); // trigger IMAGE event self.trigger({ type: Galleria.IMAGE, index: queue.index, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); }; }( data, next, active, queue, thumb )); // let the carousel follow if ( this._options.carousel && this._options.carouselFollow ) { this._carousel.follow( queue.index ); } // preload images if ( this._options.preload ) { var p, i, n = this.getNext(), ndata; try { for ( i = this._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = self.getData( n ); p.preload( this.isFullscreen() && 'big' in ndata ? ndata.big : ndata.image ); n = self.getNext( n ); } } catch(e) {} } // show the next image, just in case Utils.show( next.container ); next.isIframe = !!data.iframe; // add active classes $( self._thumbnails[ queue.index ].container ) .addClass( 'active' ) .siblings( '.active' ) .removeClass( 'active' ); // trigger the LOADSTART event self.trigger( { type: Galleria.LOADSTART, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); // begin loading the next image next.load( src, function( next ) { // add layer HTML var layer = $( self._layers[ 1-self._controls.active ] ).html( data.layer || '' ).hide(); self._scaleImage( next, { complete: function( next ) { // toggle low quality for IE if ( 'image' in active ) { Utils.toggleQuality( active.image, false ); } Utils.toggleQuality( next.image, false ); // stall the queue self._queue.stalled = true; // remove the image panning, if applied // TODO: rethink if this is necessary self.removePan(); // set the captions and counter self.setInfo( queue.index ); self.setCounter( queue.index ); // show the layer now if ( data.layer ) { layer.show(); // inherit click events set on image if ( data.link || self._options.lightbox || self._options.clicknext ) { layer.css( 'cursor', 'pointer' ).unbind( 'mouseup' ).mouseup( mousetrigger ); } } // trigger the LOADFINISH event self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: self._thumbnails[ queue.index ].image, galleriaData: self.getData( queue.index ) }); var transition = self._options.transition; // can JavaScript loop through objects in order? yes. $.each({ initial: active.image === null, touch: Galleria.TOUCH, fullscreen: self.isFullscreen() }, function( type, arg ) { if ( arg && self._options[ type + 'Transition' ] !== undef ) { transition = self._options[ type + 'Transition' ]; return false; } }); // validate the transition if ( transition in _transitions.effects === false ) { complete(); } else { var params = { prev: active.container, next: next.container, rewind: queue.rewind, speed: self._options.transitionSpeed || 400 }; _transitions.active = true; // call the transition function and send some stuff _transitions.init.call( self, transition, params, complete ); } } }); }); }, /** Gets the next index @param {number} [base] Optional starting point @returns {number} the next index, or the first if you are at the first (looping) */ getNext : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === this.getDataLength() - 1 ? 0 : base + 1; }, /** Gets the previous index @param {number} [base] Optional starting point @returns {number} the previous index, or the last if you are at the first (looping) */ getPrev : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === 0 ? this.getDataLength() - 1 : base - 1; }, /** Shows the next image in line @returns Instance */ next : function() { if ( this.getDataLength() > 1 ) { this.show( this.getNext(), false ); } return this; }, /** Shows the previous image in line @returns Instance */ prev : function() { if ( this.getDataLength() > 1 ) { this.show( this.getPrev(), true ); } return this; }, /** Retrieve a DOM element by element ID @param {string} elemId The delement ID to fetch @returns {HTMLElement} The elements DOM node or null if not found. */ get : function( elemId ) { return elemId in this._dom ? this._dom[ elemId ] : null; }, /** Retrieve a data object @param {number} index The data index to retrieve. If no index specified it will take the currently active image @returns {Object} The data object */ getData : function( index ) { return index in this._data ? this._data[ index ] : this._data[ this._active ]; }, /** Retrieve the number of data items @returns {number} The data length */ getDataLength : function() { return this._data.length; }, /** Retrieve the currently active index @returns {number|boolean} The active index or false if none found */ getIndex : function() { return typeof this._active === 'number' ? this._active : false; }, /** Retrieve the stage height @returns {number} The stage height */ getStageHeight : function() { return this._stageHeight; }, /** Retrieve the stage width @returns {number} The stage width */ getStageWidth : function() { return this._stageWidth; }, /** Retrieve the option @param {string} key The option key to retrieve. If no key specified it will return all options in an object. @returns option or options */ getOptions : function( key ) { return typeof key === 'undefined' ? this._options : this._options[ key ]; }, /** Set options to the instance. You can set options using a key & value argument or a single object argument (see examples) @param {string} key The option key @param {string} value the the options value @example setOptions( 'autoplay', true ) @example setOptions({ autoplay: true }); @returns Instance */ setOptions : function( key, value ) { if ( typeof key === 'object' ) { $.extend( this._options, key ); } else { this._options[ key ] = value; } return this; }, /** Starts playing the slideshow @param {number} delay Sets the slideshow interval in milliseconds. If you set it once, you can just call play() and get the same interval the next time. @returns Instance */ play : function( delay ) { this._playing = true; this._playtime = delay || this._playtime; this._playCheck(); this.trigger( Galleria.PLAY ); return this; }, /** Stops the slideshow if currently playing @returns Instance */ pause : function() { this._playing = false; this.trigger( Galleria.PAUSE ); return this; }, /** Toggle between play and pause events. @param {number} delay Sets the slideshow interval in milliseconds. @returns Instance */ playToggle : function( delay ) { return ( this._playing ) ? this.pause() : this.play( delay ); }, /** Checks if the gallery is currently playing @returns {Boolean} */ isPlaying : function() { return this._playing; }, /** Checks if the gallery is currently in fullscreen mode @returns {Boolean} */ isFullscreen : function() { return this._fullscreen.active; }, _playCheck : function() { var self = this, played = 0, interval = 20, now = Utils.timestamp(), timer_id = 'play' + this._id; if ( this._playing ) { this.clearTimer( timer_id ); var fn = function() { played = Utils.timestamp() - now; if ( played >= self._playtime && self._playing ) { self.clearTimer( timer_id ); self.next(); return; } if ( self._playing ) { // trigger the PROGRESS event self.trigger({ type: Galleria.PROGRESS, percent: Math.ceil( played / self._playtime * 100 ), seconds: Math.floor( played / 1000 ), milliseconds: played }); self.addTimer( timer_id, fn, interval ); } }; self.addTimer( timer_id, fn, interval ); } }, /** Modify the slideshow delay @param {number} delay the number of milliseconds between slides, @returns Instance */ setPlaytime: function( delay ) { this._playtime = delay; return this; }, setIndex: function( val ) { this._active = val; return this; }, /** Manually modify the counter @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index @returns Instance */ setCounter: function( index ) { if ( typeof index === 'number' ) { index++; } else if ( typeof index === 'undefined' ) { index = this.getIndex()+1; } this.get( 'current' ).innerHTML = index; if ( IE ) { // weird IE bug var count = this.$( 'counter' ), opacity = count.css( 'opacity' ); if ( parseInt( opacity, 10 ) === 1) { Utils.removeAlpha( count[0] ); } else { this.$( 'counter' ).css( 'opacity', opacity ); } } return this; }, /** Manually set captions @param {number} [index] Optional data index to fectch and apply as caption, if no index found it assumes the currently active index @returns Instance */ setInfo : function( index ) { var self = this, data = this.getData( index ); $.each( ['title','description'], function( i, type ) { var elem = self.$( 'info-' + type ); if ( !!data[type] ) { elem[ data[ type ].length ? 'show' : 'hide' ]().html( data[ type ] ); } else { elem.empty().hide(); } }); return this; }, /** Checks if the data contains any captions @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index. @returns {boolean} */ hasInfo : function( index ) { var check = 'title description'.split(' '), i; for ( i = 0; check[i]; i++ ) { if ( !!this.getData( index )[ check[i] ] ) { return true; } } return false; }, jQuery : function( str ) { var self = this, ret = []; $.each( str.split(','), function( i, elemId ) { elemId = $.trim( elemId ); if ( self.get( elemId ) ) { ret.push( elemId ); } }); var jQ = $( self.get( ret.shift() ) ); $.each( ret, function( i, elemId ) { jQ = jQ.add( self.get( elemId ) ); }); return jQ; }, /** Converts element IDs into a jQuery collection You can call for multiple IDs separated with commas. @param {string} str One or more element IDs (comma-separated) @returns jQuery @example this.$('info,container').hide(); */ $ : function( str ) { return this.jQuery.apply( this, Utils.array( arguments ) ); } }; // End of Galleria prototype // Add events as static variables $.each( _events, function( i, ev ) { // legacy events var type = /_/.test( ev ) ? ev.replace( /_/g, '' ) : ev; Galleria[ ev.toUpperCase() ] = 'galleria.'+type; } ); $.extend( Galleria, { // Browser helpers IE9: IE === 9, IE8: IE === 8, IE7: IE === 7, IE6: IE === 6, IE: IE, WEBKIT: /webkit/.test( NAV ), CHROME: /chrome/.test( NAV ), SAFARI: /safari/.test( NAV ) && !(/chrome/.test( NAV )), QUIRK: ( IE && doc.compatMode && doc.compatMode === "BackCompat" ), MAC: /mac/.test( navigator.platform.toLowerCase() ), OPERA: !!window.opera, IPHONE: /iphone/.test( NAV ), IPAD: /ipad/.test( NAV ), ANDROID: /android/.test( NAV ), TOUCH: ('ontouchstart' in doc) }); // Galleria static methods /** Adds a theme that you can use for your Gallery @param {Object} theme Object that should contain all your theme settings. <ul> <li>name - name of the theme</li> <li>author - name of the author</li> <li>css - css file name (not path)</li> <li>defaults - default options to apply, including theme-specific options</li> <li>init - the init function</li> </ul> @returns {Object} theme */ Galleria.addTheme = function( theme ) { // make sure we have a name if ( !theme.name ) { Galleria.raise('No theme name specified'); } if ( typeof theme.defaults !== 'object' ) { theme.defaults = {}; } else { theme.defaults = _legacyOptions( theme.defaults ); } var css = false, reg; if ( typeof theme.css === 'string' ) { // look for manually added CSS $('link').each(function( i, link ) { reg = new RegExp( theme.css ); if ( reg.test( link.href ) ) { // we found the css css = true; // the themeload trigger _themeLoad( theme ); return false; } }); // else look for the absolute path and load the CSS dynamic if ( !css ) { $('script').each(function( i, script ) { // look for the theme script reg = new RegExp( 'galleria\\.' + theme.name.toLowerCase() + '\\.' ); if( reg.test( script.src )) { // we have a match css = script.src.replace(/[^\/]*$/, '') + theme.css; window.setTimeout(function() { Utils.loadCSS( css, 'galleria-theme', function() { // the themeload trigger _themeLoad( theme ); }); }, 1); } }); } if ( !css ) { Galleria.raise('No theme CSS loaded'); } } else { // pass _themeLoad( theme ); } return theme; }; /** loadTheme loads a theme js file and attaches a load event to Galleria @param {string} src The relative path to the theme source file @param {Object} [options] Optional options you want to apply @returns Galleria */ Galleria.loadTheme = function( src, options ) { var loaded = false, length = _galleries.length, err = window.setTimeout( function() { Galleria.raise( "Theme at " + src + " could not load, check theme path.", true ); }, 5000 ); // first clear the current theme, if exists Galleria.theme = undef; // load the theme Utils.loadScript( src, function() { window.clearTimeout( err ); // check for existing galleries and reload them with the new theme if ( length ) { // temporary save the new galleries var refreshed = []; // refresh all instances // when adding a new theme to an existing gallery, all options will be resetted but the data will be kept // you can apply new options as a second argument $.each( Galleria.get(), function(i, instance) { // mix the old data and options into the new instance var op = $.extend( instance._original.options, { data_source: instance._data }, options); // remove the old container instance.$('container').remove(); // create a new instance var g = new Galleria(); // move the id g._id = instance._id; // initialize the new instance g.init( instance._original.target, op ); // push the new instance refreshed.push( g ); }); // now overwrite the old holder with the new instances _galleries = refreshed; } }); return Galleria; }; /** Retrieves a Galleria instance. @param {number} [index] Optional index to retrieve. If no index is supplied, the method will return all instances in an array. @returns Instance or Array of instances */ Galleria.get = function( index ) { if ( !!_instances[ index ] ) { return _instances[ index ]; } else if ( typeof index !== 'number' ) { return _instances; } else { Galleria.raise('Gallery index ' + index + ' not found'); } }; /** Configure Galleria options via a static function. The options will be applied to all instances @param {string|object} key The options to apply or a key @param [value] If key is a string, this is the value @returns Galleria */ Galleria.configure = function( key, value ) { var opts = {}; if( typeof key == 'string' && value ) { opts[key] = value; key = opts; } else { $.extend( opts, key ); } Galleria.configure.options = opts; $.each( Galleria.get(), function(i, instance) { instance.setOptions( opts ); }); return Galleria; }; Galleria.configure.options = {}; /** Bind a Galleria event to the gallery @param {string} type A string representing the galleria event @param {function} callback The function that should run when the event is triggered @returns Galleria */ Galleria.on = function( type, callback ) { if ( !type ) { return; } callback = callback || F; // hash the bind var hash = type + callback.toString().replace(/\s/g,'') + Utils.timestamp(); // for existing instances $.each( Galleria.get(), function(i, instance) { instance._binds.push( hash ); instance.bind( type, callback ); }); // for future instances Galleria.on.binds.push({ type: type, callback: callback, hash: hash }); return Galleria; }; Galleria.on.binds = []; /** Run Galleria Alias for $(selector).galleria(options) @param {string} selector A selector of element(s) to intialize galleria to @param {object} options The options to apply @returns Galleria */ Galleria.run = function( selector, options ) { $( selector || '#galleria' ).galleria( options ); return Galleria; }; /** Creates a transition to be used in your gallery @param {string} name The name of the transition that you will use as an option @param {Function} fn The function to be executed in the transition. The function contains two arguments, params and complete. Use the params Object to integrate the transition, and then call complete when you are done. @returns Galleria */ Galleria.addTransition = function( name, fn ) { _transitions.effects[name] = fn; return Galleria; }; /** The Galleria utilites */ Galleria.utils = Utils; /** A helper metod for cross-browser logging. It uses the console log if available otherwise it falls back to alert @example Galleria.log("hello", document.body, [1,2,3]); */ Galleria.log = function() { var args = Utils.array( arguments ); if( 'console' in window && 'log' in window.console ) { try { return window.console.log.apply( window.console, args ); } catch( e ) { $.each( args, function() { window.console.log(this); }); } } else { return window.alert( args.join('<br>') ); } }; /** A ready method for adding callbacks when a gallery is ready Each method is call before the extend option for every instance @param {function} callback The function to call @returns Galleria */ Galleria.ready = function( fn ) { if ( typeof fn != 'function' ) { return Galleria; } $.each( _galleries, function( i, gallery ) { fn.call( gallery, gallery._options ); }); Galleria.ready.callbacks.push( fn ); return Galleria; }; Galleria.ready.callbacks = []; /** Method for raising errors @param {string} msg The message to throw @param {boolean} [fatal] Set this to true to override debug settings and display a fatal error */ Galleria.raise = function( msg, fatal ) { var type = fatal ? 'Fatal error' : 'Error', self = this, css = { color: '#fff', position: 'absolute', top: 0, left: 0, zIndex: 100000 }, echo = function( msg ) { var html = '<div style="padding:4px;margin:0 0 2px;background:#' + ( fatal ? '811' : '222' ) + '";>' + ( fatal ? '<strong>' + type + ': </strong>' : '' ) + msg + '</div>'; $.each( _instances, function() { var cont = this.$( 'errors' ), target = this.$( 'target' ); if ( !cont.length ) { target.css( 'position', 'relative' ); cont = this.addElement( 'errors' ).appendChild( 'target', 'errors' ).$( 'errors' ).css(css); } cont.append( html ); }); if ( !_instances.length ) { $('<div>').css( $.extend( css, { position: 'fixed' } ) ).append( html ).appendTo( DOM().body ); } }; // if debug is on, display errors and throw exception if fatal if ( DEBUG ) { echo( msg ); if ( fatal ) { throw new Error(type + ': ' + msg); } // else just echo a silent generic error if fatal } else if ( fatal ) { if ( _hasError ) { return; } _hasError = true; fatal = false; echo( 'Gallery could not load.' ); } }; // Add the version Galleria.version = VERSION; /** A method for checking what version of Galleria the user has installed and throws a readable error if the user needs to upgrade. Useful when building plugins that requires a certain version to function. @param {number} version The minimum version required @param {string} [msg] Optional message to display. If not specified, Galleria will throw a generic error. @returns Galleria */ Galleria.requires = function( version, msg ) { msg = msg || 'You need to upgrade Galleria to version ' + version + ' to use one or more components.'; if ( Galleria.version < version ) { Galleria.raise(msg, true); } return Galleria; }; /** Adds preload, cache, scale and crop functionality @constructor @requires jQuery @param {number} [id] Optional id to keep track of instances */ Galleria.Picture = function( id ) { // save the id this.id = id || null; // the image should be null until loaded this.image = null; // Create a new container this.container = Utils.create('galleria-image'); // add container styles $( this.container ).css({ overflow: 'hidden', position: 'relative' // for IE Standards mode }); // saves the original measurements this.original = { width: 0, height: 0 }; // flag when the image is ready this.ready = false; // flag for iframe Picture this.isIframe = false; }; Galleria.Picture.prototype = { // the inherited cache object cache: {}, // show the image on stage show: function() { Utils.show( this.image ); }, // hide the image hide: function() { Utils.moveOut( this.image ); }, clear: function() { this.image = null; }, /** Checks if an image is in cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns {boolean} */ isCached: function( src ) { return !!this.cache[src]; }, /** Preloads an image into the cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns Galleria.Picture */ preload: function( src ) { $( new Image() ).load((function(src, cache) { return function() { cache[ src ] = src; }; }( src, this.cache ))).attr( 'src', src ); }, /** Loads an image and call the callback when ready. Will also add the image to cache. @param {string} src The image source path, ex '/path/to/img.jpg' @param {Object} [size] The forced size of the image, defined as an object { width: xx, height:xx } @param {Function} callback The function to be executed when the image is loaded & scaled @returns The image container (jQuery object) */ load: function(src, size, callback) { if ( typeof size == 'function' ) { callback = size; size = null; } if( this.isIframe ) { var id = 'if'+new Date().getTime(); this.image = $('<iframe>', { src: src, frameborder: 0, id: id, allowfullscreen: true, css: { visibility: 'hidden' } })[0]; $( this.container ).find( 'iframe,img' ).remove(); this.container.appendChild( this.image ); $('#'+id).load( (function( self, callback ) { return function() { window.setTimeout(function() { $( self.image ).css( 'visibility', 'visible' ); if( typeof callback == 'function' ) { callback.call( self, self ); } }, 10); }; }( this, callback ))); return this.container; } this.image = new Image(); var i = 0, reload = false, resort = false, // some jquery cache $container = $( this.container ), $image = $( this.image ), onerror = function() { if ( !reload ) { reload = true; // reload the image with a timestamp window.setTimeout((function(image, src) { return function() { image.attr('src', src + '?' + Utils.timestamp() ); }; }( $(this), src )), 50); } else { // apply the dummy image if it exists if ( DUMMY ) { $( this ).attr( 'src', DUMMY ); } else { Galleria.raise('Image not found: ' + src); } } }, // the onload method onload = (function( self, callback, src ) { return function() { var complete = function() { $( this ).unbind( 'load' ); // save the original size self.original = size || { height: this.height, width: this.width }; self.container.appendChild( this ); self.cache[ src ] = src; // will override old cache if (typeof callback == 'function' ) { window.setTimeout(function() { callback.call( self, self ); },1); } }; // Delay the callback to "fix" the Adblock Bug // http://code.google.com/p/adblockforchrome/issues/detail?id=3701 if ( ( !this.width || !this.height ) ) { window.setTimeout( (function( img ) { return function() { if ( img.width && img.height ) { complete.call( img ); } else { // last resort, this should never happen but just in case it does... if ( !resort ) { $(new Image()).load( onload ).attr( 'src', img.src ); resort = true; } else { Galleria.raise('Could not extract width/height from image: ' + img.src + '. Traced measures: width:' + img.width + 'px, height: ' + img.height + 'px.'); } } }; }( this )), 2); } else { complete.call( this ); } }; }( this, callback, src )); // remove any previous images $container.find( 'iframe,img' ).remove(); // append the image $image.css( 'display', 'block'); // hide it for now Utils.hide( this.image ); // remove any max/min scaling $.each('minWidth minHeight maxWidth maxHeight'.split(' '), function(i, prop) { $image.css(prop, (/min/.test(prop) ? '0' : 'none')); }); // begin load and insert in cache when done $image.load( onload ).error( onerror ).attr( 'src', src ); // return the container return this.container; }, /** Scales and crops the image @param {Object} options The method takes an object with a number of options: <ul> <li>width - width of the container</li> <li>height - height of the container</li> <li>min - minimum scale ratio</li> <li>max - maximum scale ratio</li> <li>margin - distance in pixels from the image border to the container</li> <li>complete - a callback that fires when scaling is complete</li> <li>position - positions the image, works like the css background-image property.</li> <li>crop - defines how to crop. Can be true, false, 'width' or 'height'</li> <li>canvas - set to true to try a canvas-based rescale</li> </ul> @returns The image container object (jQuery) */ scale: function( options ) { var self = this; // extend some defaults options = $.extend({ width: 0, height: 0, min: undef, max: undef, margin: 0, complete: F, position: 'center', crop: false, canvas: false }, options); if( this.isIframe ) { $( this.image ).width( options.width ).height( options.height ).removeAttr( 'width' ).removeAttr( 'height' ); $( this.container ).width( options.width ).height( options.height) ; options.complete.call(self, self); try { if( this.image.contentWindow ) { $( this.image.contentWindow ).trigger('resize'); } } catch(e) {} return this.container; } // return the element if no image found if (!this.image) { return this.container; } // store locale variables var width, height, $container = $( self.container ), data; // wait for the width/height Utils.wait({ until: function() { width = options.width || $container.width() || Utils.parseValue( $container.css('width') ); height = options.height || $container.height() || Utils.parseValue( $container.css('height') ); return width && height; }, success: function() { // calculate some cropping var newWidth = ( width - options.margin * 2 ) / self.original.width, newHeight = ( height - options.margin * 2 ) / self.original.height, min = Math.min( newWidth, newHeight ), max = Math.max( newWidth, newHeight ), cropMap = { 'true' : max, 'width' : newWidth, 'height': newHeight, 'false' : min, 'landscape': self.original.width > self.original.height ? max : min, 'portrait': self.original.width < self.original.height ? max : min }, ratio = cropMap[ options.crop.toString() ], canvasKey = ''; // allow maxScaleRatio if ( options.max ) { ratio = Math.min( options.max, ratio ); } // allow minScaleRatio if ( options.min ) { ratio = Math.max( options.min, ratio ); } $.each( ['width','height'], function( i, m ) { $( self.image )[ m ]( self[ m ] = self.image[ m ] = Math.round( self.original[ m ] * ratio ) ); }); $( self.container ).width( width ).height( height ); if ( options.canvas && _canvas ) { _canvas.elem.width = self.width; _canvas.elem.height = self.height; canvasKey = self.image.src + ':' + self.width + 'x' + self.height; self.image.src = _canvas.cache[ canvasKey ] || (function( key ) { _canvas.context.drawImage(self.image, 0, 0, self.original.width*ratio, self.original.height*ratio); try { data = _canvas.elem.toDataURL(); _canvas.length += data.length; _canvas.cache[ key ] = data; return data; } catch( e ) { return self.image.src; } }( canvasKey ) ); } // calculate image_position var pos = {}, mix = {}, getPosition = function(value, measure, margin) { var result = 0; if (/\%/.test(value)) { var flt = parseInt( value, 10 ) / 100, m = self.image[ measure ] || $( self.image )[ measure ](); result = Math.ceil( m * -1 * flt + margin * flt ); } else { result = Utils.parseValue( value ); } return result; }, positionMap = { 'top': { top: 0 }, 'left': { left: 0 }, 'right': { left: '100%' }, 'bottom': { top: '100%' } }; $.each( options.position.toLowerCase().split(' '), function( i, value ) { if ( value === 'center' ) { value = '50%'; } pos[i ? 'top' : 'left'] = value; }); $.each( pos, function( i, value ) { if ( positionMap.hasOwnProperty( value ) ) { $.extend( mix, positionMap[ value ] ); } }); pos = pos.top ? $.extend( pos, mix ) : mix; pos = $.extend({ top: '50%', left: '50%' }, pos); // apply position $( self.image ).css({ position : 'absolute', top : getPosition(pos.top, 'height', height), left : getPosition(pos.left, 'width', width) }); // show the image self.show(); // flag ready and call the callback self.ready = true; options.complete.call( self, self ); }, error: function() { Galleria.raise('Could not scale image: '+self.image.src); }, timeout: 1000 }); return this; } }; // our own easings $.extend( $.easing, { galleria: function (_, t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t*t + b; } return c/2*((t-=2)*t*t + 2) + b; }, galleriaIn: function (_, t, b, c, d) { return c*(t/=d)*t + b; }, galleriaOut: function (_, t, b, c, d) { return -c *(t/=d)*(t-2) + b; } }); // the plugin initializer $.fn.galleria = function( options ) { var selector = this.selector; // try domReady if element not found if ( !$(this).length ) { $(function() { if ( $( selector ).length ) { // if found on domReady, go ahead $( selector ).galleria( options ); } else { // if not, try fetching the element for 5 secs, then raise a warning. Galleria.utils.wait({ until: function() { return $( selector ).length; }, success: function() { $( selector ).galleria( options ); }, error: function() { Galleria.raise('Init failed: Galleria could not find the element "'+selector+'".'); }, timeout: 5000 }); } }); return this; } return this.each(function() { // fail silent if already run if ( !$.data(this, 'galleria') ) { $.data( this, 'galleria', new Galleria().init( this, options ) ); } }); }; // phew }( jQuery ) );
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["en-CA"] = $.extend(true, {}, en, { name: "en-CA", englishName: "English (Canada)", nativeName: "English (Canada)", numberFormat: { currency: { pattern: ["-$n","$n"] } }, calendars: { standard: $.extend(true, {}, standard, { patterns: { d: "dd/MM/yyyy", D: "MMMM-dd-yy", f: "MMMM-dd-yy h:mm tt", F: "MMMM-dd-yy h:mm:ss tt" } }) } }, cultures["en-CA"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
/*! * Globalize * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( window, undefined ) { var Globalize, // private variables regexHex, regexInfinity, regexParseFloat, regexTrim, // private JavaScript utility functions arrayIndexOf, endsWith, extend, isArray, isFunction, isObject, startsWith, trim, truncate, zeroPad, // private Globalization utility functions appendPreOrPostMatch, expandFormat, formatDate, formatNumber, getTokenRegExp, getEra, getEraYear, parseExact, parseNegativePattern; // Global variable (Globalize) or CommonJS module (globalize) Globalize = function( cultureSelector ) { return new Globalize.prototype.init( cultureSelector ); }; if ( typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined" ) { // Assume CommonJS module.exports = Globalize; } else { // Export as global variable window.Globalize = Globalize; } Globalize.cultures = {}; Globalize.prototype = { constructor: Globalize, init: function( cultureSelector ) { this.cultures = Globalize.cultures; this.cultureSelector = cultureSelector; return this; } }; Globalize.prototype.init.prototype = Globalize.prototype; // 1. When defining a culture, all fields are required except the ones stated as optional. // 2. Each culture should have a ".calendars" object with at least one calendar named "standard" // which serves as the default calendar in use by that culture. // 3. Each culture should have a ".calendar" object which is the current calendar being used, // it may be dynamically changed at any time to one of the calendars in ".calendars". Globalize.cultures[ "default" ] = { // A unique name for the culture in the form <language code>-<country/region code> name: "en", // the name of the culture in the english language englishName: "English", // the name of the culture in its own language nativeName: "English", // whether the culture uses right-to-left text isRTL: false, // "language" is used for so-called "specific" cultures. // For example, the culture "es-CL" means "Spanish, in Chili". // It represents the Spanish-speaking culture as it is in Chili, // which might have different formatting rules or even translations // than Spanish in Spain. A "neutral" culture is one that is not // specific to a region. For example, the culture "es" is the generic // Spanish culture, which may be a more generalized version of the language // that may or may not be what a specific culture expects. // For a specific culture like "es-CL", the "language" field refers to the // neutral, generic culture information for the language it is using. // This is not always a simple matter of the string before the dash. // For example, the "zh-Hans" culture is netural (Simplified Chinese). // And the "zh-SG" culture is Simplified Chinese in Singapore, whose lanugage // field is "zh-CHS", not "zh". // This field should be used to navigate from a specific culture to it's // more general, neutral culture. If a culture is already as general as it // can get, the language may refer to itself. language: "en", // numberFormat defines general number formatting rules, like the digits in // each grouping, the group separator, and how negative numbers are displayed. numberFormat: { // [negativePattern] // Note, numberFormat.pattern has no "positivePattern" unlike percent and currency, // but is still defined as an array for consistency with them. // negativePattern: one of "(n)|-n|- n|n-|n -" pattern: [ "-n" ], // number of decimal places normally shown decimals: 2, // string that separates number groups, as in 1,000,000 ",": ",", // string that separates a number from the fractional portion, as in 1.99 ".": ".", // array of numbers indicating the size of each number group. // TODO: more detailed description and example groupSizes: [ 3 ], // symbol used for positive numbers "+": "+", // symbol used for negative numbers "-": "-", // symbol used for NaN (Not-A-Number) "NaN": "NaN", // symbol used for Negative Infinity negativeInfinity: "-Infinity", // symbol used for Positive Infinity positiveInfinity: "Infinity", percent: { // [negativePattern, positivePattern] // negativePattern: one of "-n %|-n%|-%n|%-n|%n-|n-%|n%-|-% n|n %-|% n-|% -n|n- %" // positivePattern: one of "n %|n%|%n|% n" pattern: [ "-n %", "n %" ], // number of decimal places normally shown decimals: 2, // array of numbers indicating the size of each number group. // TODO: more detailed description and example groupSizes: [ 3 ], // string that separates number groups, as in 1,000,000 ",": ",", // string that separates a number from the fractional portion, as in 1.99 ".": ".", // symbol used to represent a percentage symbol: "%" }, currency: { // [negativePattern, positivePattern] // negativePattern: one of "($n)|-$n|$-n|$n-|(n$)|-n$|n-$|n$-|-n $|-$ n|n $-|$ n-|$ -n|n- $|($ n)|(n $)" // positivePattern: one of "$n|n$|$ n|n $" pattern: [ "($n)", "$n" ], // number of decimal places normally shown decimals: 2, // array of numbers indicating the size of each number group. // TODO: more detailed description and example groupSizes: [ 3 ], // string that separates number groups, as in 1,000,000 ",": ",", // string that separates a number from the fractional portion, as in 1.99 ".": ".", // symbol used to represent currency symbol: "$" } }, // calendars defines all the possible calendars used by this culture. // There should be at least one defined with name "standard", and is the default // calendar used by the culture. // A calendar contains information about how dates are formatted, information about // the calendar's eras, a standard set of the date formats, // translations for day and month names, and if the calendar is not based on the Gregorian // calendar, conversion functions to and from the Gregorian calendar. calendars: { standard: { // name that identifies the type of calendar this is name: "Gregorian_USEnglish", // separator of parts of a date (e.g. "/" in 11/05/1955) "/": "/", // separator of parts of a time (e.g. ":" in 05:44 PM) ":": ":", // the first day of the week (0 = Sunday, 1 = Monday, etc) firstDay: 0, days: { // full day names names: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], // abbreviated day names namesAbbr: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], // shortest day names namesShort: [ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" ] }, months: { // full month names (13 months for lunar calendards -- 13th month should be "" if not lunar) names: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "" ], // abbreviated month names namesAbbr: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "" ] }, // AM and PM designators in one of these forms: // The usual view, and the upper and lower case versions // [ standard, lowercase, uppercase ] // The culture does not use AM or PM (likely all standard date formats use 24 hour time) // null AM: [ "AM", "am", "AM" ], PM: [ "PM", "pm", "PM" ], eras: [ // eras in reverse chronological order. // name: the name of the era in this culture (e.g. A.D., C.E.) // start: when the era starts in ticks (gregorian, gmt), null if it is the earliest supported era. // offset: offset in years from gregorian calendar { "name": "A.D.", "start": null, "offset": 0 } ], // when a two digit year is given, it will never be parsed as a four digit // year greater than this year (in the appropriate era for the culture) // Set it as a full year (e.g. 2029) or use an offset format starting from // the current year: "+19" would correspond to 2029 if the current year 2010. twoDigitYearMax: 2029, // set of predefined date and time patterns used by the culture // these represent the format someone in this culture would expect // to see given the portions of the date that are shown. patterns: { // short date pattern d: "M/d/yyyy", // long date pattern D: "dddd, MMMM dd, yyyy", // short time pattern t: "h:mm tt", // long time pattern T: "h:mm:ss tt", // long date, short time pattern f: "dddd, MMMM dd, yyyy h:mm tt", // long date, long time pattern F: "dddd, MMMM dd, yyyy h:mm:ss tt", // month/day pattern M: "MMMM dd", // month/year pattern Y: "yyyy MMMM", // S is a sortable format that does not vary by culture S: "yyyy\u0027-\u0027MM\u0027-\u0027dd\u0027T\u0027HH\u0027:\u0027mm\u0027:\u0027ss" } // optional fields for each calendar: /* monthsGenitive: Same as months but used when the day preceeds the month. Omit if the culture has no genitive distinction in month names. For an explaination of genitive months, see http://blogs.msdn.com/michkap/archive/2004/12/25/332259.aspx convert: Allows for the support of non-gregorian based calendars. This convert object is used to to convert a date to and from a gregorian calendar date to handle parsing and formatting. The two functions: fromGregorian( date ) Given the date as a parameter, return an array with parts [ year, month, day ] corresponding to the non-gregorian based year, month, and day for the calendar. toGregorian( year, month, day ) Given the non-gregorian year, month, and day, return a new Date() object set to the corresponding date in the gregorian calendar. */ } }, // For localized strings messages: {} }; Globalize.cultures[ "default" ].calendar = Globalize.cultures[ "default" ].calendars.standard; Globalize.cultures.en = Globalize.cultures[ "default" ]; Globalize.cultureSelector = "en"; // // private variables // regexHex = /^0x[a-f0-9]+$/i; regexInfinity = /^[+\-]?infinity$/i; regexParseFloat = /^[+\-]?\d*\.?\d*(e[+\-]?\d+)?$/; regexTrim = /^\s+|\s+$/g; // // private JavaScript utility functions // arrayIndexOf = function( array, item ) { if ( array.indexOf ) { return array.indexOf( item ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[i] === item ) { return i; } } return -1; }; endsWith = function( value, pattern ) { return value.substr( value.length - pattern.length ) === pattern; }; 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" && !isFunction(target) ) { target = {}; } 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 && ( isObject(copy) || (copyIsArray = isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; isArray = Array.isArray || function( obj ) { return Object.prototype.toString.call( obj ) === "[object Array]"; }; isFunction = function( obj ) { return Object.prototype.toString.call( obj ) === "[object Function]"; }; isObject = function( obj ) { return Object.prototype.toString.call( obj ) === "[object Object]"; }; startsWith = function( value, pattern ) { return value.indexOf( pattern ) === 0; }; trim = function( value ) { return ( value + "" ).replace( regexTrim, "" ); }; truncate = function( value ) { if ( isNaN( value ) ) { return NaN; } return Math[ value < 0 ? "ceil" : "floor" ]( value ); }; zeroPad = function( str, count, left ) { var l; for ( l = str.length; l < count; l += 1 ) { str = ( left ? ("0" + str) : (str + "0") ); } return str; }; // // private Globalization utility functions // appendPreOrPostMatch = function( preMatch, strings ) { // appends pre- and post- token match strings while removing escaped characters. // Returns a single quote count which is used to determine if the token occurs // in a string literal. var quoteCount = 0, escaped = false; for ( var i = 0, il = preMatch.length; i < il; i++ ) { var c = preMatch.charAt( i ); switch ( c ) { case "\'": if ( escaped ) { strings.push( "\'" ); } else { quoteCount++; } escaped = false; break; case "\\": if ( escaped ) { strings.push( "\\" ); } escaped = !escaped; break; default: strings.push( c ); escaped = false; break; } } return quoteCount; }; expandFormat = function( cal, format ) { // expands unspecified or single character date formats into the full pattern. format = format || "F"; var pattern, patterns = cal.patterns, len = format.length; if ( len === 1 ) { pattern = patterns[ format ]; if ( !pattern ) { throw "Invalid date format string \'" + format + "\'."; } format = pattern; } else if ( len === 2 && format.charAt(0) === "%" ) { // %X escape format -- intended as a custom format string that is only one character, not a built-in format. format = format.charAt( 1 ); } return format; }; formatDate = function( value, format, culture ) { var cal = culture.calendar, convert = cal.convert, ret; if ( !format || !format.length || format === "i" ) { if ( culture && culture.name.length ) { if ( convert ) { // non-gregorian calendar, so we cannot use built-in toLocaleString() ret = formatDate( value, cal.patterns.F, culture ); } else { var eraDate = new Date( value.getTime() ), era = getEra( value, cal.eras ); eraDate.setFullYear( getEraYear(value, cal, era) ); ret = eraDate.toLocaleString(); } } else { ret = value.toString(); } return ret; } var eras = cal.eras, sortable = format === "s"; format = expandFormat( cal, format ); // Start with an empty string ret = []; var hour, zeros = [ "0", "00", "000" ], foundDay, checkedDay, dayPartRegExp = /([^d]|^)(d|dd)([^d]|$)/g, quoteCount = 0, tokenRegExp = getTokenRegExp(), converted; function padZeros( num, c ) { var r, s = num + ""; if ( c > 1 && s.length < c ) { r = ( zeros[c - 2] + s); return r.substr( r.length - c, c ); } else { r = s; } return r; } function hasDay() { if ( foundDay || checkedDay ) { return foundDay; } foundDay = dayPartRegExp.test( format ); checkedDay = true; return foundDay; } function getPart( date, part ) { if ( converted ) { return converted[ part ]; } switch ( part ) { case 0: return date.getFullYear(); case 1: return date.getMonth(); case 2: return date.getDate(); default: throw "Invalid part value " + part; } } if ( !sortable && convert ) { converted = convert.fromGregorian( value ); } for ( ; ; ) { // Save the current index var index = tokenRegExp.lastIndex, // Look for the next pattern ar = tokenRegExp.exec( format ); // Append the text before the pattern (or the end of the string if not found) var preMatch = format.slice( index, ar ? ar.index : format.length ); quoteCount += appendPreOrPostMatch( preMatch, ret ); if ( !ar ) { break; } // do not replace any matches that occur inside a string literal. if ( quoteCount % 2 ) { ret.push( ar[0] ); continue; } var current = ar[ 0 ], clength = current.length; switch ( current ) { case "ddd": //Day of the week, as a three-letter abbreviation case "dddd": // Day of the week, using the full name var names = ( clength === 3 ) ? cal.days.namesAbbr : cal.days.names; ret.push( names[value.getDay()] ); break; case "d": // Day of month, without leading zero for single-digit days case "dd": // Day of month, with leading zero for single-digit days foundDay = true; ret.push( padZeros( getPart(value, 2), clength ) ); break; case "MMM": // Month, as a three-letter abbreviation case "MMMM": // Month, using the full name var part = getPart( value, 1 ); ret.push( ( cal.monthsGenitive && hasDay() ) ? ( cal.monthsGenitive[ clength === 3 ? "namesAbbr" : "names" ][ part ] ) : ( cal.months[ clength === 3 ? "namesAbbr" : "names" ][ part ] ) ); break; case "M": // Month, as digits, with no leading zero for single-digit months case "MM": // Month, as digits, with leading zero for single-digit months ret.push( padZeros( getPart(value, 1) + 1, clength ) ); break; case "y": // Year, as two digits, but with no leading zero for years less than 10 case "yy": // Year, as two digits, with leading zero for years less than 10 case "yyyy": // Year represented by four full digits part = converted ? converted[ 0 ] : getEraYear( value, cal, getEra(value, eras), sortable ); if ( clength < 4 ) { part = part % 100; } ret.push( padZeros( part, clength ) ); break; case "h": // Hours with no leading zero for single-digit hours, using 12-hour clock case "hh": // Hours with leading zero for single-digit hours, using 12-hour clock hour = value.getHours() % 12; if ( hour === 0 ) hour = 12; ret.push( padZeros( hour, clength ) ); break; case "H": // Hours with no leading zero for single-digit hours, using 24-hour clock case "HH": // Hours with leading zero for single-digit hours, using 24-hour clock ret.push( padZeros( value.getHours(), clength ) ); break; case "m": // Minutes with no leading zero for single-digit minutes case "mm": // Minutes with leading zero for single-digit minutes ret.push( padZeros( value.getMinutes(), clength ) ); break; case "s": // Seconds with no leading zero for single-digit seconds case "ss": // Seconds with leading zero for single-digit seconds ret.push( padZeros( value.getSeconds(), clength ) ); break; case "t": // One character am/pm indicator ("a" or "p") case "tt": // Multicharacter am/pm indicator part = value.getHours() < 12 ? ( cal.AM ? cal.AM[0] : " " ) : ( cal.PM ? cal.PM[0] : " " ); ret.push( clength === 1 ? part.charAt(0) : part ); break; case "f": // Deciseconds case "ff": // Centiseconds case "fff": // Milliseconds ret.push( padZeros( value.getMilliseconds(), 3 ).substr( 0, clength ) ); break; case "z": // Time zone offset, no leading zero case "zz": // Time zone offset with leading zero hour = value.getTimezoneOffset() / 60; ret.push( ( hour <= 0 ? "+" : "-" ) + padZeros( Math.floor(Math.abs(hour)), clength ) ); break; case "zzz": // Time zone offset with leading zero hour = value.getTimezoneOffset() / 60; ret.push( ( hour <= 0 ? "+" : "-" ) + padZeros( Math.floor(Math.abs(hour)), 2 ) + // Hard coded ":" separator, rather than using cal.TimeSeparator // Repeated here for consistency, plus ":" was already assumed in date parsing. ":" + padZeros( Math.abs(value.getTimezoneOffset() % 60), 2 ) ); break; case "g": case "gg": if ( cal.eras ) { ret.push( cal.eras[ getEra(value, eras) ].name ); } break; case "/": ret.push( cal["/"] ); break; default: throw "Invalid date format pattern \'" + current + "\'."; } } return ret.join( "" ); }; // formatNumber (function() { var expandNumber; expandNumber = function( number, precision, formatInfo ) { var groupSizes = formatInfo.groupSizes, curSize = groupSizes[ 0 ], curGroupIndex = 1, factor = Math.pow( 10, precision ), rounded = Math.round( number * factor ) / factor; if ( !isFinite(rounded) ) { rounded = number; } number = rounded; var numberString = number+"", right = "", split = numberString.split( /e/i ), exponent = split.length > 1 ? parseInt( split[1], 10 ) : 0; numberString = split[ 0 ]; split = numberString.split( "." ); numberString = split[ 0 ]; right = split.length > 1 ? split[ 1 ] : ""; var l; if ( exponent > 0 ) { right = zeroPad( right, exponent, false ); numberString += right.slice( 0, exponent ); right = right.substr( exponent ); } else if ( exponent < 0 ) { exponent = -exponent; numberString = zeroPad( numberString, exponent + 1, true ); right = numberString.slice( -exponent, numberString.length ) + right; numberString = numberString.slice( 0, -exponent ); } if ( precision > 0 ) { right = formatInfo[ "." ] + ( (right.length > precision) ? right.slice(0, precision) : zeroPad(right, precision) ); } else { right = ""; } var stringIndex = numberString.length - 1, sep = formatInfo[ "," ], ret = ""; while ( stringIndex >= 0 ) { if ( curSize === 0 || curSize > stringIndex ) { return numberString.slice( 0, stringIndex + 1 ) + ( ret.length ? (sep + ret + right) : right ); } ret = numberString.slice( stringIndex - curSize + 1, stringIndex + 1 ) + ( ret.length ? (sep + ret) : "" ); stringIndex -= curSize; if ( curGroupIndex < groupSizes.length ) { curSize = groupSizes[ curGroupIndex ]; curGroupIndex++; } } return numberString.slice( 0, stringIndex + 1 ) + sep + ret + right; }; formatNumber = function( value, format, culture ) { if ( !isFinite(value) ) { if ( value === Infinity ) { return culture.numberFormat.positiveInfinity; } if ( value === -Infinity ) { return culture.numberFormat.negativeInfinity; } return culture.numberFormat.NaN; } if ( !format || format === "i" ) { return culture.name.length ? value.toLocaleString() : value.toString(); } format = format || "D"; var nf = culture.numberFormat, number = Math.abs( value ), precision = -1, pattern; if ( format.length > 1 ) precision = parseInt( format.slice(1), 10 ); var current = format.charAt( 0 ).toUpperCase(), formatInfo; switch ( current ) { case "D": pattern = "n"; number = truncate( number ); if ( precision !== -1 ) { number = zeroPad( "" + number, precision, true ); } if ( value < 0 ) number = "-" + number; break; case "N": formatInfo = nf; /* falls through */ case "C": formatInfo = formatInfo || nf.currency; /* falls through */ case "P": formatInfo = formatInfo || nf.percent; pattern = value < 0 ? formatInfo.pattern[ 0 ] : ( formatInfo.pattern[1] || "n" ); if ( precision === -1 ) precision = formatInfo.decimals; number = expandNumber( number * (current === "P" ? 100 : 1), precision, formatInfo ); break; default: throw "Bad number format specifier: " + current; } var patternParts = /n|\$|-|%/g, ret = ""; for ( ; ; ) { var index = patternParts.lastIndex, ar = patternParts.exec( pattern ); ret += pattern.slice( index, ar ? ar.index : pattern.length ); if ( !ar ) { break; } switch ( ar[0] ) { case "n": ret += number; break; case "$": ret += nf.currency.symbol; break; case "-": // don't make 0 negative if ( /[1-9]/.test(number) ) { ret += nf[ "-" ]; } break; case "%": ret += nf.percent.symbol; break; } } return ret; }; }()); getTokenRegExp = function() { // regular expression for matching date and time tokens in format strings. return (/\/|dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z|gg|g/g); }; getEra = function( date, eras ) { if ( !eras ) return 0; var start, ticks = date.getTime(); for ( var i = 0, l = eras.length; i < l; i++ ) { start = eras[ i ].start; if ( start === null || ticks >= start ) { return i; } } return 0; }; getEraYear = function( date, cal, era, sortable ) { var year = date.getFullYear(); if ( !sortable && cal.eras ) { // convert normal gregorian year to era-shifted gregorian // year by subtracting the era offset year -= cal.eras[ era ].offset; } return year; }; // parseExact (function() { var expandYear, getDayIndex, getMonthIndex, getParseRegExp, outOfRange, toUpper, toUpperArray; expandYear = function( cal, year ) { // expands 2-digit year into 4 digits. if ( year < 100 ) { var now = new Date(), era = getEra( now ), curr = getEraYear( now, cal, era ), twoDigitYearMax = cal.twoDigitYearMax; twoDigitYearMax = typeof twoDigitYearMax === "string" ? new Date().getFullYear() % 100 + parseInt( twoDigitYearMax, 10 ) : twoDigitYearMax; year += curr - ( curr % 100 ); if ( year > twoDigitYearMax ) { year -= 100; } } return year; }; getDayIndex = function ( cal, value, abbr ) { var ret, days = cal.days, upperDays = cal._upperDays; if ( !upperDays ) { cal._upperDays = upperDays = [ toUpperArray( days.names ), toUpperArray( days.namesAbbr ), toUpperArray( days.namesShort ) ]; } value = toUpper( value ); if ( abbr ) { ret = arrayIndexOf( upperDays[1], value ); if ( ret === -1 ) { ret = arrayIndexOf( upperDays[2], value ); } } else { ret = arrayIndexOf( upperDays[0], value ); } return ret; }; getMonthIndex = function( cal, value, abbr ) { var months = cal.months, monthsGen = cal.monthsGenitive || cal.months, upperMonths = cal._upperMonths, upperMonthsGen = cal._upperMonthsGen; if ( !upperMonths ) { cal._upperMonths = upperMonths = [ toUpperArray( months.names ), toUpperArray( months.namesAbbr ) ]; cal._upperMonthsGen = upperMonthsGen = [ toUpperArray( monthsGen.names ), toUpperArray( monthsGen.namesAbbr ) ]; } value = toUpper( value ); var i = arrayIndexOf( abbr ? upperMonths[1] : upperMonths[0], value ); if ( i < 0 ) { i = arrayIndexOf( abbr ? upperMonthsGen[1] : upperMonthsGen[0], value ); } return i; }; getParseRegExp = function( cal, format ) { // converts a format string into a regular expression with groups that // can be used to extract date fields from a date string. // check for a cached parse regex. var re = cal._parseRegExp; if ( !re ) { cal._parseRegExp = re = {}; } else { var reFormat = re[ format ]; if ( reFormat ) { return reFormat; } } // expand single digit formats, then escape regular expression characters. var expFormat = expandFormat( cal, format ).replace( /([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g, "\\\\$1" ), regexp = [ "^" ], groups = [], index = 0, quoteCount = 0, tokenRegExp = getTokenRegExp(), match; // iterate through each date token found. while ( (match = tokenRegExp.exec(expFormat)) !== null ) { var preMatch = expFormat.slice( index, match.index ); index = tokenRegExp.lastIndex; // don't replace any matches that occur inside a string literal. quoteCount += appendPreOrPostMatch( preMatch, regexp ); if ( quoteCount % 2 ) { regexp.push( match[0] ); continue; } // add a regex group for the token. var m = match[ 0 ], len = m.length, add; switch ( m ) { case "dddd": case "ddd": case "MMMM": case "MMM": case "gg": case "g": add = "(\\D+)"; break; case "tt": case "t": add = "(\\D*)"; break; case "yyyy": case "fff": case "ff": case "f": add = "(\\d{" + len + "})"; break; case "dd": case "d": case "MM": case "M": case "yy": case "y": case "HH": case "H": case "hh": case "h": case "mm": case "m": case "ss": case "s": add = "(\\d\\d?)"; break; case "zzz": add = "([+-]?\\d\\d?:\\d{2})"; break; case "zz": case "z": add = "([+-]?\\d\\d?)"; break; case "/": add = "(\\/)"; break; default: throw "Invalid date format pattern \'" + m + "\'."; } if ( add ) { regexp.push( add ); } groups.push( match[0] ); } appendPreOrPostMatch( expFormat.slice(index), regexp ); regexp.push( "$" ); // allow whitespace to differ when matching formats. var regexpStr = regexp.join( "" ).replace( /\s+/g, "\\s+" ), parseRegExp = { "regExp": regexpStr, "groups": groups }; // cache the regex for this format. return re[ format ] = parseRegExp; }; outOfRange = function( value, low, high ) { return value < low || value > high; }; toUpper = function( value ) { // "he-IL" has non-breaking space in weekday names. return value.split( "\u00A0" ).join( " " ).toUpperCase(); }; toUpperArray = function( arr ) { var results = []; for ( var i = 0, l = arr.length; i < l; i++ ) { results[ i ] = toUpper( arr[i] ); } return results; }; parseExact = function( value, format, culture ) { // try to parse the date string by matching against the format string // while using the specified culture for date field names. value = trim( value ); var cal = culture.calendar, // convert date formats into regular expressions with groupings. // use the regexp to determine the input format and extract the date fields. parseInfo = getParseRegExp( cal, format ), match = new RegExp( parseInfo.regExp ).exec( value ); if ( match === null ) { return null; } // found a date format that matches the input. var groups = parseInfo.groups, era = null, year = null, month = null, date = null, weekDay = null, hour = 0, hourOffset, min = 0, sec = 0, msec = 0, tzMinOffset = null, pmHour = false; // iterate the format groups to extract and set the date fields. for ( var j = 0, jl = groups.length; j < jl; j++ ) { var matchGroup = match[ j + 1 ]; if ( matchGroup ) { var current = groups[ j ], clength = current.length, matchInt = parseInt( matchGroup, 10 ); switch ( current ) { case "dd": case "d": // Day of month. date = matchInt; // check that date is generally in valid range, also checking overflow below. if ( outOfRange(date, 1, 31) ) return null; break; case "MMM": case "MMMM": month = getMonthIndex( cal, matchGroup, clength === 3 ); if ( outOfRange(month, 0, 11) ) return null; break; case "M": case "MM": // Month. month = matchInt - 1; if ( outOfRange(month, 0, 11) ) return null; break; case "y": case "yy": case "yyyy": year = clength < 4 ? expandYear( cal, matchInt ) : matchInt; if ( outOfRange(year, 0, 9999) ) return null; break; case "h": case "hh": // Hours (12-hour clock). hour = matchInt; if ( hour === 12 ) hour = 0; if ( outOfRange(hour, 0, 11) ) return null; break; case "H": case "HH": // Hours (24-hour clock). hour = matchInt; if ( outOfRange(hour, 0, 23) ) return null; break; case "m": case "mm": // Minutes. min = matchInt; if ( outOfRange(min, 0, 59) ) return null; break; case "s": case "ss": // Seconds. sec = matchInt; if ( outOfRange(sec, 0, 59) ) return null; break; case "tt": case "t": // AM/PM designator. // see if it is standard, upper, or lower case PM. If not, ensure it is at least one of // the AM tokens. If not, fail the parse for this format. pmHour = cal.PM && ( matchGroup === cal.PM[0] || matchGroup === cal.PM[1] || matchGroup === cal.PM[2] ); if ( !pmHour && ( !cal.AM || ( matchGroup !== cal.AM[0] && matchGroup !== cal.AM[1] && matchGroup !== cal.AM[2] ) ) ) return null; break; case "f": // Deciseconds. case "ff": // Centiseconds. case "fff": // Milliseconds. msec = matchInt * Math.pow( 10, 3 - clength ); if ( outOfRange(msec, 0, 999) ) return null; break; case "ddd": // Day of week. case "dddd": // Day of week. weekDay = getDayIndex( cal, matchGroup, clength === 3 ); if ( outOfRange(weekDay, 0, 6) ) return null; break; case "zzz": // Time zone offset in +/- hours:min. var offsets = matchGroup.split( /:/ ); if ( offsets.length !== 2 ) return null; hourOffset = parseInt( offsets[0], 10 ); if ( outOfRange(hourOffset, -12, 13) ) return null; var minOffset = parseInt( offsets[1], 10 ); if ( outOfRange(minOffset, 0, 59) ) return null; tzMinOffset = ( hourOffset * 60 ) + ( startsWith(matchGroup, "-") ? -minOffset : minOffset ); break; case "z": case "zz": // Time zone offset in +/- hours. hourOffset = matchInt; if ( outOfRange(hourOffset, -12, 13) ) return null; tzMinOffset = hourOffset * 60; break; case "g": case "gg": var eraName = matchGroup; if ( !eraName || !cal.eras ) return null; eraName = trim( eraName.toLowerCase() ); for ( var i = 0, l = cal.eras.length; i < l; i++ ) { if ( eraName === cal.eras[i].name.toLowerCase() ) { era = i; break; } } // could not find an era with that name if ( era === null ) return null; break; } } } var result = new Date(), defaultYear, convert = cal.convert; defaultYear = convert ? convert.fromGregorian( result )[ 0 ] : result.getFullYear(); if ( year === null ) { year = defaultYear; } else if ( cal.eras ) { // year must be shifted to normal gregorian year // but not if year was not specified, its already normal gregorian // per the main if clause above. year += cal.eras[( era || 0 )].offset; } // set default day and month to 1 and January, so if unspecified, these are the defaults // instead of the current day/month. if ( month === null ) { month = 0; } if ( date === null ) { date = 1; } // now have year, month, and date, but in the culture's calendar. // convert to gregorian if necessary if ( convert ) { result = convert.toGregorian( year, month, date ); // conversion failed, must be an invalid match if ( result === null ) return null; } else { // have to set year, month and date together to avoid overflow based on current date. result.setFullYear( year, month, date ); // check to see if date overflowed for specified month (only checked 1-31 above). if ( result.getDate() !== date ) return null; // invalid day of week. if ( weekDay !== null && result.getDay() !== weekDay ) { return null; } } // if pm designator token was found make sure the hours fit the 24-hour clock. if ( pmHour && hour < 12 ) { hour += 12; } result.setHours( hour, min, sec, msec ); if ( tzMinOffset !== null ) { // adjust timezone to utc before applying local offset. var adjustedMin = result.getMinutes() - ( tzMinOffset + result.getTimezoneOffset() ); // Safari limits hours and minutes to the range of -127 to 127. We need to use setHours // to ensure both these fields will not exceed this range. adjustedMin will range // somewhere between -1440 and 1500, so we only need to split this into hours. result.setHours( result.getHours() + parseInt(adjustedMin / 60, 10), adjustedMin % 60 ); } return result; }; }()); parseNegativePattern = function( value, nf, negativePattern ) { var neg = nf[ "-" ], pos = nf[ "+" ], ret; switch ( negativePattern ) { case "n -": neg = " " + neg; pos = " " + pos; /* falls through */ case "n-": if ( endsWith(value, neg) ) { ret = [ "-", value.substr(0, value.length - neg.length) ]; } else if ( endsWith(value, pos) ) { ret = [ "+", value.substr(0, value.length - pos.length) ]; } break; case "- n": neg += " "; pos += " "; /* falls through */ case "-n": if ( startsWith(value, neg) ) { ret = [ "-", value.substr(neg.length) ]; } else if ( startsWith(value, pos) ) { ret = [ "+", value.substr(pos.length) ]; } break; case "(n)": if ( startsWith(value, "(") && endsWith(value, ")") ) { ret = [ "-", value.substr(1, value.length - 2) ]; } break; } return ret || [ "", value ]; }; // // public instance functions // Globalize.prototype.findClosestCulture = function( cultureSelector ) { return Globalize.findClosestCulture.call( this, cultureSelector ); }; Globalize.prototype.format = function( value, format, cultureSelector ) { return Globalize.format.call( this, value, format, cultureSelector ); }; Globalize.prototype.localize = function( key, cultureSelector ) { return Globalize.localize.call( this, key, cultureSelector ); }; Globalize.prototype.parseInt = function( value, radix, cultureSelector ) { return Globalize.parseInt.call( this, value, radix, cultureSelector ); }; Globalize.prototype.parseFloat = function( value, radix, cultureSelector ) { return Globalize.parseFloat.call( this, value, radix, cultureSelector ); }; Globalize.prototype.culture = function( cultureSelector ) { return Globalize.culture.call( this, cultureSelector ); }; // // public singleton functions // Globalize.addCultureInfo = function( cultureName, baseCultureName, info ) { var base = {}, isNew = false; if ( typeof cultureName !== "string" ) { // cultureName argument is optional string. If not specified, assume info is first // and only argument. Specified info deep-extends current culture. info = cultureName; cultureName = this.culture().name; base = this.cultures[ cultureName ]; } else if ( typeof baseCultureName !== "string" ) { // baseCultureName argument is optional string. If not specified, assume info is second // argument. Specified info deep-extends specified culture. // If specified culture does not exist, create by deep-extending default info = baseCultureName; isNew = ( this.cultures[ cultureName ] == null ); base = this.cultures[ cultureName ] || this.cultures[ "default" ]; } else { // cultureName and baseCultureName specified. Assume a new culture is being created // by deep-extending an specified base culture isNew = true; base = this.cultures[ baseCultureName ]; } this.cultures[ cultureName ] = extend(true, {}, base, info ); // Make the standard calendar the current culture if it's a new culture if ( isNew ) { this.cultures[ cultureName ].calendar = this.cultures[ cultureName ].calendars.standard; } }; Globalize.findClosestCulture = function( name ) { var match; if ( !name ) { return this.findClosestCulture( this.cultureSelector ) || this.cultures[ "default" ]; } if ( typeof name === "string" ) { name = name.split( "," ); } if ( isArray(name) ) { var lang, cultures = this.cultures, list = name, i, l = list.length, prioritized = []; for ( i = 0; i < l; i++ ) { name = trim( list[i] ); var pri, parts = name.split( ";" ); lang = trim( parts[0] ); if ( parts.length === 1 ) { pri = 1; } else { name = trim( parts[1] ); if ( name.indexOf("q=") === 0 ) { name = name.substr( 2 ); pri = parseFloat( name ); pri = isNaN( pri ) ? 0 : pri; } else { pri = 1; } } prioritized.push({ lang: lang, pri: pri }); } prioritized.sort(function( a, b ) { if ( a.pri < b.pri ) { return 1; } else if ( a.pri > b.pri ) { return -1; } return 0; }); // exact match for ( i = 0; i < l; i++ ) { lang = prioritized[ i ].lang; match = cultures[ lang ]; if ( match ) { return match; } } // neutral language match for ( i = 0; i < l; i++ ) { lang = prioritized[ i ].lang; do { var index = lang.lastIndexOf( "-" ); if ( index === -1 ) { break; } // strip off the last part. e.g. en-US => en lang = lang.substr( 0, index ); match = cultures[ lang ]; if ( match ) { return match; } } while ( 1 ); } // last resort: match first culture using that language for ( i = 0; i < l; i++ ) { lang = prioritized[ i ].lang; for ( var cultureKey in cultures ) { var culture = cultures[ cultureKey ]; if ( culture.language == lang ) { return culture; } } } } else if ( typeof name === "object" ) { return name; } return match || null; }; Globalize.format = function( value, format, cultureSelector ) { var culture = this.findClosestCulture( cultureSelector ); if ( value instanceof Date ) { value = formatDate( value, format, culture ); } else if ( typeof value === "number" ) { value = formatNumber( value, format, culture ); } return value; }; Globalize.localize = function( key, cultureSelector ) { return this.findClosestCulture( cultureSelector ).messages[ key ] || this.cultures[ "default" ].messages[ key ]; }; Globalize.parseDate = function( value, formats, culture ) { culture = this.findClosestCulture( culture ); var date, prop, patterns; if ( formats ) { if ( typeof formats === "string" ) { formats = [ formats ]; } if ( formats.length ) { for ( var i = 0, l = formats.length; i < l; i++ ) { var format = formats[ i ]; if ( format ) { date = parseExact( value, format, culture ); if ( date ) { break; } } } } } else { patterns = culture.calendar.patterns; for ( prop in patterns ) { date = parseExact( value, patterns[prop], culture ); if ( date ) { break; } } } return date || null; }; Globalize.parseInt = function( value, radix, cultureSelector ) { return truncate( Globalize.parseFloat(value, radix, cultureSelector) ); }; Globalize.parseFloat = function( value, radix, cultureSelector ) { // radix argument is optional if ( typeof radix !== "number" ) { cultureSelector = radix; radix = 10; } var culture = this.findClosestCulture( cultureSelector ); var ret = NaN, nf = culture.numberFormat; if ( value.indexOf(culture.numberFormat.currency.symbol) > -1 ) { // remove currency symbol value = value.replace( culture.numberFormat.currency.symbol, "" ); // replace decimal seperator value = value.replace( culture.numberFormat.currency["."], culture.numberFormat["."] ); } //Remove percentage character from number string before parsing if ( value.indexOf(culture.numberFormat.percent.symbol) > -1){ value = value.replace( culture.numberFormat.percent.symbol, "" ); } // remove spaces: leading, trailing and between - and number. Used for negative currency pt-BR value = value.replace( / /g, "" ); // allow infinity or hexidecimal if ( regexInfinity.test(value) ) { ret = parseFloat( value ); } else if ( !radix && regexHex.test(value) ) { ret = parseInt( value, 16 ); } else { // determine sign and number var signInfo = parseNegativePattern( value, nf, nf.pattern[0] ), sign = signInfo[ 0 ], num = signInfo[ 1 ]; // #44 - try parsing as "(n)" if ( sign === "" && nf.pattern[0] !== "(n)" ) { signInfo = parseNegativePattern( value, nf, "(n)" ); sign = signInfo[ 0 ]; num = signInfo[ 1 ]; } // try parsing as "-n" if ( sign === "" && nf.pattern[0] !== "-n" ) { signInfo = parseNegativePattern( value, nf, "-n" ); sign = signInfo[ 0 ]; num = signInfo[ 1 ]; } sign = sign || "+"; // determine exponent and number var exponent, intAndFraction, exponentPos = num.indexOf( "e" ); if ( exponentPos < 0 ) exponentPos = num.indexOf( "E" ); if ( exponentPos < 0 ) { intAndFraction = num; exponent = null; } else { intAndFraction = num.substr( 0, exponentPos ); exponent = num.substr( exponentPos + 1 ); } // determine decimal position var integer, fraction, decSep = nf[ "." ], decimalPos = intAndFraction.indexOf( decSep ); if ( decimalPos < 0 ) { integer = intAndFraction; fraction = null; } else { integer = intAndFraction.substr( 0, decimalPos ); fraction = intAndFraction.substr( decimalPos + decSep.length ); } // handle groups (e.g. 1,000,000) var groupSep = nf[ "," ]; integer = integer.split( groupSep ).join( "" ); var altGroupSep = groupSep.replace( /\u00A0/g, " " ); if ( groupSep !== altGroupSep ) { integer = integer.split( altGroupSep ).join( "" ); } // build a natively parsable number string var p = sign + integer; if ( fraction !== null ) { p += "." + fraction; } if ( exponent !== null ) { // exponent itself may have a number patternd var expSignInfo = parseNegativePattern( exponent, nf, "-n" ); p += "e" + ( expSignInfo[0] || "+" ) + expSignInfo[ 1 ]; } if ( regexParseFloat.test(p) ) { ret = parseFloat( p ); } } return ret; }; Globalize.culture = function( cultureSelector ) { // setter if ( typeof cultureSelector !== "undefined" ) { this.cultureSelector = cultureSelector; } // getter return this.findClosestCulture( cultureSelector ) || this.cultures[ "default" ]; }; }( this ));
JavaScript