code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
!function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery"],e):"undefined"!=typeof module&&module.exports?module.exports=e(require("jquery")):e(jQuery)}(function(e){"use strict";function t(t){return!t.nodeName||-1!==e.inArray(t.nodeName.toLowerCase(),["iframe","#document","html","body"])}function o(t){return e.isFunction(t)||e.isPlainObject(t)?t:{top:t,left:t}}var n=e.scrollTo=function(t,o,n){return e(window).scrollTo(t,o,n)};return n.defaults={axis:"xy",duration:0,limit:!0},e.fn.scrollTo=function(r,i,s){"object"==typeof i&&(s=i,i=0),"function"==typeof s&&(s={onAfter:s}),"max"===r&&(r=9e9),s=e.extend({},n.defaults,s),i=i||s.duration;var a=s.queue&&s.axis.length>1;return a&&(i/=2),s.offset=o(s.offset),s.over=o(s.over),this.each(function(){function f(t){var o=e.extend({},s,{queue:!0,duration:i,complete:t&&function(){t.call(l,m,s)}});d.animate(p,o)}if(null!==r){var u,c=t(this),l=c?this.contentWindow||window:this,d=e(l),m=r,p={};switch(typeof m){case"number":case"string":if(/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(m)){m=o(m);break}m=c?e(m):e(m,l);case"object":if(0===m.length)return;(m.is||m.style)&&(u=(m=e(m)).offset())}var h=e.isFunction(s.offset)&&s.offset(l,m)||s.offset;e.each(s.axis.split(""),function(e,t){var o="x"===t?"Left":"Top",r=o.toLowerCase(),i="scroll"+o,x=d[i](),v=n.max(l,t);if(u)p[i]=u[r]+(c?0:x-d.offset()[r]),s.margin&&(p[i]-=parseInt(m.css("margin"+o),10)||0,p[i]-=parseInt(m.css("border"+o+"Width"),10)||0),p[i]+=h[r]||0,s.over[r]&&(p[i]+=m["x"===t?"width":"height"]()*s.over[r]);else{var w=m[r];p[i]=w.slice&&"%"===w.slice(-1)?parseFloat(w)/100*v:w}s.limit&&/^\d+$/.test(p[i])&&(p[i]=p[i]<=0?0:Math.min(p[i],v)),!e&&s.axis.length>1&&(x===p[i]?p={}:a&&(f(s.onAfterFirst),p={}))}),f(s.onAfter)}})},n.max=function(o,n){var r="x"===n?"Width":"Height",i="scroll"+r;if(!t(o))return o[i]-e(o)[r.toLowerCase()]();var s="client"+r,a=o.ownerDocument||o.document,f=a.documentElement,u=a.body;return Math.max(f[i],u[i])-Math.min(f[s],u[s])},e.Tween.propHooks.scrollLeft=e.Tween.propHooks.scrollTop={get:function(t){return e(t.elem)[t.prop]()},set:function(t){var o=this.get(t);if(t.options.interrupt&&t._last&&t._last!==o)return e(t.elem).stop();var n=Math.round(t.now);o!==n&&(e(t.elem)[t.prop](n),t._last=this.get(t))}},n});
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-scrollto-2.1.2.min.js
jquery-scrollto-2.1.2.min.js
!function(e,c,a,g){var d="ontouchstart" in a.documentElement,b="touchstart mousedown",f="touchmove mousemove",h="touchend mouseup";d&&e.each("touchstart touchmove touchend".split(" "),function(k,j){e.event.fixHooks[j]=e.event.mouseHooks});e(a).ready(function(){function i(k){var j={},l=k.match(/([^;:]+)/g)||[];while(l.length){j[l.shift()]=l.shift().trim()}return j}e("table").each(function(){if(e(this).data("table")=="dnd"){e(this).tableDnD({onDragStyle:e(this).data("ondragstyle")&&i(e(this).data("ondragstyle"))||null,onDropStyle:e(this).data("ondropstyle")&&i(e(this).data("ondropstyle"))||null,onDragClass:e(this).data("ondragclass")==g&&"tDnD_whileDrag"||e(this).data("ondragclass"),onDrop:e(this).data("ondrop")&&new Function("table","row",e(this).data("ondrop")),onDragStart:e(this).data("ondragstart")&&new Function("table","row",e(this).data("ondragstart")),scrollAmount:e(this).data("scrollamount")||5,sensitivity:e(this).data("sensitivity")||10,hierarchyLevel:e(this).data("hierarchylevel")||0,indentArtifact:e(this).data("indentartifact")||'<div class="indent">&nbsp;</div>',autoWidthAdjust:e(this).data("autowidthadjust")||true,autoCleanRelations:e(this).data("autocleanrelations")||true,jsonPretifySeparator:e(this).data("jsonpretifyseparator")||"\t",serializeRegexp:e(this).data("serializeregexp")&&new RegExp(e(this).data("serializeregexp"))||/[^\-]*$/,serializeParamName:e(this).data("serializeparamname")||false,dragHandle:e(this).data("draghandle")||null})}})});jQuery.tableDnD={currentTable:null,dragObject:null,mouseOffset:null,oldX:0,oldY:0,build:function(i){this.each(function(){this.tableDnDConfig=e.extend({onDragStyle:null,onDropStyle:null,onDragClass:"tDnD_whileDrag",onDrop:null,onDragStart:null,scrollAmount:5,sensitivity:10,hierarchyLevel:0,indentArtifact:'<div class="indent">&nbsp;</div>',autoWidthAdjust:true,autoCleanRelations:true,jsonPretifySeparator:"\t",serializeRegexp:/[^\-]*$/,serializeParamName:false,dragHandle:null},i||{});e.tableDnD.makeDraggable(this);this.tableDnDConfig.hierarchyLevel&&e.tableDnD.makeIndented(this)});return this},makeIndented:function(p){var i=p.tableDnDConfig,q=p.rows,m=e(q).first().find("td:first")[0],o=0,j=0,l,k;if(e(p).hasClass("indtd")){return null}k=e(p).addClass("indtd").attr("style");e(p).css({whiteSpace:"nowrap"});for(var n=0;n<q.length;n++){if(j<e(q[n]).find("td:first").text().length){j=e(q[n]).find("td:first").text().length;l=n}}e(m).css({width:"auto"});for(n=0;n<i.hierarchyLevel;n++){e(q[l]).find("td:first").prepend(i.indentArtifact)}m&&e(m).css({width:m.offsetWidth});k&&e(p).css(k);for(n=0;n<i.hierarchyLevel;n++){e(q[l]).find("td:first").children(":first").remove()}i.hierarchyLevel&&e(q).each(function(){o=e(this).data("level")||0;o<=i.hierarchyLevel&&e(this).data("level",o)||e(this).data("level",0);for(var r=0;r<e(this).data("level");r++){e(this).find("td:first").prepend(i.indentArtifact)}});return this},makeDraggable:function(j){var i=j.tableDnDConfig;i.dragHandle&&e(i.dragHandle,j).each(function(){e(this).bind(b,function(k){e.tableDnD.initialiseDrag(e(this).parents("tr")[0],j,this,k,i);return false})})||e(j.rows).each(function(){if(!e(this).hasClass("nodrag")){e(this).bind(b,function(k){if(k.target.tagName=="TD"){e.tableDnD.initialiseDrag(this,j,this,k,i);return false}}).css("cursor","move")}})},currentOrder:function(){var i=this.currentTable.rows;return e.map(i,function(j){return(e(j).data("level")+j.id).replace(/\s/g,"")}).join("")},initialiseDrag:function(k,j,m,l,i){this.dragObject=k;this.currentTable=j;this.mouseOffset=this.getMouseOffset(m,l);this.originalOrder=this.currentOrder();e(a).bind(f,this.mousemove).bind(h,this.mouseup);i.onDragStart&&i.onDragStart(j,m)},updateTables:function(){this.each(function(){if(this.tableDnDConfig){e.tableDnD.makeDraggable(this)}})},mouseCoords:function(i){i=i||c.event;if(i.changedTouches){return{x:i.changedTouches[0].clientX,y:i.changedTouches[0].clientY}}if(i.pageX||i.pageY){return{x:i.pageX,y:i.pageY}}return{x:i.clientX+a.body.scrollLeft-a.body.clientLeft,y:i.clientY+a.body.scrollTop-a.body.clientTop}},getMouseOffset:function(l,k){var i,j;k=k||c.event;j=this.getPosition(l);i=this.mouseCoords(k);return{x:i.x-j.x,y:i.y-j.y}},getPosition:function(i){var k=0,j=0;if(i.offsetHeight==0){i=i.firstChild}while(i.offsetParent){k+=i.offsetLeft;j+=i.offsetTop;i=i.offsetParent}k+=i.offsetLeft;j+=i.offsetTop;return{x:k,y:j}},autoScroll:function(i){var j=this.currentTable.tableDnDConfig,k=c.pageYOffset,l=c.innerHeight?c.innerHeight:a.documentElement.clientHeight?a.documentElement.clientHeight:a.body.clientHeight;if(a.all){if(typeof a.compatMode!="undefined"&&a.compatMode!="BackCompat"){k=a.documentElement.scrollTop}else{if(typeof a.body!="undefined"){k=a.body.scrollTop}}}i.y-k<j.scrollAmount&&c.scrollBy(0,-j.scrollAmount)||l-(i.y-k)<j.scrollAmount&&c.scrollBy(0,j.scrollAmount)},moveVerticle:function(i,j){if(0!=i.vertical&&j&&this.dragObject!=j&&this.dragObject.parentNode==j.parentNode){0>i.vertical&&this.dragObject.parentNode.insertBefore(this.dragObject,j.nextSibling)||0<i.vertical&&this.dragObject.parentNode.insertBefore(this.dragObject,j)}},moveHorizontal:function(i,k){var j=this.currentTable.tableDnDConfig,l;if(!j.hierarchyLevel||0==i.horizontal||!k||this.dragObject!=k){return null}l=e(k).data("level");0<i.horizontal&&l>0&&e(k).find("td:first").children(":first").remove()&&e(k).data("level",--l);0>i.horizontal&&l<j.hierarchyLevel&&e(k).prev().data("level")>=l&&e(k).children(":first").prepend(j.indentArtifact)&&e(k).data("level",++l)},mousemove:function(o){var n=e(e.tableDnD.dragObject),m=e.tableDnD.currentTable.tableDnDConfig,l,k,j,i,p;o&&o.preventDefault();if(!e.tableDnD.dragObject){return false}o.type=="touchmove"&&event.preventDefault();m.onDragClass&&n.addClass(m.onDragClass)||n.css(m.onDragStyle);k=e.tableDnD.mouseCoords(o);i=k.x-e.tableDnD.mouseOffset.x;p=k.y-e.tableDnD.mouseOffset.y;e.tableDnD.autoScroll(k);l=e.tableDnD.findDropTargetRow(n,p);j=e.tableDnD.findDragDirection(i,p);e.tableDnD.moveVerticle(j,l);e.tableDnD.moveHorizontal(j,l);return false},findDragDirection:function(o,n){var l=this.currentTable.tableDnDConfig.sensitivity,r=this.oldX,p=this.oldY,j=r-l,m=r+l,q=p-l,k=p+l,i={horizontal:o>=j&&o<=m?0:o>r?-1:1,vertical:n>=q&&n<=k?0:n>p?-1:1};if(i.horizontal!=0){this.oldX=o}if(i.vertical!=0){this.oldY=n}return i},findDropTargetRow:function(n,q){var m=0,o=this.currentTable.rows,k=this.currentTable.tableDnDConfig,j=0,p=null;for(var l=0;l<o.length;l++){p=o[l];j=this.getPosition(p).y;m=parseInt(p.offsetHeight)/2;if(p.offsetHeight==0){j=this.getPosition(p.firstChild).y;m=parseInt(p.firstChild.offsetHeight)/2}if(q>(j-m)&&q<(j+m)){if(n.is(p)||(k.onAllowDrop&&!k.onAllowDrop(n,p))||e(p).hasClass("nodrop")){return null}else{return p}}}return null},processMouseup:function(){if(!this.currentTable||!this.dragObject){return null}var i=this.currentTable.tableDnDConfig,j=this.dragObject,l=0,k=0;e(a).unbind(f,this.mousemove).unbind(h,this.mouseup);i.hierarchyLevel&&i.autoCleanRelations&&e(this.currentTable.rows).first().find("td:first").children().each(function(){k=e(this).parents("tr:first").data("level");k&&e(this).parents("tr:first").data("level",--k)&&e(this).remove()})&&i.hierarchyLevel>1&&e(this.currentTable.rows).each(function(){k=e(this).data("level");if(k>1){l=e(this).prev().data("level");while(k>l+1){e(this).find("td:first").children(":first").remove();e(this).data("level",--k)}}});i.onDragClass&&e(j).removeClass(i.onDragClass)||e(j).css(i.onDropStyle);this.dragObject=null;i.onDrop&&this.originalOrder!=this.currentOrder()&&e(j).hide().fadeIn("fast")&&i.onDrop(this.currentTable,j);this.currentTable=null},mouseup:function(i){i&&i.preventDefault();e.tableDnD.processMouseup();return false},jsonize:function(i){var j=this.currentTable;if(i){return JSON.stringify(this.tableData(j),null,j.tableDnDConfig.jsonPretifySeparator)}return JSON.stringify(this.tableData(j))},serialize:function(){return e.param(this.tableData(this.currentTable))},serializeTable:function(l){var j="";var o=l.tableDnDConfig.serializeParamName||l.id;var m=l.rows;for(var k=0;k<m.length;k++){if(j.length>0){j+="&"}var n=m[k].id;if(n&&l.tableDnDConfig&&l.tableDnDConfig.serializeRegexp){n=n.match(l.tableDnDConfig.serializeRegexp)[0];j+=o+"[]="+n}}return j},serializeTables:function(){var i=[];e("table").each(function(){this.id&&i.push(e.param(this.tableData(this)))});return i.join("&")},tableData:function(u){var n=u.tableDnDConfig,k=[],l=0,t=0,s=null,p={},m,r,j,v;if(!u){u=this.currentTable}if(!u||!u.id||!u.rows||!u.rows.length){return{error:{code:500,message:"Not a valid table, no serializable unique id provided."}}}v=n.autoCleanRelations&&u.rows||e.makeArray(u.rows);r=n.serializeParamName||u.id;j=r;m=function(i){if(i&&n&&n.serializeRegexp){return i.match(n.serializeRegexp)[0]}return i};p[j]=[];!n.autoCleanRelations&&e(v[0]).data("level")&&v.unshift({id:"undefined"});for(var o=0;o<v.length;o++){if(n.hierarchyLevel){t=e(v[o]).data("level")||0;if(t==0){j=r;k=[]}else{if(t>l){k.push([j,l]);j=m(v[o-1].id)}else{if(t<l){for(var q=0;q<k.length;q++){if(k[q][1]==t){j=k[q][0]}if(k[q][1]>=l){k[q][1]=0}}}}}l=t;if(!e.isArray(p[j])){p[j]=[]}s=m(v[o].id);s&&p[j].push(s)}else{s=m(v[o].id);s&&p[j].push(s)}}return p}};jQuery.fn.extend({tableDnD:e.tableDnD.build,tableDnDUpdate:e.tableDnD.updateTables,tableDnDSerialize:e.proxy(e.tableDnD.serialize,e.tableDnD),tableDnDSerializeAll:e.tableDnD.serializeTables,tableDnDData:e.proxy(e.tableDnD.tableData,e.tableDnD)})}(jQuery,window,window.document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-tablednd.min.js
jquery-tablednd.min.js
Copyright 2010-2013 Manos Malihutsakis This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/lgpl.html. */ (function ($) { /*plugin script*/ var methods = { init: function (options) { var defaults = { set_width: false, /*optional element width: boolean, pixels, percentage*/ set_height: false, /*optional element height: boolean, pixels, percentage*/ horizontalScroll: false, /*scroll horizontally: boolean*/ scrollInertia: 950, /*scrolling inertia: integer (milliseconds)*/ mouseWheel: true, /*mousewheel support: boolean*/ mouseWheelPixels: "auto", /*mousewheel pixels amount: integer, "auto"*/ autoDraggerLength: true, /*auto-adjust scrollbar dragger length: boolean*/ autoHideScrollbar: false, /*auto-hide scrollbar when idle*/ alwaysShowScrollbar: false, /*always show scrollbar even when there's nothing to scroll (disables autoHideScrollbar): boolean*/ snapAmount: null, /* optional element always snaps to a multiple of this number in pixels */ snapOffset: 0, /* when snapping, snap with this number in pixels as an offset */ scrollButtons: { /*scroll buttons*/ enable: false, /*scroll buttons support: boolean*/ scrollType: "continuous", /*scroll buttons scrolling type: "continuous", "pixels"*/ scrollSpeed: "auto", /*scroll buttons continuous scrolling speed: integer, "auto"*/ scrollAmount: 40 /*scroll buttons pixels scroll amount: integer (pixels)*/ }, advanced: { updateOnBrowserResize: true, /*update scrollbars on browser resize (for layouts based on percentages): boolean*/ updateOnContentResize: false, /*auto-update scrollbars on content resize (for dynamic content): boolean*/ autoExpandHorizontalScroll: false, /*auto-expand width for horizontal scrolling: boolean*/ autoScrollOnFocus: true, /*auto-scroll on focused elements: boolean*/ normalizeMouseWheelDelta: false /*normalize mouse-wheel delta (-1/1)*/ }, contentTouchScroll: true, /*scrolling by touch-swipe content: boolean*/ callbacks: { onScrollStart: function () { }, /*user custom callback function on scroll start event*/ onScroll: function () { }, /*user custom callback function on scroll event*/ onTotalScroll: function () { }, /*user custom callback function on scroll end reached event*/ onTotalScrollBack: function () { }, /*user custom callback function on scroll begin reached event*/ onTotalScrollOffset: 0, /*scroll end reached offset: integer (pixels)*/ onTotalScrollBackOffset: 0, /*scroll begin reached offset: integer (pixels)*/ whileScrolling: function () { } /*user custom callback function on scrolling event*/ }, theme: "light" /*"light", "dark", "light-2", "dark-2", "light-thick", "dark-thick", "light-thin", "dark-thin"*/ }, options = $.extend(true, defaults, options); return this.each(function () { var $this = $(this); /*set element width/height, create markup for custom scrollbars, add classes*/ if (options.set_width) { $this.css("width", options.set_width); } if (options.set_height) { $this.css("height", options.set_height); } if (!$(document).data("mCustomScrollbar-index")) { $(document).data("mCustomScrollbar-index", "1"); } else { var mCustomScrollbarIndex = parseInt($(document).data("mCustomScrollbar-index")); $(document).data("mCustomScrollbar-index", mCustomScrollbarIndex + 1); } $this.wrapInner("<div class='mCustomScrollBox" + " mCS-" + options.theme + "' id='mCSB_" + $(document).data("mCustomScrollbar-index") + "' style='position:relative; height:100%; overflow:hidden; max-width:100%;' />").addClass("mCustomScrollbar _mCS_" + $(document).data("mCustomScrollbar-index")); var mCustomScrollBox = $this.children(".mCustomScrollBox"); if (options.horizontalScroll) { mCustomScrollBox.addClass("mCSB_horizontal").wrapInner("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />"); var mCSB_h_wrapper = mCustomScrollBox.children(".mCSB_h_wrapper"); mCSB_h_wrapper.wrapInner("<div class='mCSB_container' style='position:absolute; left:0;' />").children(".mCSB_container").css({"width": mCSB_h_wrapper.children().outerWidth(), "position": "relative"}).unwrap(); } else { mCustomScrollBox.wrapInner("<div class='mCSB_container' style='position:relative; top:0;' />"); } var mCSB_container = mCustomScrollBox.children(".mCSB_container"); if ($.support.touch) { mCSB_container.addClass("mCS_touch"); } mCSB_container.after("<div class='mCSB_scrollTools' style='position:absolute;'><div class='mCSB_draggerContainer'><div class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'><div class='mCSB_dragger_bar' style='position:relative;'></div></div><div class='mCSB_draggerRail'></div></div></div>"); var mCSB_scrollTools = mCustomScrollBox.children(".mCSB_scrollTools"), mCSB_draggerContainer = mCSB_scrollTools.children(".mCSB_draggerContainer"), mCSB_dragger = mCSB_draggerContainer.children(".mCSB_dragger"); if (options.horizontalScroll) { mCSB_dragger.data("minDraggerWidth", mCSB_dragger.width()); } else { mCSB_dragger.data("minDraggerHeight", mCSB_dragger.height()); } if (options.scrollButtons.enable) { if (options.horizontalScroll) { mCSB_scrollTools.prepend("<a class='mCSB_buttonLeft' oncontextmenu='return false;'></a>").append("<a class='mCSB_buttonRight' oncontextmenu='return false;'></a>"); } else { mCSB_scrollTools.prepend("<a class='mCSB_buttonUp' oncontextmenu='return false;'></a>").append("<a class='mCSB_buttonDown' oncontextmenu='return false;'></a>"); } } /*mCustomScrollBox scrollTop and scrollLeft is always 0 to prevent browser focus scrolling*/ mCustomScrollBox.bind("scroll", function () { if (!$this.is(".mCS_disabled")) { /*native focus scrolling for disabled scrollbars*/ mCustomScrollBox.scrollTop(0).scrollLeft(0); } }); /*store options, global vars/states, intervals*/ $this.data({ /*init state*/ "mCS_Init": true, /*instance index*/ "mCustomScrollbarIndex": $(document).data("mCustomScrollbar-index"), /*option parameters*/ "horizontalScroll": options.horizontalScroll, "scrollInertia": options.scrollInertia, "scrollEasing": "mcsEaseOut", "mouseWheel": options.mouseWheel, "mouseWheelPixels": options.mouseWheelPixels, "autoDraggerLength": options.autoDraggerLength, "autoHideScrollbar": options.autoHideScrollbar, "alwaysShowScrollbar": options.alwaysShowScrollbar, "snapAmount": options.snapAmount, "snapOffset": options.snapOffset, "scrollButtons_enable": options.scrollButtons.enable, "scrollButtons_scrollType": options.scrollButtons.scrollType, "scrollButtons_scrollSpeed": options.scrollButtons.scrollSpeed, "scrollButtons_scrollAmount": options.scrollButtons.scrollAmount, "autoExpandHorizontalScroll": options.advanced.autoExpandHorizontalScroll, "autoScrollOnFocus": options.advanced.autoScrollOnFocus, "normalizeMouseWheelDelta": options.advanced.normalizeMouseWheelDelta, "contentTouchScroll": options.contentTouchScroll, "onScrollStart_Callback": options.callbacks.onScrollStart, "onScroll_Callback": options.callbacks.onScroll, "onTotalScroll_Callback": options.callbacks.onTotalScroll, "onTotalScrollBack_Callback": options.callbacks.onTotalScrollBack, "onTotalScroll_Offset": options.callbacks.onTotalScrollOffset, "onTotalScrollBack_Offset": options.callbacks.onTotalScrollBackOffset, "whileScrolling_Callback": options.callbacks.whileScrolling, /*events binding state*/ "bindEvent_scrollbar_drag": false, "bindEvent_content_touch": false, "bindEvent_scrollbar_click": false, "bindEvent_mousewheel": false, "bindEvent_buttonsContinuous_y": false, "bindEvent_buttonsContinuous_x": false, "bindEvent_buttonsPixels_y": false, "bindEvent_buttonsPixels_x": false, "bindEvent_focusin": false, "bindEvent_autoHideScrollbar": false, /*buttons intervals*/ "mCSB_buttonScrollRight": false, "mCSB_buttonScrollLeft": false, "mCSB_buttonScrollDown": false, "mCSB_buttonScrollUp": false }); /*max-width/max-height*/ if (options.horizontalScroll) { if ($this.css("max-width") !== "none") { if (!options.advanced.updateOnContentResize) { /*needs updateOnContentResize*/ options.advanced.updateOnContentResize = true; } } } else { if ($this.css("max-height") !== "none") { var percentage = false, maxHeight = parseInt($this.css("max-height")); if ($this.css("max-height").indexOf("%") >= 0) { percentage = maxHeight, maxHeight = $this.parent().height() * percentage / 100; } $this.css("overflow", "hidden"); mCustomScrollBox.css("max-height", maxHeight); } } $this.mCustomScrollbar("update"); /*window resize fn (for layouts based on percentages)*/ if (options.advanced.updateOnBrowserResize) { var mCSB_resizeTimeout, currWinWidth = $(window).width(), currWinHeight = $(window).height(); $(window).bind("resize." + $this.data("mCustomScrollbarIndex"), function () { if (mCSB_resizeTimeout) { clearTimeout(mCSB_resizeTimeout); } mCSB_resizeTimeout = setTimeout(function () { if (!$this.is(".mCS_disabled") && !$this.is(".mCS_destroyed")) { var winWidth = $(window).width(), winHeight = $(window).height(); if (currWinWidth !== winWidth || currWinHeight !== winHeight) { /*ie8 fix*/ if ($this.css("max-height") !== "none" && percentage) { mCustomScrollBox.css("max-height", $this.parent().height() * percentage / 100); } $this.mCustomScrollbar("update"); currWinWidth = winWidth; currWinHeight = winHeight; } } }, 150); }); } /*content resize fn (for dynamically generated content)*/ if (options.advanced.updateOnContentResize) { var mCSB_onContentResize; if (options.horizontalScroll) { var mCSB_containerOldSize = mCSB_container.outerWidth(); } else { var mCSB_containerOldSize = mCSB_container.outerHeight(); } mCSB_onContentResize = setInterval(function () { if (options.horizontalScroll) { if (options.advanced.autoExpandHorizontalScroll) { mCSB_container.css({"position": "absolute", "width": "auto"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({"width": mCSB_container.outerWidth(), "position": "relative"}).unwrap(); } var mCSB_containerNewSize = mCSB_container.outerWidth(); } else { var mCSB_containerNewSize = mCSB_container.outerHeight(); } if (mCSB_containerNewSize != mCSB_containerOldSize) { $this.mCustomScrollbar("update"); mCSB_containerOldSize = mCSB_containerNewSize; } }, 300); } }); }, update: function () { var $this = $(this), mCustomScrollBox = $this.children(".mCustomScrollBox"), mCSB_container = mCustomScrollBox.children(".mCSB_container"); mCSB_container.removeClass("mCS_no_scrollbar"); $this.removeClass("mCS_disabled mCS_destroyed"); mCustomScrollBox.scrollTop(0).scrollLeft(0); /*reset scrollTop/scrollLeft to prevent browser focus scrolling*/ var mCSB_scrollTools = mCustomScrollBox.children(".mCSB_scrollTools"), mCSB_draggerContainer = mCSB_scrollTools.children(".mCSB_draggerContainer"), mCSB_dragger = mCSB_draggerContainer.children(".mCSB_dragger"); if ($this.data("horizontalScroll")) { var mCSB_buttonLeft = mCSB_scrollTools.children(".mCSB_buttonLeft"), mCSB_buttonRight = mCSB_scrollTools.children(".mCSB_buttonRight"), mCustomScrollBoxW = mCustomScrollBox.width(); if ($this.data("autoExpandHorizontalScroll")) { mCSB_container.css({"position": "absolute", "width": "auto"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({"width": mCSB_container.outerWidth(), "position": "relative"}).unwrap(); } var mCSB_containerW = mCSB_container.outerWidth(); } else { var mCSB_buttonUp = mCSB_scrollTools.children(".mCSB_buttonUp"), mCSB_buttonDown = mCSB_scrollTools.children(".mCSB_buttonDown"), mCustomScrollBoxH = mCustomScrollBox.height(), mCSB_containerH = mCSB_container.outerHeight(); } if (mCSB_containerH > mCustomScrollBoxH && !$this.data("horizontalScroll")) { /*content needs vertical scrolling*/ mCSB_scrollTools.css("display", "block"); var mCSB_draggerContainerH = mCSB_draggerContainer.height(); /*auto adjust scrollbar dragger length analogous to content*/ if ($this.data("autoDraggerLength")) { var draggerH = Math.round(mCustomScrollBoxH / mCSB_containerH * mCSB_draggerContainerH), minDraggerH = mCSB_dragger.data("minDraggerHeight"); if (draggerH <= minDraggerH) { /*min dragger height*/ mCSB_dragger.css({"height": minDraggerH}); } else if (draggerH >= mCSB_draggerContainerH - 10) { /*max dragger height*/ var mCSB_draggerContainerMaxH = mCSB_draggerContainerH - 10; mCSB_dragger.css({"height": mCSB_draggerContainerMaxH}); } else { mCSB_dragger.css({"height": draggerH}); } mCSB_dragger.children(".mCSB_dragger_bar").css({"line-height": mCSB_dragger.height() + "px"}); } var mCSB_draggerH = mCSB_dragger.height(), /*calculate and store scroll amount, add scrolling*/ scrollAmount = (mCSB_containerH - mCustomScrollBoxH) / (mCSB_draggerContainerH - mCSB_draggerH); $this.data("scrollAmount", scrollAmount).mCustomScrollbar("scrolling", mCustomScrollBox, mCSB_container, mCSB_draggerContainer, mCSB_dragger, mCSB_buttonUp, mCSB_buttonDown, mCSB_buttonLeft, mCSB_buttonRight); /*scroll*/ var mCSB_containerP = Math.abs(mCSB_container.position().top); $this.mCustomScrollbar("scrollTo", mCSB_containerP, {scrollInertia: 0, trigger: "internal"}); } else if (mCSB_containerW > mCustomScrollBoxW && $this.data("horizontalScroll")) { /*content needs horizontal scrolling*/ mCSB_scrollTools.css("display", "block"); var mCSB_draggerContainerW = mCSB_draggerContainer.width(); /*auto adjust scrollbar dragger length analogous to content*/ if ($this.data("autoDraggerLength")) { var draggerW = Math.round(mCustomScrollBoxW / mCSB_containerW * mCSB_draggerContainerW), minDraggerW = mCSB_dragger.data("minDraggerWidth"); if (draggerW <= minDraggerW) { /*min dragger height*/ mCSB_dragger.css({"width": minDraggerW}); } else if (draggerW >= mCSB_draggerContainerW - 10) { /*max dragger height*/ var mCSB_draggerContainerMaxW = mCSB_draggerContainerW - 10; mCSB_dragger.css({"width": mCSB_draggerContainerMaxW}); } else { mCSB_dragger.css({"width": draggerW}); } } var mCSB_draggerW = mCSB_dragger.width(), /*calculate and store scroll amount, add scrolling*/ scrollAmount = (mCSB_containerW - mCustomScrollBoxW) / (mCSB_draggerContainerW - mCSB_draggerW); $this.data("scrollAmount", scrollAmount).mCustomScrollbar("scrolling", mCustomScrollBox, mCSB_container, mCSB_draggerContainer, mCSB_dragger, mCSB_buttonUp, mCSB_buttonDown, mCSB_buttonLeft, mCSB_buttonRight); /*scroll*/ var mCSB_containerP = Math.abs(mCSB_container.position().left); $this.mCustomScrollbar("scrollTo", mCSB_containerP, {scrollInertia: 0, trigger: "internal"}); } else { /*content does not need scrolling*/ /*unbind events, reset content position, hide scrollbars, remove classes*/ mCustomScrollBox.unbind("mousewheel focusin"); if ($this.data("horizontalScroll")) { mCSB_dragger.add(mCSB_container).css("left", 0); } else { mCSB_dragger.add(mCSB_container).css("top", 0); } if ($this.data("alwaysShowScrollbar")) { if (!$this.data("horizontalScroll")) { /*vertical scrolling*/ mCSB_dragger.css({"height": mCSB_draggerContainer.height()}); } else if ($this.data("horizontalScroll")) { /*horizontal scrolling*/ mCSB_dragger.css({"width": mCSB_draggerContainer.width()}); } } else { mCSB_scrollTools.css("display", "none"); mCSB_container.addClass("mCS_no_scrollbar"); } $this.data({"bindEvent_mousewheel": false, "bindEvent_focusin": false}); } }, scrolling: function (mCustomScrollBox, mCSB_container, mCSB_draggerContainer, mCSB_dragger, mCSB_buttonUp, mCSB_buttonDown, mCSB_buttonLeft, mCSB_buttonRight) { var $this = $(this); /*scrollbar drag scrolling*/ if (!$this.data("bindEvent_scrollbar_drag")) { var mCSB_draggerDragY, mCSB_draggerDragX, mCSB_dragger_downEvent, mCSB_dragger_moveEvent, mCSB_dragger_upEvent; if ($.support.pointer) { /*pointer*/ mCSB_dragger_downEvent = "pointerdown"; mCSB_dragger_moveEvent = "pointermove"; mCSB_dragger_upEvent = "pointerup"; } else if ($.support.msPointer) { /*MSPointer*/ mCSB_dragger_downEvent = "MSPointerDown"; mCSB_dragger_moveEvent = "MSPointerMove"; mCSB_dragger_upEvent = "MSPointerUp"; } if ($.support.pointer || $.support.msPointer) { /*pointer, MSPointer*/ mCSB_dragger.bind(mCSB_dragger_downEvent, function (e) { e.preventDefault(); $this.data({"on_drag": true}); mCSB_dragger.addClass("mCSB_dragger_onDrag"); var elem = $(this), elemOffset = elem.offset(), x = e.originalEvent.pageX - elemOffset.left, y = e.originalEvent.pageY - elemOffset.top; if (x < elem.width() && x > 0 && y < elem.height() && y > 0) { mCSB_draggerDragY = y; mCSB_draggerDragX = x; } }); $(document).bind(mCSB_dragger_moveEvent + "." + $this.data("mCustomScrollbarIndex"),function (e) { e.preventDefault(); if ($this.data("on_drag")) { var elem = mCSB_dragger, elemOffset = elem.offset(), x = e.originalEvent.pageX - elemOffset.left, y = e.originalEvent.pageY - elemOffset.top; scrollbarDrag(mCSB_draggerDragY, mCSB_draggerDragX, y, x); } }).bind(mCSB_dragger_upEvent + "." + $this.data("mCustomScrollbarIndex"), function (e) { $this.data({"on_drag": false}); mCSB_dragger.removeClass("mCSB_dragger_onDrag"); }); } else { /*mouse/touch*/ mCSB_dragger.bind("mousedown touchstart",function (e) { e.preventDefault(); e.stopImmediatePropagation(); var elem = $(this), elemOffset = elem.offset(), x, y; if (e.type === "touchstart") { var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]; x = touch.pageX - elemOffset.left; y = touch.pageY - elemOffset.top; } else { $this.data({"on_drag": true}); mCSB_dragger.addClass("mCSB_dragger_onDrag"); x = e.pageX - elemOffset.left; y = e.pageY - elemOffset.top; } if (x < elem.width() && x > 0 && y < elem.height() && y > 0) { mCSB_draggerDragY = y; mCSB_draggerDragX = x; } }).bind("touchmove", function (e) { e.preventDefault(); e.stopImmediatePropagation(); var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0], elem = $(this), elemOffset = elem.offset(), x = touch.pageX - elemOffset.left, y = touch.pageY - elemOffset.top; scrollbarDrag(mCSB_draggerDragY, mCSB_draggerDragX, y, x); }); $(document).bind("mousemove." + $this.data("mCustomScrollbarIndex"),function (e) { if ($this.data("on_drag")) { var elem = mCSB_dragger, elemOffset = elem.offset(), x = e.pageX - elemOffset.left, y = e.pageY - elemOffset.top; scrollbarDrag(mCSB_draggerDragY, mCSB_draggerDragX, y, x); } }).bind("mouseup." + $this.data("mCustomScrollbarIndex"), function (e) { $this.data({"on_drag": false}); mCSB_dragger.removeClass("mCSB_dragger_onDrag"); }); } $this.data({"bindEvent_scrollbar_drag": true}); } function scrollbarDrag(mCSB_draggerDragY, mCSB_draggerDragX, y, x) { if ($this.data("horizontalScroll")) { $this.mCustomScrollbar("scrollTo", (mCSB_dragger.position().left - (mCSB_draggerDragX)) + x, {moveDragger: true, trigger: "internal"}); } else { $this.mCustomScrollbar("scrollTo", (mCSB_dragger.position().top - (mCSB_draggerDragY)) + y, {moveDragger: true, trigger: "internal"}); } } /*content touch-drag*/ if ($.support.touch && $this.data("contentTouchScroll")) { if (!$this.data("bindEvent_content_touch")) { var touch, elem, elemOffset, y, x, mCSB_containerTouchY, mCSB_containerTouchX; mCSB_container.bind("touchstart", function (e) { e.stopImmediatePropagation(); touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]; elem = $(this); elemOffset = elem.offset(); x = touch.pageX - elemOffset.left; y = touch.pageY - elemOffset.top; mCSB_containerTouchY = y; mCSB_containerTouchX = x; }); mCSB_container.bind("touchmove", function (e) { e.preventDefault(); e.stopImmediatePropagation(); touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]; elem = $(this).parent(); elemOffset = elem.offset(); x = touch.pageX - elemOffset.left; y = touch.pageY - elemOffset.top; if ($this.data("horizontalScroll")) { $this.mCustomScrollbar("scrollTo", mCSB_containerTouchX - x, {trigger: "internal"}); } else { $this.mCustomScrollbar("scrollTo", mCSB_containerTouchY - y, {trigger: "internal"}); } }); } } /*dragger rail click scrolling*/ if (!$this.data("bindEvent_scrollbar_click")) { mCSB_draggerContainer.bind("click", function (e) { var scrollToPos = (e.pageY - mCSB_draggerContainer.offset().top) * $this.data("scrollAmount"), target = $(e.target); if ($this.data("horizontalScroll")) { scrollToPos = (e.pageX - mCSB_draggerContainer.offset().left) * $this.data("scrollAmount"); } if (target.hasClass("mCSB_draggerContainer") || target.hasClass("mCSB_draggerRail")) { $this.mCustomScrollbar("scrollTo", scrollToPos, {trigger: "internal", scrollEasing: "draggerRailEase"}); } }); $this.data({"bindEvent_scrollbar_click": true}); } /*mousewheel scrolling*/ if ($this.data("mouseWheel")) { if (!$this.data("bindEvent_mousewheel")) { mCustomScrollBox.bind("mousewheel", function (e, delta) { var scrollTo, mouseWheelPixels = $this.data("mouseWheelPixels"), absPos = Math.abs(mCSB_container.position().top), draggerPos = mCSB_dragger.position().top, limit = mCSB_draggerContainer.height() - mCSB_dragger.height(); if ($this.data("normalizeMouseWheelDelta")) { if (delta < 0) { delta = -1; } else { delta = 1; } } if (mouseWheelPixels === "auto") { mouseWheelPixels = 100 + Math.round($this.data("scrollAmount") / 2); } if ($this.data("horizontalScroll")) { draggerPos = mCSB_dragger.position().left; limit = mCSB_draggerContainer.width() - mCSB_dragger.width(); absPos = Math.abs(mCSB_container.position().left); } if ((delta > 0 && draggerPos !== 0) || (delta < 0 && draggerPos !== limit)) { e.preventDefault(); e.stopImmediatePropagation(); } scrollTo = absPos - (delta * mouseWheelPixels); $this.mCustomScrollbar("scrollTo", scrollTo, {trigger: "internal"}); }); $this.data({"bindEvent_mousewheel": true}); } } /*buttons scrolling*/ if ($this.data("scrollButtons_enable")) { if ($this.data("scrollButtons_scrollType") === "pixels") { /*scroll by pixels*/ if ($this.data("horizontalScroll")) { mCSB_buttonRight.add(mCSB_buttonLeft).unbind("mousedown touchstart MSPointerDown pointerdown mouseup MSPointerUp pointerup mouseout MSPointerOut pointerout touchend", mCSB_buttonRight_stop, mCSB_buttonLeft_stop); $this.data({"bindEvent_buttonsContinuous_x": false}); if (!$this.data("bindEvent_buttonsPixels_x")) { /*scroll right*/ mCSB_buttonRight.bind("click", function (e) { e.preventDefault(); PixelsScrollTo(Math.abs(mCSB_container.position().left) + $this.data("scrollButtons_scrollAmount")); }); /*scroll left*/ mCSB_buttonLeft.bind("click", function (e) { e.preventDefault(); PixelsScrollTo(Math.abs(mCSB_container.position().left) - $this.data("scrollButtons_scrollAmount")); }); $this.data({"bindEvent_buttonsPixels_x": true}); } } else { mCSB_buttonDown.add(mCSB_buttonUp).unbind("mousedown touchstart MSPointerDown pointerdown mouseup MSPointerUp pointerup mouseout MSPointerOut pointerout touchend", mCSB_buttonRight_stop, mCSB_buttonLeft_stop); $this.data({"bindEvent_buttonsContinuous_y": false}); if (!$this.data("bindEvent_buttonsPixels_y")) { /*scroll down*/ mCSB_buttonDown.bind("click", function (e) { e.preventDefault(); PixelsScrollTo(Math.abs(mCSB_container.position().top) + $this.data("scrollButtons_scrollAmount")); }); /*scroll up*/ mCSB_buttonUp.bind("click", function (e) { e.preventDefault(); PixelsScrollTo(Math.abs(mCSB_container.position().top) - $this.data("scrollButtons_scrollAmount")); }); $this.data({"bindEvent_buttonsPixels_y": true}); } } function PixelsScrollTo(to) { if (!mCSB_dragger.data("preventAction")) { mCSB_dragger.data("preventAction", true); $this.mCustomScrollbar("scrollTo", to, {trigger: "internal"}); } } } else { /*continuous scrolling*/ if ($this.data("horizontalScroll")) { mCSB_buttonRight.add(mCSB_buttonLeft).unbind("click"); $this.data({"bindEvent_buttonsPixels_x": false}); if (!$this.data("bindEvent_buttonsContinuous_x")) { /*scroll right*/ mCSB_buttonRight.bind("mousedown touchstart MSPointerDown pointerdown", function (e) { e.preventDefault(); var scrollButtonsSpeed = ScrollButtonsSpeed(); $this.data({"mCSB_buttonScrollRight": setInterval(function () { $this.mCustomScrollbar("scrollTo", Math.abs(mCSB_container.position().left) + scrollButtonsSpeed, {trigger: "internal", scrollEasing: "easeOutCirc"}); }, 17)}); }); var mCSB_buttonRight_stop = function (e) { e.preventDefault(); clearInterval($this.data("mCSB_buttonScrollRight")); } mCSB_buttonRight.bind("mouseup touchend MSPointerUp pointerup mouseout MSPointerOut pointerout", mCSB_buttonRight_stop); /*scroll left*/ mCSB_buttonLeft.bind("mousedown touchstart MSPointerDown pointerdown", function (e) { e.preventDefault(); var scrollButtonsSpeed = ScrollButtonsSpeed(); $this.data({"mCSB_buttonScrollLeft": setInterval(function () { $this.mCustomScrollbar("scrollTo", Math.abs(mCSB_container.position().left) - scrollButtonsSpeed, {trigger: "internal", scrollEasing: "easeOutCirc"}); }, 17)}); }); var mCSB_buttonLeft_stop = function (e) { e.preventDefault(); clearInterval($this.data("mCSB_buttonScrollLeft")); } mCSB_buttonLeft.bind("mouseup touchend MSPointerUp pointerup mouseout MSPointerOut pointerout", mCSB_buttonLeft_stop); $this.data({"bindEvent_buttonsContinuous_x": true}); } } else { mCSB_buttonDown.add(mCSB_buttonUp).unbind("click"); $this.data({"bindEvent_buttonsPixels_y": false}); if (!$this.data("bindEvent_buttonsContinuous_y")) { /*scroll down*/ mCSB_buttonDown.bind("mousedown touchstart MSPointerDown pointerdown", function (e) { e.preventDefault(); var scrollButtonsSpeed = ScrollButtonsSpeed(); $this.data({"mCSB_buttonScrollDown": setInterval(function () { $this.mCustomScrollbar("scrollTo", Math.abs(mCSB_container.position().top) + scrollButtonsSpeed, {trigger: "internal", scrollEasing: "easeOutCirc"}); }, 17)}); }); var mCSB_buttonDown_stop = function (e) { e.preventDefault(); clearInterval($this.data("mCSB_buttonScrollDown")); } mCSB_buttonDown.bind("mouseup touchend MSPointerUp pointerup mouseout MSPointerOut pointerout", mCSB_buttonDown_stop); /*scroll up*/ mCSB_buttonUp.bind("mousedown touchstart MSPointerDown pointerdown", function (e) { e.preventDefault(); var scrollButtonsSpeed = ScrollButtonsSpeed(); $this.data({"mCSB_buttonScrollUp": setInterval(function () { $this.mCustomScrollbar("scrollTo", Math.abs(mCSB_container.position().top) - scrollButtonsSpeed, {trigger: "internal", scrollEasing: "easeOutCirc"}); }, 17)}); }); var mCSB_buttonUp_stop = function (e) { e.preventDefault(); clearInterval($this.data("mCSB_buttonScrollUp")); } mCSB_buttonUp.bind("mouseup touchend MSPointerUp pointerup mouseout MSPointerOut pointerout", mCSB_buttonUp_stop); $this.data({"bindEvent_buttonsContinuous_y": true}); } } function ScrollButtonsSpeed() { var speed = $this.data("scrollButtons_scrollSpeed"); if ($this.data("scrollButtons_scrollSpeed") === "auto") { speed = Math.round(($this.data("scrollInertia") + 100) / 40); } return speed; } } } /*scrolling on element focus (e.g. via TAB key)*/ if ($this.data("autoScrollOnFocus")) { if (!$this.data("bindEvent_focusin")) { mCustomScrollBox.bind("focusin", function () { mCustomScrollBox.scrollTop(0).scrollLeft(0); var focusedElem = $(document.activeElement); if (focusedElem.is("input,textarea,select,button,a[tabindex],area,object")) { var mCSB_containerPos = mCSB_container.position().top, focusedElemPos = focusedElem.position().top, visibleLimit = mCustomScrollBox.height() - focusedElem.outerHeight(); if ($this.data("horizontalScroll")) { mCSB_containerPos = mCSB_container.position().left; focusedElemPos = focusedElem.position().left; visibleLimit = mCustomScrollBox.width() - focusedElem.outerWidth(); } if (mCSB_containerPos + focusedElemPos < 0 || mCSB_containerPos + focusedElemPos > visibleLimit) { $this.mCustomScrollbar("scrollTo", focusedElemPos, {trigger: "internal"}); } } }); $this.data({"bindEvent_focusin": true}); } } /*auto-hide scrollbar*/ if ($this.data("autoHideScrollbar") && !$this.data("alwaysShowScrollbar")) { if (!$this.data("bindEvent_autoHideScrollbar")) { mCustomScrollBox.bind("mouseenter",function (e) { mCustomScrollBox.addClass("mCS-mouse-over"); functions.showScrollbar.call(mCustomScrollBox.children(".mCSB_scrollTools")); }).bind("mouseleave touchend", function (e) { mCustomScrollBox.removeClass("mCS-mouse-over"); if (e.type === "mouseleave") { functions.hideScrollbar.call(mCustomScrollBox.children(".mCSB_scrollTools")); } }); $this.data({"bindEvent_autoHideScrollbar": true}); } } }, scrollTo: function (scrollTo, options) { var $this = $(this), defaults = { moveDragger: false, trigger: "external", callbacks: true, scrollInertia: $this.data("scrollInertia"), scrollEasing: $this.data("scrollEasing") }, options = $.extend(defaults, options), draggerScrollTo, mCustomScrollBox = $this.children(".mCustomScrollBox"), mCSB_container = mCustomScrollBox.children(".mCSB_container"), mCSB_scrollTools = mCustomScrollBox.children(".mCSB_scrollTools"), mCSB_draggerContainer = mCSB_scrollTools.children(".mCSB_draggerContainer"), mCSB_dragger = mCSB_draggerContainer.children(".mCSB_dragger"), contentSpeed = draggerSpeed = options.scrollInertia, scrollBeginning, scrollBeginningOffset, totalScroll, totalScrollOffset; if (!mCSB_container.hasClass("mCS_no_scrollbar")) { $this.data({"mCS_trigger": options.trigger}); if ($this.data("mCS_Init")) { options.callbacks = false; } if (scrollTo || scrollTo === 0) { if (typeof(scrollTo) === "number") { /*if integer, scroll by number of pixels*/ if (options.moveDragger) { /*scroll dragger*/ draggerScrollTo = scrollTo; if ($this.data("horizontalScroll")) { scrollTo = mCSB_dragger.position().left * $this.data("scrollAmount"); } else { scrollTo = mCSB_dragger.position().top * $this.data("scrollAmount"); } draggerSpeed = 0; } else { /*scroll content by default*/ draggerScrollTo = scrollTo / $this.data("scrollAmount"); } } else if (typeof(scrollTo) === "string") { /*if string, scroll by element position*/ var target; if (scrollTo === "top") { /*scroll to top*/ target = 0; } else if (scrollTo === "bottom" && !$this.data("horizontalScroll")) { /*scroll to bottom*/ target = mCSB_container.outerHeight() - mCustomScrollBox.height(); } else if (scrollTo === "left") { /*scroll to left*/ target = 0; } else if (scrollTo === "right" && $this.data("horizontalScroll")) { /*scroll to right*/ target = mCSB_container.outerWidth() - mCustomScrollBox.width(); } else if (scrollTo === "first") { /*scroll to first element position*/ target = $this.find(".mCSB_container").find(":first"); } else if (scrollTo === "last") { /*scroll to last element position*/ target = $this.find(".mCSB_container").find(":last"); } else { /*scroll to element position*/ target = $this.find(scrollTo); } if (target.length === 1) { /*if such unique element exists, scroll to it*/ if ($this.data("horizontalScroll")) { scrollTo = target.position().left; } else { scrollTo = target.position().top; } draggerScrollTo = scrollTo / $this.data("scrollAmount"); } else { draggerScrollTo = scrollTo = target; } } /*scroll to*/ if ($this.data("horizontalScroll")) { if ($this.data("onTotalScrollBack_Offset")) { /*scroll beginning offset*/ scrollBeginningOffset = -$this.data("onTotalScrollBack_Offset"); } if ($this.data("onTotalScroll_Offset")) { /*total scroll offset*/ totalScrollOffset = mCustomScrollBox.width() - mCSB_container.outerWidth() + $this.data("onTotalScroll_Offset"); } if (draggerScrollTo < 0) { /*scroll start position*/ draggerScrollTo = scrollTo = 0; clearInterval($this.data("mCSB_buttonScrollLeft")); if (!scrollBeginningOffset) { scrollBeginning = true; } } else if (draggerScrollTo >= mCSB_draggerContainer.width() - mCSB_dragger.width()) { /*scroll end position*/ draggerScrollTo = mCSB_draggerContainer.width() - mCSB_dragger.width(); scrollTo = mCustomScrollBox.width() - mCSB_container.outerWidth(); clearInterval($this.data("mCSB_buttonScrollRight")); if (!totalScrollOffset) { totalScroll = true; } } else { scrollTo = -scrollTo; } var snapAmount = $this.data("snapAmount"); if (snapAmount) { scrollTo = Math.round(scrollTo / snapAmount) * snapAmount - $this.data("snapOffset"); } /*scrolling animation*/ functions.mTweenAxis.call(this, mCSB_dragger[0], "left", Math.round(draggerScrollTo), draggerSpeed, options.scrollEasing); functions.mTweenAxis.call(this, mCSB_container[0], "left", Math.round(scrollTo), contentSpeed, options.scrollEasing, { onStart: function () { if (options.callbacks && !$this.data("mCS_tweenRunning")) { callbacks("onScrollStart"); } if ($this.data("autoHideScrollbar") && !$this.data("alwaysShowScrollbar")) { functions.showScrollbar.call(mCSB_scrollTools); } }, onUpdate: function () { if (options.callbacks) { callbacks("whileScrolling"); } }, onComplete: function () { if (options.callbacks) { callbacks("onScroll"); if (scrollBeginning || (scrollBeginningOffset && mCSB_container.position().left >= scrollBeginningOffset)) { callbacks("onTotalScrollBack"); } if (totalScroll || (totalScrollOffset && mCSB_container.position().left <= totalScrollOffset)) { callbacks("onTotalScroll"); } } mCSB_dragger.data("preventAction", false); $this.data("mCS_tweenRunning", false); if ($this.data("autoHideScrollbar") && !$this.data("alwaysShowScrollbar")) { if (!mCustomScrollBox.hasClass("mCS-mouse-over")) { functions.hideScrollbar.call(mCSB_scrollTools); } } } }); } else { if ($this.data("onTotalScrollBack_Offset")) { /*scroll beginning offset*/ scrollBeginningOffset = -$this.data("onTotalScrollBack_Offset"); } if ($this.data("onTotalScroll_Offset")) { /*total scroll offset*/ totalScrollOffset = mCustomScrollBox.height() - mCSB_container.outerHeight() + $this.data("onTotalScroll_Offset"); } if (draggerScrollTo < 0) { /*scroll start position*/ draggerScrollTo = scrollTo = 0; clearInterval($this.data("mCSB_buttonScrollUp")); if (!scrollBeginningOffset) { scrollBeginning = true; } } else if (draggerScrollTo >= mCSB_draggerContainer.height() - mCSB_dragger.height()) { /*scroll end position*/ draggerScrollTo = mCSB_draggerContainer.height() - mCSB_dragger.height(); scrollTo = mCustomScrollBox.height() - mCSB_container.outerHeight(); clearInterval($this.data("mCSB_buttonScrollDown")); if (!totalScrollOffset) { totalScroll = true; } } else { scrollTo = -scrollTo; } var snapAmount = $this.data("snapAmount"); if (snapAmount) { scrollTo = Math.round(scrollTo / snapAmount) * snapAmount - $this.data("snapOffset"); } /*scrolling animation*/ functions.mTweenAxis.call(this, mCSB_dragger[0], "top", Math.round(draggerScrollTo), draggerSpeed, options.scrollEasing); functions.mTweenAxis.call(this, mCSB_container[0], "top", Math.round(scrollTo), contentSpeed, options.scrollEasing, { onStart: function () { if (options.callbacks && !$this.data("mCS_tweenRunning")) { callbacks("onScrollStart"); } if ($this.data("autoHideScrollbar") && !$this.data("alwaysShowScrollbar")) { functions.showScrollbar.call(mCSB_scrollTools); } }, onUpdate: function () { if (options.callbacks) { callbacks("whileScrolling"); } }, onComplete: function () { if (options.callbacks) { callbacks("onScroll"); if (scrollBeginning || (scrollBeginningOffset && mCSB_container.position().top >= scrollBeginningOffset)) { callbacks("onTotalScrollBack"); } if (totalScroll || (totalScrollOffset && mCSB_container.position().top <= totalScrollOffset)) { callbacks("onTotalScroll"); } } mCSB_dragger.data("preventAction", false); $this.data("mCS_tweenRunning", false); if ($this.data("autoHideScrollbar") && !$this.data("alwaysShowScrollbar")) { if (!mCustomScrollBox.hasClass("mCS-mouse-over")) { functions.hideScrollbar.call(mCSB_scrollTools); } } } }); } if ($this.data("mCS_Init")) { $this.data({"mCS_Init": false}); } } } /*callbacks*/ function callbacks(cb) { if ($this.data("mCustomScrollbarIndex")) { this.mcs = { top: mCSB_container.position().top, left: mCSB_container.position().left, draggerTop: mCSB_dragger.position().top, draggerLeft: mCSB_dragger.position().left, topPct: Math.round((100 * Math.abs(mCSB_container.position().top)) / Math.abs(mCSB_container.outerHeight() - mCustomScrollBox.height())), leftPct: Math.round((100 * Math.abs(mCSB_container.position().left)) / Math.abs(mCSB_container.outerWidth() - mCustomScrollBox.width())) }; switch (cb) { /*start scrolling callback*/ case "onScrollStart": $this.data("mCS_tweenRunning", true).data("onScrollStart_Callback").call($this, this.mcs); break; case "whileScrolling": $this.data("whileScrolling_Callback").call($this, this.mcs); break; case "onScroll": $this.data("onScroll_Callback").call($this, this.mcs); break; case "onTotalScrollBack": $this.data("onTotalScrollBack_Callback").call($this, this.mcs); break; case "onTotalScroll": $this.data("onTotalScroll_Callback").call($this, this.mcs); break; } } } }, stop: function () { var $this = $(this), mCSB_container = $this.children().children(".mCSB_container"), mCSB_dragger = $this.children().children().children().children(".mCSB_dragger"); functions.mTweenAxisStop.call(this, mCSB_container[0]); functions.mTweenAxisStop.call(this, mCSB_dragger[0]); }, disable: function (resetScroll) { var $this = $(this), mCustomScrollBox = $this.children(".mCustomScrollBox"), mCSB_container = mCustomScrollBox.children(".mCSB_container"), mCSB_scrollTools = mCustomScrollBox.children(".mCSB_scrollTools"), mCSB_dragger = mCSB_scrollTools.children().children(".mCSB_dragger"); mCustomScrollBox.unbind("mousewheel focusin mouseenter mouseleave touchend"); mCSB_container.unbind("touchstart touchmove") if (resetScroll) { if ($this.data("horizontalScroll")) { mCSB_dragger.add(mCSB_container).css("left", 0); } else { mCSB_dragger.add(mCSB_container).css("top", 0); } } mCSB_scrollTools.css("display", "none"); mCSB_container.addClass("mCS_no_scrollbar"); $this.data({"bindEvent_mousewheel": false, "bindEvent_focusin": false, "bindEvent_content_touch": false, "bindEvent_autoHideScrollbar": false}).addClass("mCS_disabled"); }, destroy: function () { var $this = $(this); $this.removeClass("mCustomScrollbar _mCS_" + $this.data("mCustomScrollbarIndex")).addClass("mCS_destroyed").children().children(".mCSB_container").unwrap().children().unwrap().siblings(".mCSB_scrollTools").remove(); $(document).unbind("mousemove." + $this.data("mCustomScrollbarIndex") + " mouseup." + $this.data("mCustomScrollbarIndex") + " MSPointerMove." + $this.data("mCustomScrollbarIndex") + " MSPointerUp." + $this.data("mCustomScrollbarIndex")); $(window).unbind("resize." + $this.data("mCustomScrollbarIndex")); } }, functions = { /*hide/show scrollbar*/ showScrollbar: function () { this.stop().animate({opacity: 1}, "fast"); }, hideScrollbar: function () { this.stop().animate({opacity: 0}, "fast"); }, /*js animation tween*/ mTweenAxis: function (el, prop, to, duration, easing, callbacks) { var callbacks = callbacks || {}, onStart = callbacks.onStart || function () { }, onUpdate = callbacks.onUpdate || function () { }, onComplete = callbacks.onComplete || function () { }; var startTime = _getTime(), _delay, progress = 0, from = el.offsetTop, elStyle = el.style; if (prop === "left") { from = el.offsetLeft; } var diff = to - from; _cancelTween(); _startTween(); function _getTime() { if (window.performance && window.performance.now) { return window.performance.now(); } else { if (window.performance && window.performance.webkitNow) { return window.performance.webkitNow(); } else { if (Date.now) { return Date.now(); } else { return new Date().getTime(); } } } } function _step() { if (!progress) { onStart.call(); } progress = _getTime() - startTime; _tween(); if (progress >= el._time) { el._time = (progress > el._time) ? progress + _delay - (progress - el._time) : progress + _delay - 1; if (el._time < progress + 1) { el._time = progress + 1; } } if (el._time < duration) { el._id = _request(_step); } else { onComplete.call(); } } function _tween() { if (duration > 0) { el.currVal = _ease(el._time, from, diff, duration, easing); elStyle[prop] = Math.round(el.currVal) + "px"; } else { elStyle[prop] = to + "px"; } onUpdate.call(); } function _startTween() { _delay = 1000 / 60; el._time = progress + _delay; _request = (!window.requestAnimationFrame) ? function (f) { _tween(); return setTimeout(f, 0.01); } : window.requestAnimationFrame; el._id = _request(_step); } function _cancelTween() { if (el._id == null) { return; } if (!window.requestAnimationFrame) { clearTimeout(el._id); } else { window.cancelAnimationFrame(el._id); } el._id = null; } function _ease(t, b, c, d, type) { switch (type) { case "linear": return c * t / d + b; break; case "easeOutQuad": t /= d; return -c * t * (t - 2) + b; break; case "easeInOutQuad": t /= d / 2; if (t < 1) return c / 2 * t * t + b; t--; return -c / 2 * (t * (t - 2) - 1) + b; break; case "easeOutCubic": t /= d; t--; return c * (t * t * t + 1) + b; break; case "easeOutQuart": t /= d; t--; return -c * (t * t * t * t - 1) + b; break; case "easeOutQuint": t /= d; t--; return c * (t * t * t * t * t + 1) + b; break; case "easeOutCirc": t /= d; t--; return c * Math.sqrt(1 - t * t) + b; break; case "easeOutSine": return c * Math.sin(t / d * (Math.PI / 2)) + b; break; case "easeOutExpo": return c * ( -Math.pow(2, -10 * t / d) + 1 ) + b; break; case "mcsEaseOut": var ts = (t /= d) * t, tc = ts * t; return b + c * (0.499999999999997 * tc * ts + -2.5 * ts * ts + 5.5 * tc + -6.5 * ts + 4 * t); break; case "draggerRailEase": t /= d / 2; if (t < 1) return c / 2 * t * t * t + b; t -= 2; return c / 2 * (t * t * t + 2) + b; break; } } }, /*stop js animation tweens*/ mTweenAxisStop: function (el) { if (el._id == null) { return; } if (!window.requestAnimationFrame) { clearTimeout(el._id); } else { window.cancelAnimationFrame(el._id); } el._id = null; }, /*detect requestAnimationFrame and polyfill*/ rafPolyfill: function () { var pfx = ["ms", "moz", "webkit", "o"], i = pfx.length; while (--i > -1 && !window.requestAnimationFrame) { window.requestAnimationFrame = window[pfx[i] + "RequestAnimationFrame"]; window.cancelAnimationFrame = window[pfx[i] + "CancelAnimationFrame"] || window[pfx[i] + "CancelRequestAnimationFrame"]; } } } /*detect features*/ functions.rafPolyfill.call(); /*requestAnimationFrame*/ $.support.touch = !!('ontouchstart' in window); /*touch*/ $.support.pointer = window.navigator.pointerEnabled; /*pointer support*/ $.support.msPointer = window.navigator.msPointerEnabled; /*MSPointer support*/ /*plugin dependencies*/ var _dlp = ("https:" == document.location.protocol) ? "https:" : "http:"; $.event.special.mousewheel || document.write('<script src="' + _dlp + '//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.0.6/jquery.mousewheel.min.js"><\/script>'); /*plugin fn*/ $.fn.mCustomScrollbar = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === "object" || !method) { return methods.init.apply(this, arguments); } else { $.error("Method " + method + " does not exist"); } }; })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-mCustomScrollbar.js
jquery-mCustomScrollbar.js
(function ($) { function fixTitle($ele) { if ($ele.attr('title') || typeof($ele.attr('original-title')) != 'string') { $ele.attr('original-title', $ele.attr('title') || '').removeAttr('title'); } } function Tipsy(element, options) { this.$element = $(element); this.options = options; this.enabled = true; fixTitle(this.$element); } Tipsy.prototype = { show: function () { var title = this.getTitle(); if (title && this.enabled) { var $tip = this.tip(); $tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title); $tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity $tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body); var pos = $.extend({}, this.$element.offset(), { width: this.$element[0].offsetWidth, height: this.$element[0].offsetHeight }); var actualWidth = $tip[0].offsetWidth, actualHeight = $tip[0].offsetHeight; var gravity = (typeof this.options.gravity == 'function') ? this.options.gravity.call(this.$element[0]) : this.options.gravity; var offset = (typeof this.options.offset == 'function') ? this.options.offset.call(this.$element[0]) : this.options.offset; var tp; switch (gravity.charAt(0)) { case 'n': tp = {top: pos.top + pos.height + offset, left: pos.left + pos.width / 2 - actualWidth / 2}; break; case 's': tp = {top: pos.top - actualHeight - offset, left: pos.left + pos.width / 2 - actualWidth / 2}; break; case 'e': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - offset}; break; case 'w': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + offset}; break; } if (gravity.length == 2) { if (gravity.charAt(1) == 'w') { tp.left = pos.width < 15 ? pos.left + (pos.width / 2) - 14 : pos.left - 5; } else { tp.left = pos.width < 15 ? pos.left + pos.width - actualWidth + (pos.width / 2) + 4 : pos.left + pos.width - actualWidth + 5; } } tp.left = Math.min(tp.left, $('html').width() - actualWidth - 10); $tip.css(tp).addClass('tipsy-' + gravity); if (this.options.fade) { $tip.stop() .css({ opacity: 0, display: 'block', visibility: 'visible' }) .animate({ opacity: this.options.opacity }); } else { $tip.css({ visibility: 'visible', opacity: this.options.opacity }); } } }, hide: function () { if (this.options.fade) { this.tip().stop().fadeOut(function () { $(this).remove(); }); } else { this.tip().remove(); } }, getTitle: function () { var title, $e = this.$element, o = this.options; fixTitle($e); var title, o = this.options; if (typeof o.title == 'string') { title = $e.attr(o.title == 'title' ? 'original-title' : o.title); } else if (typeof o.title == 'function') { title = o.title.call($e[0]); } title = ('' + title).replace(/(^\s*|\s*$)/, ""); return title || o.fallback; }, tip: function () { if (!this.$tip) { this.$tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"/></div>'); } return this.$tip; }, validate: function () { if (!this.$element[0].parentNode) { this.hide(); this.$element = null; this.options = null; } }, enable: function () { this.enabled = true; }, disable: function () { this.enabled = false; }, toggleEnabled: function () { this.enabled = !this.enabled; } }; $.fn.tipsy = function (options) { if (options === true) { return this.data('tipsy'); } else if (typeof options == 'string') { return this.data('tipsy')[options](); } options = $.extend({}, $.fn.tipsy.defaults, options); function get(ele) { var tipsy = $.data(ele, 'tipsy'); if (!tipsy) { tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options)); $.data(ele, 'tipsy', tipsy); } return tipsy; } function enter() { var tipsy = get(this); tipsy.hoverState = 'in'; if (options.delayIn == 0) { tipsy.show(); } else { setTimeout(function () { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn); } }; function leave() { var tipsy = get(this); tipsy.hoverState = 'out'; if (options.delayOut == 0) { tipsy.hide(); } else { setTimeout(function () { if (tipsy.hoverState == 'out') tipsy.hide(); }, options.delayOut); } }; if (!options.live) this.each(function () { get(this); }); if (options.trigger != 'manual') { var binder = options.live ? 'live' : 'bind', eventIn = options.trigger == 'hover' ? 'mouseenter' : 'focus', eventOut = options.trigger == 'hover' ? 'mouseleave' : 'blur'; this[binder](eventIn, enter)[binder](eventOut, leave); } return this; }; $.fn.tipsy.defaults = { delayIn: 0, delayOut: 0, fade: false, fallback: '', gravity: 'n', html: false, live: false, offset: 0, opacity: 0.8, title: 'title', trigger: 'hover' }; // Overwrite this method to provide options on a per-element basis. // For example, you could store the gravity in a 'tipsy-gravity' attribute: // return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' }); // (remember - do not modify 'options' in place!) $.fn.tipsy.elementOptions = function (ele, options) { return $.metadata ? $.extend({}, options, $(ele).metadata()) : options; }; $.fn.tipsy.autoNS = function () { return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n'; }; $.fn.tipsy.autoWE = function () { return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w'; }; })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-tipsy.js
jquery-tipsy.js
(function ($) { "use strict"; $.fn.rowReordering = function (options) { function _fnStartProcessingMode(oTable) { ///<summary> ///Function that starts "Processing" mode i.e. shows "Processing..." dialog while some action is executing(Default function) ///</summary> if (oTable.fnSettings().oFeatures.bProcessing) { $(".dataTables_processing").css('visibility', 'visible'); } } function _fnEndProcessingMode(oTable) { ///<summary> ///Function that ends the "Processing" mode and returns the table in the normal state(Default function) ///</summary> if (oTable.fnSettings().oFeatures.bProcessing) { $(".dataTables_processing").css('visibility', 'hidden'); } } ///Not used function fnGetStartPosition(oTable, sSelector) { var iStart = 1000000; $(sSelector, oTable).each(function () { var iPosition = parseInt(oTable.fnGetData(this, properties.iIndexColumn)); if (iPosition < iStart) iStart = iPosition; }); return iStart; } function fnCancelSorting(oTable, tbody, properties, iLogLevel, sMessage) { tbody.sortable('cancel'); if (iLogLevel <= properties.iLogLevel) { if (sMessage != undefined) { properties.fnAlert(sMessage, ""); } else { properties.fnAlert("Row cannot be moved", ""); } } properties.fnEndProcessingMode(oTable); } function fnGetState(oTable, sSelector, id) { var tr = $("#" + id, oTable); var iCurrentPosition = oTable.fnGetData(tr[0], properties.iIndexColumn); var iNewPosition = -1; // fnGetStartPosition(sSelector); var sDirection; var trPrevious = tr.prev(sSelector); if (trPrevious.length > 0) { iNewPosition = parseInt(oTable.fnGetData(trPrevious[0], properties.iIndexColumn)); if (iNewPosition < iCurrentPosition) { iNewPosition = iNewPosition + 1; } } else { var trNext = tr.next(sSelector); if (trNext.length > 0) { iNewPosition = parseInt(oTable.fnGetData(trNext[0], properties.iIndexColumn)); if (iNewPosition > iCurrentPosition)//moved back iNewPosition = iNewPosition - 1; } } if (iNewPosition < iCurrentPosition) sDirection = "back"; else sDirection = "forward"; return { sDirection: sDirection, iCurrentPosition: iCurrentPosition, iNewPosition: iNewPosition }; } function fnMoveRows(oTable, sSelector, iCurrentPosition, iNewPosition, sDirection, id, sGroup) { var iStart = iCurrentPosition; var iEnd = iNewPosition; if (sDirection == "back") { iStart = iNewPosition; iEnd = iCurrentPosition; } $(oTable.fnGetNodes()).each(function () { if (sGroup != "" && $(this).attr("data-group") != sGroup) return; var tr = this; var iRowPosition = parseInt(oTable.fnGetData(tr, properties.iIndexColumn)); if (iStart <= iRowPosition && iRowPosition <= iEnd) { if (tr.id == id) { oTable.fnUpdate(iNewPosition, oTable.fnGetPosition(tr), // get row position in current model properties.iIndexColumn, false); // false = defer redraw until all row updates are done } else { if (sDirection == "back") { oTable.fnUpdate(iRowPosition + 1, oTable.fnGetPosition(tr), // get row position in current model properties.iIndexColumn, false); // false = defer redraw until all row updates are done } else { oTable.fnUpdate(iRowPosition - 1, oTable.fnGetPosition(tr), // get row position in current model properties.iIndexColumn, false); // false = defer redraw until all row updates are done } } } }); var oSettings = oTable.fnSettings(); //Standing Redraw Extension //Author: Jonathan Hoguet //http://datatables.net/plug-ins/api#fnStandingRedraw if (oSettings.oFeatures.bServerSide === false) { var before = oSettings._iDisplayStart; oSettings.oApi._fnReDraw(oSettings); //iDisplayStart has been reset to zero - so lets change it back oSettings._iDisplayStart = before; oSettings.oApi._fnCalculateEnd(oSettings); } //draw the 'current' page oSettings.oApi._fnDraw(oSettings); } function _fnAlert(message, type) { alert(message); } var defaults = { iIndexColumn: 0, iStartPosition: 1, sURL: null, sRequestType: "POST", iGroupingLevel: 0, fnAlert: _fnAlert, fnSuccess: jQuery.noop, iLogLevel: 1, sDataGroupAttribute: "data-group", fnStartProcessingMode: _fnStartProcessingMode, fnEndProcessingMode: _fnEndProcessingMode, fnUpdateAjaxRequest: jQuery.noop }; var properties = $.extend(defaults, options); var iFrom, iTo; // Return a helper with preserved width of cells (see Issue 9) var tableFixHelper = function (e, tr) { var $originals = tr.children(); var $helper = tr.clone(); $helper.children().each(function (index) { // Set helper cell sizes to match the original sizes $(this).width($originals.eq(index).width()) }); return $helper; }; return this.each(function () { var oTable = $(this).dataTable(); var aaSortingFixed = (oTable.fnSettings().aaSortingFixed == null ? new Array() : oTable.fnSettings().aaSortingFixed); aaSortingFixed.push([properties.iIndexColumn, "asc"]); oTable.fnSettings().aaSortingFixed = aaSortingFixed; for (var i = 0; i < oTable.fnSettings().aoColumns.length; i++) { oTable.fnSettings().aoColumns[i].bSortable = false; /*for(var j=0; j<aaSortingFixed.length; j++) { if( i == aaSortingFixed[j][0] ) oTable.fnSettings().aoColumns[i].bSortable = false; }*/ } oTable.fnDraw(); $("tbody", oTable).disableSelection().sortable({ cursor: "move", helper: tableFixHelper, update: function (event, ui) { var $dataTable = oTable; var tbody = $(this); var sSelector = "tbody tr"; var sGroup = ""; if (properties.bGroupingUsed) { sGroup = $(ui.item).attr(properties.sDataGroupAttribute); if (sGroup == null || sGroup == undefined) { fnCancelSorting($dataTable, tbody, properties, 3, "Grouping row cannot be moved"); return; } sSelector = "tbody tr[" + properties.sDataGroupAttribute + " ='" + sGroup + "']"; } var oState = fnGetState($dataTable, sSelector, ui.item.context.id); if (oState.iNewPosition == -1) { fnCancelSorting($dataTable, tbody, properties, 2); return; } if (properties.sURL != null) { properties.fnStartProcessingMode($dataTable); var oAjaxRequest = { url: properties.sURL, type: properties.sRequestType, data: { id: ui.item.context.id, fromPosition: oState.iCurrentPosition, toPosition: oState.iNewPosition, direction: oState.sDirection, group: sGroup }, success: function (data) { properties.fnSuccess(data); fnMoveRows($dataTable, sSelector, oState.iCurrentPosition, oState.iNewPosition, oState.sDirection, ui.item.context.id, sGroup); properties.fnEndProcessingMode($dataTable); }, error: function (jqXHR) { fnCancelSorting($dataTable, tbody, properties, 1, jqXHR.statusText); } }; properties.fnUpdateAjaxRequest(oAjaxRequest, properties, $dataTable); $.ajax(oAjaxRequest); } else { fnMoveRows($dataTable, sSelector, oState.iCurrentPosition, oState.iNewPosition, oState.sDirection, ui.item.context.id, sGroup); } } }); }); }; })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-rowReordering.js
jquery-dataTables-rowReordering.js
(function(a){a.fn.rowReordering=function(n){function c(o){if(o.fnSettings().oFeatures.bProcessing){a(".dataTables_processing").css("visibility","visible")}}function e(o){if(o.fnSettings().oFeatures.bProcessing){a(".dataTables_processing").css("visibility","hidden")}}function j(p,q){var o=1000000;a(q,p).each(function(){var r=parseInt(p.fnGetData(this,k.iIndexColumn));if(r<o){o=r}});return o}function h(o,p,r,s,q){p.sortable("cancel");if(s<=r.iLogLevel){if(q!=undefined){r.fnAlert(q,"")}else{r.fnAlert("Row cannot be moved","")}}r.fnEndProcessingMode(o)}function d(u,t,p){var s=a("#"+p,u);var w=u.fnGetData(s[0],k.iIndexColumn);var v=-1;var o;var q=s.prev(t);if(q.length>0){v=parseInt(u.fnGetData(q[0],k.iIndexColumn));if(v<w){v=v+1}}else{var r=s.next(t);if(r.length>0){v=parseInt(u.fnGetData(r[0],k.iIndexColumn));if(v>w){v=v-1}}}if(v<w){o="back"}else{o="forward"}return{sDirection:o,iCurrentPosition:w,iNewPosition:v}}function m(u,s,w,v,o,p,x){var q=w;var y=v;if(o=="back"){q=v;y=w}a(u.fnGetNodes()).each(function(){if(x!=""&&a(this).attr("data-group")!=x){return}var A=this;var z=parseInt(u.fnGetData(A,k.iIndexColumn));if(q<=z&&z<=y){if(A.id==p){u.fnUpdate(v,u.fnGetPosition(A),k.iIndexColumn,false)}else{if(o=="back"){u.fnUpdate(z+1,u.fnGetPosition(A),k.iIndexColumn,false)}else{u.fnUpdate(z-1,u.fnGetPosition(A),k.iIndexColumn,false)}}}});var r=u.fnSettings();if(r.oFeatures.bServerSide===false){var t=r._iDisplayStart;r.oApi._fnReDraw(r);r._iDisplayStart=t;r.oApi._fnCalculateEnd(r)}r.oApi._fnDraw(r)}function g(p,o){alert(p)}var f={iIndexColumn:0,iStartPosition:1,sURL:null,sRequestType:"POST",iGroupingLevel:0,fnAlert:g,fnSuccess:jQuery.noop,iLogLevel:1,sDataGroupAttribute:"data-group",fnStartProcessingMode:c,fnEndProcessingMode:e,fnUpdateAjaxRequest:jQuery.noop};var k=a.extend(f,n);var b,l;var i=function(q,o){var p=o.children();var r=o.clone();r.children().each(function(s){a(this).width(p.eq(s).width())});return r};return this.each(function(){var o=a(this).dataTable();var q=(o.fnSettings().aaSortingFixed==null?new Array():o.fnSettings().aaSortingFixed);q.push([k.iIndexColumn,"asc"]);o.fnSettings().aaSortingFixed=q;for(var p=0;p<o.fnSettings().aoColumns.length;p++){o.fnSettings().aoColumns[p].bSortable=false}o.fnDraw();a("tbody",o).disableSelection().sortable({cursor:"move",helper:i,update:function(w,x){var v=o;var u=a(this);var y="tbody tr";var r="";if(k.bGroupingUsed){r=a(x.item).attr(k.sDataGroupAttribute);if(r==null||r==undefined){h(v,u,k,3,"Grouping row cannot be moved");return}y="tbody tr["+k.sDataGroupAttribute+" ='"+r+"']"}var t=d(v,y,x.item.context.id);if(t.iNewPosition==-1){h(v,u,k,2);return}if(k.sURL!=null){k.fnStartProcessingMode(v);var s={url:k.sURL,type:k.sRequestType,data:{id:x.item.context.id,fromPosition:t.iCurrentPosition,toPosition:t.iNewPosition,direction:t.sDirection,group:r},success:function(z){k.fnSuccess(z);m(v,y,t.iCurrentPosition,t.iNewPosition,t.sDirection,x.item.context.id,r);k.fnEndProcessingMode(v)},error:function(z){h(v,u,k,1,z.statusText)}};k.fnUpdateAjaxRequest(s,k,v);a.ajax(s)}else{m(v,y,t.iCurrentPosition,t.iNewPosition,t.sDirection,x.item.context.id,r)}}})})}})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-rowReordering.min.js
jquery-dataTables-rowReordering.min.js
(function(c,a,d){var b=function(h,g){var f=function(j,i){if(!this instanceof f){alert("Scroller warning: Scroller must be initialised with the 'new' keyword.");return}if(typeof i=="undefined"){i={}}this.s={dt:j,tableTop:0,tableBottom:0,redrawTop:0,redrawBottom:0,autoHeight:true,viewportRows:0,stateTO:null,drawTO:null,heights:{jump:null,page:null,virtual:null,scroll:null,row:null,viewport:null},topRowFloat:0,scrollDrawDiff:null};this.s=h.extend(this.s,f.oDefaults,i);this.dom={force:a.createElement("div"),scroller:null,table:null};this.s.dt.oScroller=this;this._fnConstruct()};f.prototype={fnRowToPixels:function(i,l,k){var m;if(k){m=this._domain("virtualToPhysical",i*this.s.heights.row)}else{var j=i-this.s.baseRowTop;m=this.s.baseScrollTop+(j*this.s.heights.row)}return l||l===d?parseInt(m,10):m},fnPixelsToRow:function(m,k,j){var i=m-this.s.baseScrollTop;var l=j?this._domain("physicalToVirtual",m)/this.s.heights.row:(i/this.s.heights.row)+this.s.baseRowTop;return k||k===d?parseInt(l,10):l},fnScrollToRow:function(o,n){var m=this;var j=false;var l=this.fnRowToPixels(o);var i=((this.s.displayBuffer-1)/2)*this.s.viewportRows;var k=o-i;if(k<0){k=0}if((l>this.s.redrawBottom||l<this.s.redrawTop)&&this.s.dt._iDisplayStart!==k){j=true;l=this.fnRowToPixels(o,false,true)}if(typeof n=="undefined"||n){this.s.ani=j;h(this.dom.scroller).animate({scrollTop:l},function(){setTimeout(function(){m.s.ani=false},0)})}else{h(this.dom.scroller).scrollTop(l)}},fnMeasure:function(j){if(this.s.autoHeight){this._fnCalcRowHeight()}var i=this.s.heights;i.viewport=h(this.dom.scroller).height();this.s.viewportRows=parseInt(i.viewport/i.row,10)+1;this.s.dt._iDisplayLength=this.s.viewportRows*this.s.displayBuffer;if(typeof j=="undefined"||j){this.s.dt.oInstance.fnDraw()}},_fnConstruct:function(){var i=this;if(!this.s.dt.oFeatures.bPaginate){this.s.dt.oApi._fnLog(this.s.dt,0,"Pagination must be enabled for Scroller");return}this.dom.force.style.position="absolute";this.dom.force.style.top="0px";this.dom.force.style.left="0px";this.dom.force.style.width="1px";this.dom.scroller=h("div."+this.s.dt.oClasses.sScrollBody,this.s.dt.nTableWrapper)[0];this.dom.scroller.appendChild(this.dom.force);this.dom.scroller.style.position="relative";this.dom.table=h(">table",this.dom.scroller)[0];this.dom.table.style.position="absolute";this.dom.table.style.top="0px";this.dom.table.style.left="0px";h(this.s.dt.nTableWrapper).addClass("DTS");if(this.s.loadingIndicator){h(this.dom.scroller.parentNode).css("position","relative").append('<div class="DTS_Loading">'+this.s.dt.oLanguage.sLoadingRecords+"</div>")}if(this.s.heights.row&&this.s.heights.row!="auto"){this.s.autoHeight=false}this.fnMeasure(false);h(this.dom.scroller).on("scroll.DTS",function(){i._fnScroll.call(i)});h(this.dom.scroller).on("touchstart.DTS",function(){i._fnScroll.call(i)});this.s.dt.aoDrawCallback.push({fn:function(){if(i.s.dt.bInitialised){i._fnDrawCallback.call(i)}},sName:"Scroller"});h(c).on("resize.DTS",function(){i._fnInfo()});var j=true;this.s.dt.oApi._fnCallbackReg(this.s.dt,"aoStateSaveParams",function(k,l){if(j&&i.s.dt.oLoadedState){l.iScroller=i.s.dt.oLoadedState.iScroller;j=false}else{l.iScroller=i.dom.scroller.scrollTop}},"Scroller_State");this.s.dt.aoDestroyCallback.push({sName:"Scroller",fn:function(){h(c).off("resize.DTS");h(i.dom.scroller).off("touchstart.DTS scroll.DTS");h(i.s.dt.nTableWrapper).removeClass("DTS");h("div.DTS_Loading",i.dom.scroller.parentNode).remove();i.dom.table.style.position="";i.dom.table.style.top="";i.dom.table.style.left=""}})},_fnScroll:function(){var l=this,m=this.s.heights,k=this.dom.scroller.scrollTop,n;if(this.s.skip){return}if(this.s.dt.bFiltered||this.s.dt.bSorted){this.s.lastScrollTop=0;return}this._fnInfo();clearTimeout(this.s.stateTO);this.s.stateTO=setTimeout(function(){l.s.dt.oApi._fnSaveState(l.s.dt)},250);if(k<this.s.redrawTop||k>this.s.redrawBottom){var j=((this.s.displayBuffer-1)/2)*this.s.viewportRows;if(Math.abs(k-this.s.lastScrollTop)>m.viewport||this.s.ani){n=parseInt(this._domain("physicalToVirtual",k)/m.row,10)-j;this.s.topRowFloat=(this._domain("physicalToVirtual",k)/m.row)}else{n=this.fnPixelsToRow(k)-j;this.s.topRowFloat=this.fnPixelsToRow(k,false)}if(n<=0){n=0}else{if(n+this.s.dt._iDisplayLength>this.s.dt.fnRecordsDisplay()){n=this.s.dt.fnRecordsDisplay()-this.s.dt._iDisplayLength;if(n<0){n=0}}else{if(n%2!==0){n++}}}if(n!=this.s.dt._iDisplayStart){this.s.tableTop=h(this.s.dt.nTable).offset().top;this.s.tableBottom=h(this.s.dt.nTable).height()+this.s.tableTop;var i=function(){if(l.s.scrollDrawReq===null){l.s.scrollDrawReq=k}l.s.dt._iDisplayStart=n;if(l.s.dt.oApi._fnCalculateEnd){l.s.dt.oApi._fnCalculateEnd(l.s.dt)}l.s.dt.oApi._fnDraw(l.s.dt)};if(this.s.dt.oFeatures.bServerSide){clearTimeout(this.s.drawTO);this.s.drawTO=setTimeout(i,this.s.serverWait)}else{i()}}}this.s.lastScrollTop=k},_domain:function(j,m){var l=this.s.heights;var i;if(l.virtual===l.scroll){i=(l.virtual-l.viewport)/(l.scroll-l.viewport);if(j==="virtualToPhysical"){return m/i}else{if(j==="physicalToVirtual"){return m*i}}}var n=(l.scroll-l.viewport)/2;var k=(l.virtual-l.viewport)/2;i=k/(n*n);if(j==="virtualToPhysical"){if(m<k){return Math.pow(m/i,0.5)}else{m=(k*2)-m;return m<0?l.scroll:(n*2)-Math.pow(m/i,0.5)}}else{if(j==="physicalToVirtual"){if(m<n){return m*m*i}else{m=(n*2)-m;return m<0?l.virtual:(k*2)-(m*m*i)}}}},_fnDrawCallback:function(){var m=this,n=this.s.heights,l=this.dom.scroller.scrollTop,s=l,j=l+n.viewport,q=h(this.s.dt.nTable).height(),t=this.s.dt._iDisplayStart,k=this.s.dt._iDisplayLength,i=this.s.dt.fnRecordsDisplay();this.s.skip=true;this._fnScrollForce();if(t===0){l=this.s.topRowFloat*n.row}else{if(t+k>=i){l=n.scroll-((i-this.s.topRowFloat)*n.row)}else{l=this._domain("virtualToPhysical",this.s.topRowFloat*n.row)}}this.dom.scroller.scrollTop=l;this.s.baseScrollTop=l;this.s.baseRowTop=this.s.topRowFloat;var r=l-((this.s.topRowFloat-t)*n.row);if(t===0){r=0}else{if(t+k>=i){r=n.scroll-q}}this.dom.table.style.top=r+"px";this.s.tableTop=r;this.s.tableBottom=q+this.s.tableTop;var p=(l-this.s.tableTop)*this.s.boundaryScale;this.s.redrawTop=l-p;this.s.redrawBottom=l+p;this.s.skip=false;setTimeout(function(){m._fnInfo.call(m)},0);if(this.s.dt.oFeatures.bStateSave&&this.s.dt.oLoadedState!==null&&typeof this.s.dt.oLoadedState.iScroller!="undefined"){var o=this.s.dt.sAjaxSource||m.s.dt.ajax?true:false;if((o&&this.s.dt.iDraw==2)||(!o&&this.s.dt.iDraw==1)){setTimeout(function(){h(m.dom.scroller).scrollTop(m.s.dt.oLoadedState.iScroller);m.s.redrawTop=m.s.dt.oLoadedState.iScroller-(n.viewport/2)},0)}}},_fnScrollForce:function(){var j=this.s.heights;var i=1000000;j.virtual=j.row*this.s.dt.fnRecordsDisplay();j.scroll=j.virtual;if(j.scroll>i){j.scroll=i}this.dom.force.style.height=j.scroll+"px"},_fnCalcRowHeight:function(){var k=this.s.dt.nTable.cloneNode(false);var j=h("<tbody/>").appendTo(k);var i=h('<div class="'+this.s.dt.oClasses.sWrapper+' DTS"><div class="'+this.s.dt.oClasses.sScrollWrapper+'"><div class="'+this.s.dt.oClasses.sScrollBody+'"></div></div></div>');h("tbody tr:lt(4)",k).clone().appendTo(j);while(h("tr",j).length<3){j.append("<tr><td>&nbsp;</td></tr>")}h("div."+this.s.dt.oClasses.sScrollBody,i).append(k);i.appendTo("body");this.s.heights.row=h("tr",j).eq(1).outerHeight();i.remove()},_fnInfo:function(){if(!this.s.dt.oFeatures.bInfo){return}var k=this.s.dt,q=this.dom.scroller.scrollTop,j=Math.floor(this.fnPixelsToRow(q,false,this.s.ani)+1),r=k.fnRecordsTotal(),v=k.fnRecordsDisplay(),s=Math.ceil(this.fnPixelsToRow(q+this.s.heights.viewport,false,this.s.ani)),y=v<s?v:s,l=k.fnFormatNumber(j),p=k.fnFormatNumber(y),x=k.fnFormatNumber(r),w=k.fnFormatNumber(v),u;if(k.fnRecordsDisplay()===0&&k.fnRecordsDisplay()==k.fnRecordsTotal()){u=k.oLanguage.sInfoEmpty+k.oLanguage.sInfoPostFix}else{if(k.fnRecordsDisplay()===0){u=k.oLanguage.sInfoEmpty+" "+k.oLanguage.sInfoFiltered.replace("_MAX_",x)+k.oLanguage.sInfoPostFix}else{if(k.fnRecordsDisplay()==k.fnRecordsTotal()){u=k.oLanguage.sInfo.replace("_START_",l).replace("_END_",p).replace("_TOTAL_",w)+k.oLanguage.sInfoPostFix}else{u=k.oLanguage.sInfo.replace("_START_",l).replace("_END_",p).replace("_TOTAL_",w)+" "+k.oLanguage.sInfoFiltered.replace("_MAX_",k.fnFormatNumber(k.fnRecordsTotal()))+k.oLanguage.sInfoPostFix}}}var o=k.aanFeatures.i;if(typeof o!="undefined"){for(var t=0,m=o.length;t<m;t++){h(o[t]).html(u)}}}};f.defaults={trace:false,rowHeight:"auto",serverWait:200,displayBuffer:9,boundaryScale:0.5,loadingIndicator:false};f.oDefaults=f.defaults;f.version="1.2.0";if(typeof h.fn.dataTable=="function"&&typeof h.fn.dataTableExt.fnVersionCheck=="function"&&h.fn.dataTableExt.fnVersionCheck("1.9.0")){h.fn.dataTableExt.aoFeatures.push({fnInit:function(l){var k=l.oInit;var j=k.scroller||k.oScroller||{};var i=new f(l,j);return i.dom.wrapper},cFeature:"S",sFeature:"Scroller"})}else{alert("Warning: Scroller requires DataTables 1.9.0 or greater - www.datatables.net/download")}h.fn.dataTable.Scroller=f;h.fn.DataTable.Scroller=f;if(h.fn.dataTable.Api){var e=h.fn.dataTable.Api;e.register("scroller().rowToPixels()",function(j,l,k){var i=this.context;if(i.length&&i[0].oScroller){return i[0].oScroller.fnRowToPixels(j,l,k)}});e.register("scroller().pixelsToRow()",function(l,k,j){var i=this.context;if(i.length&&i[0].oScroller){return i[0].oScroller.fnPixelsToRow(l,k,j)}});e.register("scroller().scrollToRow()",function(j,i){this.iterator("table",function(k){if(k.oScroller){k.oScroller.fnScrollToRow(j,i)}});return this});e.register("scroller().measure()",function(i){this.iterator("table",function(j){if(j.oScroller){j.oScroller.fnMeasure(i)}});return this})}return f};b(jQuery,jQuery.fn.dataTable)})(window,document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-scroller.min.js
jquery-dataTables-scroller.min.js
(function ($) { $.fn.makeEditable = function (options) { var iDisplayStart = 0; function fnGetCellID(cell) { ///<summary> ///Utility function used to determine id of the cell ///By default it is assumed that id is placed as an id attribute of <tr> that that surround the cell (<td> tag). E.g.: ///<tr id="17"> /// <td>...</td><td>...</td><td>...</td><td>...</td> ///</tr> ///</summary> ///<param name="cell" type="DOM" domElement="true">TD cell refference</param> return properties.fnGetRowID($(cell.parentNode)); } function _fnSetRowIDInAttribute(row, id, overwrite) { ///<summary> ///Utility function used to set id of the row. Usually when a new record is created, added to the table, ///and when id of the record is retrieved from the server-side. ///It is assumed that id is placed as an id attribute of <tr> that that surround the cell (<td> tag). E.g.: ///<tr id="17"> /// <td>...</td><td>...</td><td>...</td><td>...</td> ///</tr> ///This function is used when a datatable is configured in the server side processing mode or ajax source mode ///</summary> ///<param name="row" type="DOM" domElement="true">TR row where record is placed</param> if (overwrite) { row.attr("id", id); } else { if (row.attr("id") == null || row.attr("id") == "") row.attr("id", id); } } function _fnGetRowIDFromAttribute(row) { ///<summary> ///Utility function used to get id of the row. ///It is assumed that id is placed as an id attribute of <tr> that that surround the cell (<td> tag). E.g.: ///<tr id="17"> /// <td>...</td><td>...</td><td>...</td><td>...</td> ///</tr> ///This function is used when a datatable is configured in the standard client side mode ///</summary> ///<param name="row" type="DOM" domElement="true">TR row where record is placed</param> ///<returns type="Number">Id of the row - by default id attribute placed in the TR tag</returns> return row.attr("id"); } function _fnSetRowIDInFirstCell(row, id) { ///<summary> ///Utility function used to set id of the row. Usually when a new record is created, added to the table, ///and when id of the record is retrieved from the server-side). ///It is assumed that id is placed as a value of the first &lt;TD&gt; cell in the &lt;TR&gt;. As example: ///<tr> /// <td>17</td><td>...</td><td>...</td><td>...</td> ///</tr> ///This function is used when a datatable is configured in the server side processing mode or ajax source mode ///</summary> ///<param name="row" type="DOM" domElement="true">TR row where record is placed</param> $("td:first", row).html(id); } function _fnGetRowIDFromFirstCell(row) { ///<summary> ///Utility function used to get id of the row. ///It is assumed that id is placed as a value of the first &lt;TD&gt; cell in the &lt;TR&gt;. As example: ///<tr> /// <td>17</td><td>...</td><td>...</td><td>...</td> ///</tr> ///This function is used when a datatable is configured in the server side processing mode or ajax source mode ///</summary> ///<param name="row" type="DOM" domElement="true">TR row where record is placed</param> ///<returns type="Number">Id of the row - by default id attribute placed in the TR tag</returns> return $("td:first", row).html(); } //Reference to the DataTable object var oTable; //Refences to the buttons used for manipulating table data var oAddNewRowButton, oDeleteRowButton, oConfirmRowAddingButton, oCancelRowAddingButton; //Reference to the form used for adding new data var oAddNewRowForm; //Plugin options var properties; function _fnShowError(errorText, action) { ///<summary> ///Shows an error message (Default function) ///</summary> ///<param name="errorText" type="String">text that should be shown</param> ///<param name="action" type="String"> action that was executed when error occured e.g. "update", "delete", or "add"</param> alert(errorText); } function _fnStartProcessingMode() { ///<summary> ///Function that starts "Processing" mode i.e. shows "Processing..." dialog while some action is executing(Default function) ///</summary> if (oTable.fnSettings().oFeatures.bProcessing) { $(".dataTables_processing").css('visibility', 'visible'); } } function _fnEndProcessingMode() { ///<summary> ///Function that ends the "Processing" mode and returns the table in the normal state(Default function) ///It shows processing message only if bProcessing setting is set to true ///</summary> if (oTable.fnSettings().oFeatures.bProcessing) { $(".dataTables_processing").css('visibility', 'hidden'); } } var sOldValue, sNewCellValue, sNewCellDislayValue; function fnApplyEditable(aoNodes) { ///<summary> ///Function that applies editable plugin to the array of table rows ///</summary> ///<param name="aoNodes" type="Array[TR]">Aray of table rows &lt;TR&gt; that should be initialized with editable plugin</param> if (properties.bDisableEditing) return; var oDefaultEditableSettings = { event: 'dblclick', "onsubmit": function (settings, original) { sOldValue = original.revert; sNewCellValue = null; sNewCellDisplayValue = null; iDisplayStart = fnGetDisplayStart(); if(settings.type == "text" || settings.type == "select" || settings.type == "textarea" ) { var input = $("input,select,textarea", this); sNewCellValue = $("input,select,textarea", $(this)).val(); if (input.length == 1) { var oEditElement = input[0]; if (oEditElement.nodeName.toLowerCase() == "select" || oEditElement.tagName.toLowerCase() == "select") sNewCellDisplayValue = $("option:selected", oEditElement).text(); //For select list use selected text instead of value for displaying in table else sNewCellDisplayValue = sNewCellValue; } if (!properties.fnOnEditing(input, settings, original.revert, fnGetCellID(original))) return false; var x = settings; //2.2.2 INLINE VALIDATION if (settings.oValidationOptions != null) { input.parents("form").validate(settings.oValidationOptions); } if (settings.cssclass != null) { input.addClass(settings.cssclass); } if(settings.cssclass == null && settings.oValidationOptions == null){ return true; }else{ if (!input.valid() || 0 == input.valid()) return false; else return true; } } properties.fnStartProcessingMode(); }, "submitdata": function (value, settings) { //iDisplayStart = fnGetDisplayStart(); //properties.fnStartProcessingMode(); var id = fnGetCellID(this); var rowId = oTable.fnGetPosition(this)[0]; var columnPosition = oTable.fnGetPosition(this)[1]; var columnId = oTable.fnGetPosition(this)[2]; var sColumnName = oTable.fnSettings().aoColumns[columnId].sName; if (sColumnName == null || sColumnName == "") sColumnName = oTable.fnSettings().aoColumns[columnId].sTitle; var updateData = null; if (properties.aoColumns == null || properties.aoColumns[columnId] == null) { updateData = $.extend({}, properties.oUpdateParameters, { "id": id, "rowId": rowId, "columnPosition": columnPosition, "columnId": columnId, "columnName": sColumnName }); } else { updateData = $.extend({}, properties.oUpdateParameters, properties.aoColumns[columnId].oUpdateParameters, { "id": id, "rowId": rowId, "columnPosition": columnPosition, "columnId": columnId, "columnName": sColumnName }); } return updateData; }, "callback": function (sValue, settings) { properties.fnEndProcessingMode(); var status = ""; var aPos = oTable.fnGetPosition(this); var bRefreshTable = !oSettings.oFeatures.bServerSide; $("td.last-updated-cell", oTable.fnGetNodes( )).removeClass("last-updated-cell"); if(sValue.indexOf(properties.sFailureResponsePrefix)>-1) { oTable.fnUpdate(sOldValue, aPos[0], aPos[2], bRefreshTable); $("td.last-updated-cell", oTable).removeClass("last-updated-cell"); $(this).addClass("last-updated-cell"); properties.fnShowError(sValue.replace(properties.sFailureResponsePrefix, "").trim(), "update"); status = "failure"; } else { if (properties.sSuccessResponse == "IGNORE" || ( properties.aoColumns != null && properties.aoColumns[aPos[2]] != null && properties.aoColumns[aPos[2]].sSuccessResponse == "IGNORE") || (sNewCellValue == null) || (sNewCellValue == sValue) || properties.sSuccessResponse == sValue) { if(sNewCellDisplayValue == null) { //sNewCellDisplayValue = sValue; oTable.fnUpdate(sValue, aPos[0], aPos[2], bRefreshTable); }else{ oTable.fnUpdate(sNewCellDisplayValue, aPos[0], aPos[2], bRefreshTable); } $("td.last-updated-cell", oTable).removeClass("last-updated-cell"); $(this).addClass("last-updated-cell"); status = "success"; } else { oTable.fnUpdate(sOldValue, aPos[0], aPos[2], bRefreshTable); properties.fnShowError(sValue, "update"); status = "failure"; } } properties.fnOnEdited(status, sOldValue, sNewCellDisplayValue, aPos[0], aPos[1], aPos[2]); if (settings.fnOnCellUpdated != null) { settings.fnOnCellUpdated(status, sValue, aPos[0], aPos[2], settings); } fnSetDisplayStart(); if (properties.bUseKeyTable) { var keys = oTable.keys; /* Unblock KeyTable, but only after this 'esc' key event has finished. Otherwise * it will 'esc' KeyTable as well */ setTimeout(function () { keys.block = false; }, 0); } }, "onerror": function () { properties.fnEndProcessingMode(); properties.fnShowError("Cell cannot be updated", "update"); properties.fnOnEdited("failure"); }, "onreset": function(){ if (properties.bUseKeyTable) { var keys = oTable.keys; /* Unblock KeyTable, but only after this 'esc' key event has finished. Otherwise * it will 'esc' KeyTable as well */ setTimeout(function () { keys.block = false; }, 0); } }, "height": properties.sEditorHeight, "width": properties.sEditorWidth }; var cells = null; if (properties.aoColumns != null) { for (var iDTindex = 0, iDTEindex = 0; iDTindex < oSettings.aoColumns.length; iDTindex++) { if (oSettings.aoColumns[iDTindex].bVisible) {//if DataTables column is visible if (properties.aoColumns[iDTEindex] == null) { //If editor for the column is not defined go to the next column iDTEindex++; continue; } //Get all cells in the iDTEindex column (nth child is 1-indexed array) cells = $("td:nth-child(" + (iDTEindex + 1) + ")", aoNodes); var oColumnSettings = oDefaultEditableSettings; oColumnSettings = $.extend({}, oDefaultEditableSettings, properties.oEditableSettings, properties.aoColumns[iDTEindex]); iDTEindex++; var sUpdateURL = properties.sUpdateURL; try { if (oColumnSettings.sUpdateURL != null) sUpdateURL = oColumnSettings.sUpdateURL; } catch (ex) { } //cells.editable(sUpdateURL, oColumnSettings); cells.each(function () { if (!$(this).hasClass(properties.sReadOnlyCellClass)) { $(this).editable(sUpdateURL, oColumnSettings); } }); } } //end for } else { cells = $('td:not(.' + properties.sReadOnlyCellClass + ')', aoNodes); cells.editable(properties.sUpdateURL, $.extend({}, oDefaultEditableSettings, properties.oEditableSettings)); } } function fnOnRowAdding(event) { ///<summary> ///Event handler called when a user click on the submit button in the "Add new row" form. ///</summary> ///<param name="event">Event that caused the action</param> if (properties.fnOnAdding()) { if (oAddNewRowForm.valid()) { iDisplayStart = fnGetDisplayStart(); properties.fnStartProcessingMode(); if (properties.bUseFormsPlugin) { //Still in beta(development) $(oAddNewRowForm).ajaxSubmit({ dataType: 'xml', success: function (response, statusString, xhr) { if (xhr.responseText.toLowerCase().indexOf("error") != -1) { properties.fnEndProcessingMode(); properties.fnShowError(xhr.responseText.replace("Error",""), "add"); properties.fnOnAdded("failure"); } else { fnOnRowAdded(xhr.responseText); } }, error: function (response) { properties.fnEndProcessingMode(); properties.fnShowError(response.responseText, "add"); properties.fnOnAdded("failure"); } } ); } else { var params = oAddNewRowForm.serialize(); $.ajax({ 'url': properties.sAddURL, 'data': params, 'type': properties.sAddHttpMethod, 'dataType': properties.sAddDataType, success: fnOnRowAdded, error: function (response) { properties.fnEndProcessingMode(); properties.fnShowError(response.responseText, "add"); properties.fnOnAdded("failure"); } }); } } } event.stopPropagation(); event.preventDefault(); } function _fnOnNewRowPosted(data) { ///<summary>Callback function called BEFORE a new record is posted to the server</summary> ///TODO: Check this return true; } function fnOnRowAdded(data) { ///<summary> ///Function that is called when a new row is added, and Ajax response is returned from server /// This function takes data from the add form and adds them into the table. ///</summary> ///<param name="data" type="int">Id of the new row that is returned from the server</param> properties.fnEndProcessingMode(); if (properties.fnOnNewRowPosted(data)) { var oSettings = oTable.fnSettings(); if (!oSettings.oFeatures.bServerSide) { jQuery.data(oAddNewRowForm, 'DT_RowId', data); var values = fnTakeRowDataFromFormElements(oAddNewRowForm); var rtn; //Add values from the form into the table if (oSettings.aoColumns != null && isNaN(parseInt(oSettings.aoColumns[0].mDataProp))) { rtn = oTable.fnAddData(rowData); } else { rtn = oTable.fnAddData(values); } var oTRAdded = oTable.fnGetNodes(rtn); //add id returned by server page as an TR id attribute properties.fnSetRowID($(oTRAdded), data, true); //Apply editable plugin on the cells of the table fnApplyEditable(oTRAdded); $("tr.last-added-row", oTable).removeClass("last-added-row"); $(oTRAdded).addClass("last-added-row"); } /*else { oTable.fnDraw(false); }*/ //Close the dialog oAddNewRowForm.dialog('close'); $(oAddNewRowForm)[0].reset(); $(".error", $(oAddNewRowForm)).html(""); fnSetDisplayStart(); properties.fnOnAdded("success"); if (properties.bUseKeyTable) { var keys = oTable.keys; /* Unblock KeyTable, but only after this 'esc' key event has finished. Otherwise * it will 'esc' KeyTable as well */ setTimeout(function () { keys.block = false; }, 0); } } } function fnOnCancelRowAdding(event) { ///<summary> ///Event handler function that is executed when a user press cancel button in the add new row form ///This function clean the add form and error messages if some of them are shown ///</summary> ///<param name="event" type="int">DOM event that caused an error</param> //Clear the validation messages and reset form $(oAddNewRowForm).validate().resetForm(); // Clears the validation errors $(oAddNewRowForm)[0].reset(); $(".error", $(oAddNewRowForm)).html(""); $(".error", $(oAddNewRowForm)).hide(); // Hides the error element //Close the dialog oAddNewRowForm.dialog('close'); event.stopPropagation(); event.preventDefault(); } function fnDisableDeleteButton() { ///<summary> ///Function that disables delete button ///</summary> if (properties.bUseKeyTable) { return; } if (properties.oDeleteRowButtonOptions != null) { //oDeleteRowButton.disable(); oDeleteRowButton.button("option", "disabled", true); } else { oDeleteRowButton.attr("disabled", "true"); } } function fnEnableDeleteButton() { ///<summary> ///Function that enables delete button ///</summary> if (properties.oDeleteRowButtonOptions != null) { //oDeleteRowButton.enable(); oDeleteRowButton.button("option", "disabled", false); } else { oDeleteRowButton.removeAttr("disabled"); } } var nSelectedRow, nSelectedCell; var oKeyTablePosition; function _fnOnRowDeleteInline(e) { var sURL = $(this).attr("href"); if (sURL == null || sURL == "") sURL = properties.sDeleteURL; e.preventDefault(); e.stopPropagation(); iDisplayStart = fnGetDisplayStart(); nSelectedCell = ($(this).parents('td'))[0]; jSelectedRow = ($(this).parents('tr')); nSelectedRow = jSelectedRow[0]; jSelectedRow.addClass(properties.sSelectedRowClass); var id = fnGetCellID(nSelectedCell); if (properties.fnOnDeleting(jSelectedRow, id, fnDeleteRow)) { fnDeleteRow(id, sURL); } } function _fnOnRowDelete(event) { ///<summary> ///Event handler for the delete button ///</summary> ///<param name="event" type="Event">DOM event</param> event.preventDefault(); event.stopPropagation(); iDisplayStart = fnGetDisplayStart(); nSelectedRow = null; nSelectedCell = null; if (!properties.bUseKeyTable) { if ($('tr.' + properties.sSelectedRowClass + ' td', oTable).length == 0) { //oDeleteRowButton.attr("disabled", "true"); _fnDisableDeleteButton(); return; } nSelectedCell = $('tr.' + properties.sSelectedRowClass + ' td', oTable)[0]; } else { nSelectedCell = $('td.focus', oTable)[0]; } if (nSelectedCell == null) { fnDisableDeleteButton(); return; } if (properties.bUseKeyTable) { oKeyTablePosition = oTable.keys.fnGetCurrentPosition(); } var id = fnGetCellID(nSelectedCell); var jSelectedRow = $(nSelectedCell).parent("tr"); nSelectedRow = jSelectedRow[0]; if (properties.fnOnDeleting(jSelectedRow, id, fnDeleteRow)) { fnDeleteRow(id); } } function _fnOnDeleting(tr, id, fnDeleteRow) { ///<summary> ///The default function that is called before row is deleted ///Returning false will abort delete ///Function can be overriden via plugin properties in order to create custom delete functionality ///in that case call fnDeleteRow with parameter id, and return false to prevent double delete action ///</summary> ///<param name="tr" type="JQuery">JQuery wrapper around the TR tag that will be deleted</param> ///<param name="id" type="String">Id of the record that wil be deleted</param> ///<param name="fnDeleteRow" type="Function(id)">Function that will be called to delete a row. Default - fnDeleteRow(id)</param> return confirm("Are you sure that you want to delete this record?"); ; } function fnDeleteRow(id, sDeleteURL) { ///<summary> ///Function that deletes a row with an id, using the sDeleteURL server page ///</summary> ///<param name="id" type="int">Id of the row that will be deleted. Id value is placed in the attribute of the TR tag that will be deleted</param> ///<param name="sDeleteURL" type="String">Server URL where delete request will be posted</param> var sURL = sDeleteURL; if (sDeleteURL == null) sURL = properties.sDeleteURL; properties.fnStartProcessingMode(); var data = $.extend(properties.oDeleteParameters, { "id": id }); $.ajax({ 'url': sURL, 'type': properties.sDeleteHttpMethod, 'data': data, "success": fnOnRowDeleted, "dataType": properties.sDeleteDataType, "error": function (response) { properties.fnEndProcessingMode(); properties.fnShowError(response.responseText, "delete"); properties.fnOnDeleted("failure"); } }); } function fnOnRowDeleted(response) { ///<summary> ///Called after the record is deleted on the server (in the ajax success callback) ///</summary> ///<param name="response" type="String">Response text eturned from the server-side page</param> properties.fnEndProcessingMode(); var oTRSelected = nSelectedRow; /* if (!properties.bUseKeyTable) { oTRSelected = $('tr.' + properties.sSelectedRowClass, oTable)[0]; } else { oTRSelected = $("td.focus", oTable)[0].parents("tr")[0]; } */ if (response == properties.sSuccessResponse || response == "") { oTable.fnDeleteRow(oTRSelected); fnDisableDeleteButton(); fnSetDisplayStart(); if (properties.bUseKeyTable) { oTable.keys.fnSetPosition( oKeyTablePosition[0], oKeyTablePosition[1] ); } properties.fnOnDeleted("success"); } else { properties.fnShowError(response, "delete"); properties.fnOnDeleted("failure"); } } /* Function called after delete action * @param result string * "success" if row is actually deleted * "failure" if delete failed * @return void */ function _fnOnDeleted(result) { } function _fnOnEditing(input) { return true; } function _fnOnEdited(result, sOldValue, sNewValue, iRowIndex, iColumnIndex, iRealColumnIndex) { } function fnOnAdding() { return true; } function _fnOnAdded(result) { } var oSettings; function fnGetDisplayStart() { return oSettings._iDisplayStart; } function fnSetDisplayStart() { ///<summary> ///Set the pagination position(do nothing in the server-side mode) ///</summary> //To refresh table with preserver pagination on cell edit //if (oSettings.oFeatures.bServerSide === false) { oSettings._iDisplayStart = iDisplayStart; oSettings.oApi._fnCalculateEnd(oSettings); //draw the 'current' page oSettings.oApi._fnDraw(oSettings); //} } function _fnOnBeforeAction(sAction) { return true; } function _fnOnActionCompleted(sStatus) { } function fnGetActionSettings(sAction) { ///<summary>Returns settings object for the action</summary> ///<param name="sAction" type="String">The name of the action</param> if (properties.aoTableAction) properties.fnShowError("Configuration error - aoTableAction setting are not set", sAction); var i = 0; for (i = 0; i < properties.aoTableActions.length; i++) { if (properties.aoTableActions[i].sAction == sAction) return properties.aoTableActions[i]; } properties.fnShowError("Cannot find action configuration settings", sAction); } function fnPopulateFormWithRowCells(oForm, oTR) { ///<summary>Populates forms with row data</summary> ///<param name="oForm" type="DOM">Form used to enter data</param> ///<param name="oTR" type="DOM">Table Row that will populate data</param> var iRowID = oTable.fnGetPosition(oTR); var id = properties.fnGetRowID($(oTR)); $(oForm).validate().resetForm(); jQuery.data($(oForm)[0], 'DT_RowId', id); $("input.DT_RowId", $(oForm)).val(id); jQuery.data($(oForm)[0], 'ROWID', iRowID); $("input.ROWID", $(oForm)).val(iRowID); var oSettings = oTable.fnSettings(); var iColumnCount = oSettings.aoColumns.length; $("input:text[rel],input:radio[rel][checked],input:hidden[rel],select[rel],textarea[rel],input:checkbox[rel]", $(oForm)).each(function () { var rel = $(this).attr("rel"); if (rel >= iColumnCount) properties.fnShowError("In the form is placed input element with the name '" + $(this).attr("name") + "' with the 'rel' attribute that must be less than a column count - " + iColumnCount, "action"); else { var sCellValue = oTable.fnGetData(oTR)[rel]; if (this.nodeName.toLowerCase() == "select" || this.tagName.toLowerCase() == "select") { if (this.multiple == true) { var aoSelectedValue = new Array(); aoCellValues = sCellValue.split(","); for (i = 0; i <= this.options.length - 1; i++) { if (jQuery.inArray(this.options[i].text.toLowerCase().trim(), aoCellValues) != -1) { aoSelectedValue.push(this.options[i].value); } } $(this).val(aoSelectedValue); } else { for (i = 0; i <= this.options.length - 1; i++) { if (this.options[i].text.toLowerCase() == sCellValue.toLowerCase()) { $(this).val(this.options[i].value); } } } } else if (this.nodeName.toLowerCase() == "span" || this.tagName.toLowerCase() == "span") $(this).html(sCellValue); else { if (this.type == "checkbox") { if (sCellValue == "true") { $(this).attr("checked", true); } } else { if (this.type == "radio") { if (this.value == sCellValue) { this.checked = true; } } else { this.value = sCellValue; } } } //sCellValue = sCellValue.replace(properties.sIDToken, data); //values[rel] = sCellValue; //oTable.fnUpdate(sCellValue, iRowID, rel); } }); } //End function fnPopulateFormWithRowCells function fnTakeRowDataFromFormElements(oForm) { ///<summary>Populates row with form elements(This should be nly function that read fom elements from form)</summary> ///<param name="iRowID" type="DOM">DatabaseRowID</param> ///<param name="oForm" type="DOM">Form used to enter data</param> ///<returns>Object or array</returns> var iDT_RowId = jQuery.data(oForm, 'DT_RowId'); var iColumnCount = oSettings.aoColumns.length; var values = new Array(); var rowData = new Object(); $("input:text[rel],input:radio[rel][checked],input:hidden[rel],select[rel],textarea[rel],span.datafield[rel],input:checkbox[rel]", oForm).each(function () { var rel = $(this).attr("rel"); var sCellValue = ""; if (rel >= iColumnCount) properties.fnShowError("In the add form is placed input element with the name '" + $(this).attr("name") + "' with the 'rel' attribute that must be less than a column count - " + iColumnCount, "add"); else { if (this.nodeName.toLowerCase() == "select" || this.tagName.toLowerCase() == "select") { //sCellValue = $("option:selected", this).text(); sCellValue = $.map( $.makeArray($("option:selected", this)), function (n, i) { return $(n).text(); }).join(","); } else if (this.nodeName.toLowerCase() == "span" || this.tagName.toLowerCase() == "span") sCellValue = $(this).html(); else { if (this.type == "checkbox") { if (this.checked) sCellValue = (this.value != "on") ? this.value : "true"; else sCellValue = (this.value != "on") ? "" : "false"; } else sCellValue = this.value; } //Deprecated sCellValue = sCellValue.replace("DATAROWID", iDT_RowId); sCellValue = sCellValue.replace(properties.sIDToken, iDT_RowId); if (oSettings.aoColumns != null && oSettings.aoColumns[rel] != null && isNaN(parseInt(oSettings.aoColumns[0].mDataProp))) { rowData[oSettings.aoColumns[rel].mDataProp] = sCellValue; } else { values[rel] = sCellValue; } } }); if (oSettings.aoColumns != null && isNaN(parseInt(oSettings.aoColumns[0].mDataProp))) { return rowData; } else { return values; } } //End function fnPopulateRowWithFormElements function fnSendFormUpdateRequest(nActionForm) { ///<summary>Updates table row using form fields</summary> ///<param name="nActionForm" type="DOM">Form used to enter data</param> var jActionForm = $(nActionForm); var sAction = jActionForm.attr("id"); sAction = sAction.replace("form", ""); var sActionURL = jActionForm.attr("action"); if (properties.fnOnBeforeAction(sAction)) { if (jActionForm.valid()) { iDisplayStart = fnGetDisplayStart(); properties.fnStartProcessingMode(); if (properties.bUseFormsPlugin) { //Still in beta(development) var oAjaxSubmitOptions = { success: function (response, statusString, xhr) { properties.fnEndProcessingMode(); if (response.toLowerCase().indexOf("error") != -1 || statusString != "success") { properties.fnShowError(response, sAction); properties.fnOnActionCompleted("failure"); } else { fnUpdateRowOnSuccess(nActionForm); properties.fnOnActionCompleted("success"); } }, error: function (response) { properties.fnEndProcessingMode(); properties.fnShowError(response.responseText, sAction); properties.fnOnActionCompleted("failure"); } }; var oActionSettings = fnGetActionSettings(sAction); oAjaxSubmitOptions = $.extend({}, properties.oAjaxSubmitOptions, oAjaxSubmitOptions); $(oActionForm).ajaxSubmit(oAjaxSubmitOptions); } else { var params = jActionForm.serialize(); $.ajax({ 'url': sActionURL, 'data': params, 'type': properties.sAddHttpMethod, 'dataType': properties.sAddDataType, success: function (response) { properties.fnEndProcessingMode(); fnUpdateRowOnSuccess(nActionForm); properties.fnOnActionCompleted("success"); }, error: function (response) { properties.fnEndProcessingMode(); properties.fnShowError(response.responseText, sAction); properties.fnOnActionCompleted("failure"); } }); } } } } function fnUpdateRowOnSuccess(nActionForm) { ///<summary>Updates table row using form fields after the ajax success callback is executed</summary> ///<param name="nActionForm" type="DOM">Form used to enter data</param> var values = fnTakeRowDataFromFormElements(nActionForm); var iRowID = jQuery.data(nActionForm, 'ROWID'); var oSettings = oTable.fnSettings(); var iColumnCount = oSettings.aoColumns.length; for (var rel = 0; rel < iColumnCount; rel++) { if (oSettings.aoColumns != null && oSettings.aoColumns[rel] != null && isNaN(parseInt(oSettings.aoColumns[0].mDataProp))) { sCellValue = rowData[oSettings.aoColumns[rel].mDataProp]; } else { sCellValue = values[rel]; } if (sCellValue != undefined) oTable.fnUpdate(sCellValue, iRowID, rel); } fnSetDisplayStart(); $(nActionForm).dialog('close'); return; } oTable = this; var defaults = { sUpdateURL: "UpdateData", sAddURL: "AddData", sDeleteURL: "DeleteData", sAddNewRowFormId: "formAddNewRow", oAddNewRowFormOptions: { autoOpen: false, modal: true }, sAddNewRowButtonId: "btnAddNewRow", oAddNewRowButtonOptions: null, sAddNewRowOkButtonId: "btnAddNewRowOk", sAddNewRowCancelButtonId: "btnAddNewRowCancel", oAddNewRowOkButtonOptions: { label: "Ok" }, oAddNewRowCancelButtonOptions: { label: "Cancel" }, sDeleteRowButtonId: "btnDeleteRow", oDeleteRowButtonOptions: null, sSelectedRowClass: "row_selected", sReadOnlyCellClass: "read_only", sAddDeleteToolbarSelector: ".add_delete_toolbar", fnShowError: _fnShowError, fnStartProcessingMode: _fnStartProcessingMode, fnEndProcessingMode: _fnEndProcessingMode, aoColumns: null, fnOnDeleting: _fnOnDeleting, fnOnDeleted: _fnOnDeleted, fnOnAdding: fnOnAdding, fnOnNewRowPosted: _fnOnNewRowPosted, fnOnAdded: _fnOnAdded, fnOnEditing: _fnOnEditing, fnOnEdited: _fnOnEdited, sAddHttpMethod: 'POST', sAddDataType: "text", sDeleteHttpMethod: 'POST', sDeleteDataType: "text", fnGetRowID: _fnGetRowIDFromAttribute, fnSetRowID: _fnSetRowIDInAttribute, sEditorHeight: "100%", sEditorWidth: "100%", bDisableEditing: false, oEditableSettings: null, oDeleteParameters: {}, oUpdateParameters: {}, sIDToken: "DT_RowId", aoTableActions: null, fnOnBeforeAction: _fnOnBeforeAction, bUseFormsPlugin: false, fnOnActionCompleted: _fnOnActionCompleted, sSuccessResponse: "ok", sFailureResponsePrefix: "ERROR", oKeyTable: null //KEYTABLE }; properties = $.extend(defaults, options); oSettings = oTable.fnSettings(); properties.bUseKeyTable = (properties.oKeyTable != null); return this.each(function () { var sTableId = oTable.dataTableSettings[0].sTableId; //KEYTABLE if (properties.bUseKeyTable) { var keys = new KeyTable({ "table": document.getElementById(sTableId), "datatable": oTable }); oTable.keys = keys; /* Apply a return key event to each cell in the table */ keys.event.action(null, null, function (nCell) { if( $(nCell).hasClass(properties.sReadOnlyCellClass)) return; /* Block KeyTable from performing any events while jEditable is in edit mode */ keys.block = true; /* Dispatch click event to go into edit mode - Saf 4 needs a timeout... */ setTimeout(function () { $(nCell).dblclick(); }, 0); //properties.bDisableEditing = true; }); } //KEYTABLE if (oTable.fnSettings().sAjaxSource != null) { oTable.fnSettings().aoDrawCallback.push({ "fn": function () { //Apply jEditable plugin on the table cells fnApplyEditable(oTable.fnGetNodes()); $(oTable.fnGetNodes()).each(function () { var position = oTable.fnGetPosition(this); var id = oTable.fnGetData(position)[0]; properties.fnSetRowID($(this), id); } ); }, "sName": "fnApplyEditable" }); } else { //Apply jEditable plugin on the table cells fnApplyEditable(oTable.fnGetNodes()); } //Setup form to open in dialog oAddNewRowForm = $("#" + properties.sAddNewRowFormId); if (oAddNewRowForm.length != 0) { ///Check does the add new form has all nessecary fields var oSettings = oTable.fnSettings(); var iColumnCount = oSettings.aoColumns.length; for (i = 0; i < iColumnCount; i++) { if ($("[rel=" + i + "]", oAddNewRowForm).length == 0) properties.fnShowError("In the form that is used for adding new records cannot be found an input element with rel=" + i + " that will be bound to the value in the column " + i + ". See http://code.google.com/p/jquery-datatables-editable/wiki/AddingNewRecords#Add_new_record_form for more details", "init"); } if (properties.oAddNewRowFormOptions != null) { properties.oAddNewRowFormOptions.autoOpen = false; } else { properties.oAddNewRowFormOptions = { autoOpen: false }; } oAddNewRowForm.dialog(properties.oAddNewRowFormOptions); //Add button click handler on the "Add new row" button oAddNewRowButton = $("#" + properties.sAddNewRowButtonId); if (oAddNewRowButton.length != 0) { if(oAddNewRowButton.data("add-event-attached")!="true") { oAddNewRowButton.click(function () { oAddNewRowForm.dialog('open'); }); oAddNewRowButton.data("add-event-attached", "true"); } } else { if ($(properties.sAddDeleteToolbarSelector).length == 0) { throw "Cannot find a button with an id '" + properties.sAddNewRowButtonId + "', or placeholder with an id '" + properties.sAddDeleteToolbarSelector + "' that should be used for adding new row although form for adding new record is specified"; } else { oAddNewRowButton = null; //It will be auto-generated later } } //Prevent Submit handler if (oAddNewRowForm[0].nodeName.toLowerCase() == "form") { oAddNewRowForm.unbind('submit'); oAddNewRowForm.submit(function (event) { fnOnRowAdding(event); return false; }); } else { $("form", oAddNewRowForm[0]).unbind('submit'); $("form", oAddNewRowForm[0]).submit(function (event) { fnOnRowAdding(event); return false; }); } // array to add default buttons to var aAddNewRowFormButtons = []; oConfirmRowAddingButton = $("#" + properties.sAddNewRowOkButtonId, oAddNewRowForm); if (oConfirmRowAddingButton.length == 0) { //If someone forgotten to set the button text if (properties.oAddNewRowOkButtonOptions.text == null || properties.oAddNewRowOkButtonOptions.text == "") { properties.oAddNewRowOkButtonOptions.text = "Ok"; } properties.oAddNewRowOkButtonOptions.click = fnOnRowAdding; properties.oAddNewRowOkButtonOptions.id = properties.sAddNewRowOkButtonId; // push the add button onto the array aAddNewRowFormButtons.push(properties.oAddNewRowOkButtonOptions); } else { oConfirmRowAddingButton.click(fnOnRowAdding); } oCancelRowAddingButton = $("#" + properties.sAddNewRowCancelButtonId); if (oCancelRowAddingButton.length == 0) { //If someone forgotten to the button text if (properties.oAddNewRowCancelButtonOptions.text == null || properties.oAddNewRowCancelButtonOptions.text == "") { properties.oAddNewRowCancelButtonOptions.text = "Cancel"; } properties.oAddNewRowCancelButtonOptions.click = fnOnCancelRowAdding; properties.oAddNewRowCancelButtonOptions.id = properties.sAddNewRowCancelButtonId; // push the cancel button onto the array aAddNewRowFormButtons.push(properties.oAddNewRowCancelButtonOptions); } else { oCancelRowAddingButton.click(fnOnCancelRowAdding); } // if the array contains elements, add them to the dialog if (aAddNewRowFormButtons.length > 0) { oAddNewRowForm.dialog('option', 'buttons', aAddNewRowFormButtons); } //Issue: It cannot find it with this call: //oConfirmRowAddingButton = $("#" + properties.sAddNewRowOkButtonId, oAddNewRowForm); //oCancelRowAddingButton = $("#" + properties.sAddNewRowCancelButtonId, oAddNewRowForm); oConfirmRowAddingButton = $("#" + properties.sAddNewRowOkButtonId); oCancelRowAddingButton = $("#" + properties.sAddNewRowCancelButtonId); if (properties.oAddNewRowFormValidation != null) { oAddNewRowForm.validate(properties.oAddNewRowFormValidation); } } else { oAddNewRowForm = null; } //Set the click handler on the "Delete selected row" button oDeleteRowButton = $('#' + properties.sDeleteRowButtonId); if (oDeleteRowButton.length != 0) { if(oDeleteRowButton.data("delete-event-attached")!="true") { oDeleteRowButton.click(_fnOnRowDelete); oDeleteRowButton.data("delete-event-attached", "true"); } } else { oDeleteRowButton = null; } //If an add and delete buttons does not exists but Add-delete toolbar is specificed //Autogenerate these buttons oAddDeleteToolbar = $(properties.sAddDeleteToolbarSelector); if (oAddDeleteToolbar.length != 0) { if (oAddNewRowButton == null && properties.sAddNewRowButtonId != "" && oAddNewRowForm != null) { oAddDeleteToolbar.append("<button id='" + properties.sAddNewRowButtonId + "' class='add_row'>Add</button>"); oAddNewRowButton = $("#" + properties.sAddNewRowButtonId); oAddNewRowButton.click(function () { oAddNewRowForm.dialog('open'); }); } if (oDeleteRowButton == null && properties.sDeleteRowButtonId != "") { oAddDeleteToolbar.append("<button id='" + properties.sDeleteRowButtonId + "' class='delete_row'>Delete</button>"); oDeleteRowButton = $("#" + properties.sDeleteRowButtonId); oDeleteRowButton.click(_fnOnRowDelete); } } //If delete button exists disable it until some row is selected if (oDeleteRowButton != null) { if (properties.oDeleteRowButtonOptions != null) { oDeleteRowButton.button(properties.oDeleteRowButtonOptions); } fnDisableDeleteButton(); } //If add button exists convert it to the JQuery-ui button if (oAddNewRowButton != null) { if (properties.oAddNewRowButtonOptions != null) { oAddNewRowButton.button(properties.oAddNewRowButtonOptions); } } //If form ok button exists convert it to the JQuery-ui button if (oConfirmRowAddingButton != null) { if (properties.oAddNewRowOkButtonOptions != null) { oConfirmRowAddingButton.button(properties.oAddNewRowOkButtonOptions); } } //If form cancel button exists convert it to the JQuery-ui button if (oCancelRowAddingButton != null) { if (properties.oAddNewRowCancelButtonOptions != null) { oCancelRowAddingButton.button(properties.oAddNewRowCancelButtonOptions); } } //Add handler to the inline delete buttons $(".table-action-deletelink", oTable).live("click", _fnOnRowDeleteInline); if (!properties.bUseKeyTable) { //Set selected class on row that is clicked //Enable delete button if row is selected, disable delete button if selected class is removed $("tbody", oTable).click(function (event) { if ($(event.target.parentNode).hasClass(properties.sSelectedRowClass)) { $(event.target.parentNode).removeClass(properties.sSelectedRowClass); if (oDeleteRowButton != null) { fnDisableDeleteButton(); } } else { $(oTable.fnSettings().aoData).each(function () { $(this.nTr).removeClass(properties.sSelectedRowClass); }); $(event.target.parentNode).addClass(properties.sSelectedRowClass); if (oDeleteRowButton != null) { fnEnableDeleteButton(); } } }); } else { oTable.keys.event.focus(null, null, function (nNode, x, y) { }); } if (properties.aoTableActions != null) { for (var i = 0; i < properties.aoTableActions.length; i++) { var oTableAction = $.extend({ sType: "edit" }, properties.aoTableActions[i]); var sAction = oTableAction.sAction; var sActionFormId = oTableAction.sActionFormId; var oActionForm = $("#form" + sAction); if (oActionForm.length != 0) { var oFormOptions = { autoOpen: false, modal: true }; oFormOptions = $.extend({}, oTableAction.oFormOptions, oFormOptions); oActionForm.dialog(oFormOptions); oActionForm.data("action-options", oTableAction); var oActionFormLink = $(".table-action-" + sAction); if (oActionFormLink.length != 0) { oActionFormLink.live("click", function () { var sClass = this.className; var classList = sClass.split(/\s+/); var sActionFormId = ""; var sAction = ""; for (i = 0; i < classList.length; i++) { if (classList[i].indexOf("table-action-") > -1) { sAction = classList[i].replace("table-action-", ""); sActionFormId = "#form" + sAction; } } if (sActionFormId == "") { properties.fnShowError("Cannot find a form with an id " + sActionFormId + " that should be associated to the action - " + sAction, sAction) } var oTableAction = $(sActionFormId).data("action-options"); if (oTableAction.sType == "edit") { //var oTD = ($(this).parents('td'))[0]; var oTR = ($(this).parents('tr'))[0]; fnPopulateFormWithRowCells(oActionForm, oTR); } $(oActionForm).dialog('open'); }); } oActionForm.submit(function (event) { fnSendFormUpdateRequest(this); return false; }); var aActionFormButtons = new Array(); //var oActionSubmitButton = $("#form" + sAction + "Ok", oActionForm); //aActionFormButtons.push(oActionSubmitButton); var oActionFormCancel = $("#form" + sAction + "Cancel", oActionForm); if (oActionFormCancel.length != 0) { aActionFormButtons.push(oActionFormCancel); oActionFormCancel.click(function () { var oActionForm = $(this).parents("form")[0]; //Clear the validation messages and reset form $(oActionForm).validate().resetForm(); // Clears the validation errors $(oActionForm)[0].reset(); $(".error", $(oActionForm)).html(""); $(".error", $(oActionForm)).hide(); // Hides the error element $(oActionForm).dialog('close'); }); } //Convert all action form buttons to the JQuery UI buttons $("button", oActionForm).button(); /* if (aActionFormButtons.length > 0) { oActionForm.dialog('option', 'buttons', aActionFormButtons); } */ } } // end for (var i = 0; i < properties.aoTableActions.length; i++) } //end if (properties.aoTableActions != null) }); }; })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-editable.js
jquery-dataTables-editable.js
(function(a){a.easyPieChart=function(d,l){var f,g,i,j,c,k,e,b,h=this;this.el=d;this.$el=a(d);this.$el.data("easyPieChart",this);this.init=function(){var n,m;h.options=a.extend({},a.easyPieChart.defaultOptions,l);n=parseInt(h.$el.data("percent"),10);h.percentage=0;h.canvas=a("<canvas width='"+h.options.size+"' height='"+h.options.size+"'></canvas>").get(0);h.$el.append(h.canvas);if(typeof G_vmlCanvasManager!=="undefined"&&G_vmlCanvasManager!==null){G_vmlCanvasManager.initElement(h.canvas)}h.ctx=h.canvas.getContext("2d");if(window.devicePixelRatio>1){m=window.devicePixelRatio;a(h.canvas).css({width:h.options.size,height:h.options.size});h.canvas.width*=m;h.canvas.height*=m;h.ctx.scale(m,m)}h.ctx.translate(h.options.size/2,h.options.size/2);h.ctx.rotate(h.options.rotate*Math.PI/180);h.$el.addClass("easyPieChart");h.$el.css({width:h.options.size,height:h.options.size,lineHeight:""+h.options.size+"px"});h.update(n);return h};this.update=function(m){m=parseFloat(m)||0;if(h.options.animate===false){i(m)}else{g(h.percentage,m)}return h};e=function(){var n,o,m;h.ctx.fillStyle=h.options.scaleColor;h.ctx.lineWidth=1;m=[];for(n=o=0;o<=24;n=++o){m.push(f(n))}return m};f=function(m){var n;n=m%6===0?0:h.options.size*0.017;h.ctx.save();h.ctx.rotate(m*Math.PI/12);h.ctx.fillRect(h.options.size/2-n,0,-h.options.size*0.05+n,1);h.ctx.restore()};b=function(){var m;m=h.options.size/2-h.options.lineWidth/2;if(h.options.scaleColor!==false){m-=h.options.size*0.08}h.ctx.beginPath();h.ctx.arc(0,0,m,0,Math.PI*2,true);h.ctx.closePath();h.ctx.strokeStyle=h.options.trackColor;h.ctx.lineWidth=h.options.lineWidth;h.ctx.stroke()};k=function(){if(h.options.scaleColor!==false){e()}if(h.options.trackColor!==false){b()}};i=function(m){var n;k();h.ctx.strokeStyle=a.isFunction(h.options.barColor)?h.options.barColor(m):h.options.barColor;h.ctx.lineCap=h.options.lineCap;h.ctx.lineWidth=h.options.lineWidth;n=h.options.size/2-h.options.lineWidth/2;if(h.options.scaleColor!==false){n-=h.options.size*0.08}h.ctx.save();h.ctx.rotate(-Math.PI/2);h.ctx.beginPath();h.ctx.arc(0,0,n,0,Math.PI*2*m/100,false);h.ctx.stroke();h.ctx.restore()};c=(function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(m){return window.setTimeout(m,1000/60)}})();g=function(p,o){var n,m;h.options.onStart.call(h);h.percentage=o;m=Date.now();n=function(){var q,r;r=Date.now()-m;if(r<h.options.animate){c(n)}h.ctx.clearRect(-h.options.size/2,-h.options.size/2,h.options.size,h.options.size);k.call(h);q=[j(r,p,o-p,h.options.animate)];h.options.onStep.call(h,q);i.call(h,q);if(r>=h.options.animate){return h.options.onStop.call(h)}};c(n)};j=function(o,n,r,p){var m,q;m=function(s){return Math.pow(s,2)};q=function(s){if(s<1){return m(s)}else{return 2-m((s/2)*-2+2)}};o/=p/2;return r/2*q(o)+n};return this.init()};a.easyPieChart.defaultOptions={barColor:"#ef1e25",trackColor:"#f2f2f2",scaleColor:"#dfe0e0",lineCap:"round",rotate:0,size:110,lineWidth:3,animate:false,onStart:a.noop,onStop:a.noop,onStep:a.noop};a.fn.easyPieChart=function(b){return a.each(this,function(d,e){var c,f;c=a(e);if(!c.data("easyPieChart")){f=a.extend({},b,c.data());return c.data("easyPieChart",new a.easyPieChart(e,f))}})};return void 0})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-easypiechart.min.js
jquery-easypiechart.min.js
* @summary FixedHeader * @description Fix a table's header or footer, so it is always visible while * Scrolling * @version 2.1.0 * @file dataTables.fixedHeader.js * @author SpryMedia Ltd (www.sprymedia.co.uk) * @contact www.sprymedia.co.uk/contact * @copyright Copyright 2009-2014 SpryMedia Ltd. * * This source file is free software, available under the following license: * MIT license - http://datatables.net/license/mit * * 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 */ /* Global scope for FixedColumns for backwards compatibility - will be removed * in future. Not documented in 1.1.x. */ /* Global scope for FixedColumns */ var FixedHeader; (function (window, document, undefined) { var factory = function ($, DataTable) { "use strict"; /* * Function: FixedHeader * Purpose: Provide 'fixed' header, footer and columns on an HTML table * Returns: object:FixedHeader - must be called with 'new' * Inputs: mixed:mTable - target table * 1. DataTable object - when using FixedHeader with DataTables, or * 2. HTML table node - when using FixedHeader without DataTables * object:oInit - initialisation settings, with the following properties (each optional) * bool:top - fix the header (default true) * bool:bottom - fix the footer (default false) * int:left - fix the left column(s) (default 0) * int:right - fix the right column(s) (default 0) * int:zTop - fixed header zIndex * int:zBottom - fixed footer zIndex * int:zLeft - fixed left zIndex * int:zRight - fixed right zIndex */ FixedHeader = function (mTable, oInit) { /* Sanity check - you just know it will happen */ if (!this instanceof FixedHeader) { alert("FixedHeader warning: FixedHeader must be initialised with the 'new' keyword."); return; } var that = this; var oSettings = { "aoCache": [], "oSides": { "top": true, "bottom": false, "left": 0, "right": 0 }, "oZIndexes": { "top": 104, "bottom": 103, "left": 102, "right": 101 }, "oCloneOnDraw": { "top": false, "bottom": false, "left": true, "right": true }, "oMes": { "iTableWidth": 0, "iTableHeight": 0, "iTableLeft": 0, "iTableRight": 0, /* note this is left+width, not actually "right" */ "iTableTop": 0, "iTableBottom": 0 /* note this is top+height, not actually "bottom" */ }, "oOffset": { "top": 0 }, "nTable": null, "bFooter": false, "bInitComplete": false }; /* * Function: fnGetSettings * Purpose: Get the settings for this object * Returns: object: - settings object * Inputs: - */ this.fnGetSettings = function () { return oSettings; }; /* * Function: fnUpdate * Purpose: Update the positioning and copies of the fixed elements * Returns: - * Inputs: - */ this.fnUpdate = function () { this._fnUpdateClones(); this._fnUpdatePositions(); }; /* * Function: fnPosition * Purpose: Update the positioning of the fixed elements * Returns: - * Inputs: - */ this.fnPosition = function () { this._fnUpdatePositions(); }; var dt = $.fn.dataTable.Api ? new $.fn.dataTable.Api(mTable).settings()[0] : mTable.fnSettings(); dt._oPluginFixedHeader = this; /* Let's do it */ this.fnInit(dt, oInit); }; /* * Variable: FixedHeader * Purpose: Prototype for FixedHeader * Scope: global */ FixedHeader.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation */ /* * Function: fnInit * Purpose: The "constructor" * Returns: - * Inputs: {as FixedHeader function} */ fnInit: function (oDtSettings, oInit) { var s = this.fnGetSettings(); var that = this; /* Record the user definable settings */ this.fnInitSettings(s, oInit); if (oDtSettings.oScroll.sX !== "" || oDtSettings.oScroll.sY !== "") { alert("FixedHeader 2 is not supported with DataTables' scrolling mode at this time"); return; } s.nTable = oDtSettings.nTable; oDtSettings.aoDrawCallback.unshift({ "fn": function () { FixedHeader.fnMeasure(); that._fnUpdateClones.call(that); that._fnUpdatePositions.call(that); }, "sName": "FixedHeader" }); s.bFooter = ($('>tfoot', s.nTable).length > 0) ? true : false; /* Add the 'sides' that are fixed */ if (s.oSides.top) { s.aoCache.push(that._fnCloneTable("fixedHeader", "FixedHeader_Header", that._fnCloneThead)); } if (s.oSides.bottom) { s.aoCache.push(that._fnCloneTable("fixedFooter", "FixedHeader_Footer", that._fnCloneTfoot)); } if (s.oSides.left) { s.aoCache.push(that._fnCloneTable("fixedLeft", "FixedHeader_Left", that._fnCloneTLeft, s.oSides.left)); } if (s.oSides.right) { s.aoCache.push(that._fnCloneTable("fixedRight", "FixedHeader_Right", that._fnCloneTRight, s.oSides.right)); } /* Event listeners for window movement */ FixedHeader.afnScroll.push(function () { that._fnUpdatePositions.call(that); }); $(window).resize(function () { FixedHeader.fnMeasure(); that._fnUpdateClones.call(that); that._fnUpdatePositions.call(that); }); $(s.nTable) .on('column-reorder', function () { FixedHeader.fnMeasure(); that._fnUpdateClones(true); that._fnUpdatePositions(); }) .on('column-visibility', function () { FixedHeader.fnMeasure(); that._fnUpdateClones(true); that._fnUpdatePositions(); }); /* Get things right to start with */ FixedHeader.fnMeasure(); that._fnUpdateClones(); that._fnUpdatePositions(); s.bInitComplete = true; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Support functions */ /* * Function: fnInitSettings * Purpose: Take the user's settings and copy them to our local store * Returns: - * Inputs: object:s - the local settings object * object:oInit - the user's settings object */ fnInitSettings: function (s, oInit) { if (oInit !== undefined) { if (oInit.top !== undefined) { s.oSides.top = oInit.top; } if (oInit.bottom !== undefined) { s.oSides.bottom = oInit.bottom; } if (typeof oInit.left == 'boolean') { s.oSides.left = oInit.left ? 1 : 0; } else if (oInit.left !== undefined) { s.oSides.left = oInit.left; } if (typeof oInit.right == 'boolean') { s.oSides.right = oInit.right ? 1 : 0; } else if (oInit.right !== undefined) { s.oSides.right = oInit.right; } if (oInit.zTop !== undefined) { s.oZIndexes.top = oInit.zTop; } if (oInit.zBottom !== undefined) { s.oZIndexes.bottom = oInit.zBottom; } if (oInit.zLeft !== undefined) { s.oZIndexes.left = oInit.zLeft; } if (oInit.zRight !== undefined) { s.oZIndexes.right = oInit.zRight; } if (oInit.offsetTop !== undefined) { s.oOffset.top = oInit.offsetTop; } if (oInit.alwaysCloneTop !== undefined) { s.oCloneOnDraw.top = oInit.alwaysCloneTop; } if (oInit.alwaysCloneBottom !== undefined) { s.oCloneOnDraw.bottom = oInit.alwaysCloneBottom; } if (oInit.alwaysCloneLeft !== undefined) { s.oCloneOnDraw.left = oInit.alwaysCloneLeft; } if (oInit.alwaysCloneRight !== undefined) { s.oCloneOnDraw.right = oInit.alwaysCloneRight; } } }, /* * Function: _fnCloneTable * Purpose: Clone the table node and do basic initialisation * Returns: - * Inputs: - */ _fnCloneTable: function (sType, sClass, fnClone, iCells) { var s = this.fnGetSettings(); var nCTable; /* We know that the table _MUST_ has a DIV wrapped around it, because this is simply how * DataTables works. Therefore, we can set this to be relatively position (if it is not * alreadu absolute, and use this as the base point for the cloned header */ if ($(s.nTable.parentNode).css('position') != "absolute") { s.nTable.parentNode.style.position = "relative"; } /* Just a shallow clone will do - we only want the table node */ nCTable = s.nTable.cloneNode(false); nCTable.removeAttribute('id'); var nDiv = document.createElement('div'); nDiv.style.position = "absolute"; nDiv.style.top = "0px"; nDiv.style.left = "0px"; nDiv.className += " FixedHeader_Cloned " + sType + " " + sClass; /* Set the zIndexes */ if (sType == "fixedHeader") { nDiv.style.zIndex = s.oZIndexes.top; } if (sType == "fixedFooter") { nDiv.style.zIndex = s.oZIndexes.bottom; } if (sType == "fixedLeft") { nDiv.style.zIndex = s.oZIndexes.left; } else if (sType == "fixedRight") { nDiv.style.zIndex = s.oZIndexes.right; } /* remove margins since we are going to position it absolutely */ nCTable.style.margin = "0"; /* Insert the newly cloned table into the DOM, on top of the "real" header */ nDiv.appendChild(nCTable); document.body.appendChild(nDiv); return { "nNode": nCTable, "nWrapper": nDiv, "sType": sType, "sPosition": "", "sTop": "", "sLeft": "", "fnClone": fnClone, "iCells": iCells }; }, /* * Function: _fnMeasure * Purpose: Get the current positioning of the table in the DOM * Returns: - * Inputs: - */ _fnMeasure: function () { var s = this.fnGetSettings(), m = s.oMes, jqTable = $(s.nTable), oOffset = jqTable.offset(), iParentScrollTop = this._fnSumScroll(s.nTable.parentNode, 'scrollTop'), iParentScrollLeft = this._fnSumScroll(s.nTable.parentNode, 'scrollLeft'); m.iTableWidth = jqTable.outerWidth(); m.iTableHeight = jqTable.outerHeight(); m.iTableLeft = oOffset.left + s.nTable.parentNode.scrollLeft; m.iTableTop = oOffset.top + iParentScrollTop; m.iTableRight = m.iTableLeft + m.iTableWidth; m.iTableRight = FixedHeader.oDoc.iWidth - m.iTableLeft - m.iTableWidth; m.iTableBottom = FixedHeader.oDoc.iHeight - m.iTableTop - m.iTableHeight; }, /* * Function: _fnSumScroll * Purpose: Sum node parameters all the way to the top * Returns: int: sum * Inputs: node:n - node to consider * string:side - scrollTop or scrollLeft */ _fnSumScroll: function (n, side) { var i = n[side]; while (n = n.parentNode) { if (n.nodeName == 'HTML' || n.nodeName == 'BODY') { break; } i = n[side]; } return i; }, /* * Function: _fnUpdatePositions * Purpose: Loop over the fixed elements for this table and update their positions * Returns: - * Inputs: - */ _fnUpdatePositions: function () { var s = this.fnGetSettings(); this._fnMeasure(); for (var i = 0, iLen = s.aoCache.length; i < iLen; i++) { if (s.aoCache[i].sType == "fixedHeader") { this._fnScrollFixedHeader(s.aoCache[i]); } else if (s.aoCache[i].sType == "fixedFooter") { this._fnScrollFixedFooter(s.aoCache[i]); } else if (s.aoCache[i].sType == "fixedLeft") { this._fnScrollHorizontalLeft(s.aoCache[i]); } else { this._fnScrollHorizontalRight(s.aoCache[i]); } } }, /* * Function: _fnUpdateClones * Purpose: Loop over the fixed elements for this table and call their cloning functions * Returns: - * Inputs: - */ _fnUpdateClones: function (full) { var s = this.fnGetSettings(); if (full) { // This is a little bit of a hack to force a full clone draw. When // `full` is set to true, we want to reclone the source elements, // regardless of the clone-on-draw settings s.bInitComplete = false; } for (var i = 0, iLen = s.aoCache.length; i < iLen; i++) { s.aoCache[i].fnClone.call(this, s.aoCache[i]); } if (full) { s.bInitComplete = true; } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Scrolling functions */ /* * Function: _fnScrollHorizontalLeft * Purpose: Update the positioning of the scrolling elements * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnScrollHorizontalRight: function (oCache) { var s = this.fnGetSettings(), oMes = s.oMes, oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc, nTable = oCache.nWrapper, iFixedWidth = $(nTable).outerWidth(); if (oWin.iScrollRight < oMes.iTableRight) { /* Fully right aligned */ this._fnUpdateCache(oCache, 'sPosition', 'absolute', 'position', nTable.style); this._fnUpdateCache(oCache, 'sTop', oMes.iTableTop + "px", 'top', nTable.style); this._fnUpdateCache(oCache, 'sLeft', (oMes.iTableLeft + oMes.iTableWidth - iFixedWidth) + "px", 'left', nTable.style); } else if (oMes.iTableLeft < oDoc.iWidth - oWin.iScrollRight - iFixedWidth) { /* Middle */ this._fnUpdateCache(oCache, 'sPosition', 'fixed', 'position', nTable.style); this._fnUpdateCache(oCache, 'sTop', (oMes.iTableTop - oWin.iScrollTop) + "px", 'top', nTable.style); this._fnUpdateCache(oCache, 'sLeft', (oWin.iWidth - iFixedWidth) + "px", 'left', nTable.style); } else { /* Fully left aligned */ this._fnUpdateCache(oCache, 'sPosition', 'absolute', 'position', nTable.style); this._fnUpdateCache(oCache, 'sTop', oMes.iTableTop + "px", 'top', nTable.style); this._fnUpdateCache(oCache, 'sLeft', oMes.iTableLeft + "px", 'left', nTable.style); } }, /* * Function: _fnScrollHorizontalLeft * Purpose: Update the positioning of the scrolling elements * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnScrollHorizontalLeft: function (oCache) { var s = this.fnGetSettings(), oMes = s.oMes, oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc, nTable = oCache.nWrapper, iCellWidth = $(nTable).outerWidth(); if (oWin.iScrollLeft < oMes.iTableLeft) { /* Fully left align */ this._fnUpdateCache(oCache, 'sPosition', 'absolute', 'position', nTable.style); this._fnUpdateCache(oCache, 'sTop', oMes.iTableTop + "px", 'top', nTable.style); this._fnUpdateCache(oCache, 'sLeft', oMes.iTableLeft + "px", 'left', nTable.style); } else if (oWin.iScrollLeft < oMes.iTableLeft + oMes.iTableWidth - iCellWidth) { this._fnUpdateCache(oCache, 'sPosition', 'fixed', 'position', nTable.style); this._fnUpdateCache(oCache, 'sTop', (oMes.iTableTop - oWin.iScrollTop) + "px", 'top', nTable.style); this._fnUpdateCache(oCache, 'sLeft', "0px", 'left', nTable.style); } else { /* Fully right align */ this._fnUpdateCache(oCache, 'sPosition', 'absolute', 'position', nTable.style); this._fnUpdateCache(oCache, 'sTop', oMes.iTableTop + "px", 'top', nTable.style); this._fnUpdateCache(oCache, 'sLeft', (oMes.iTableLeft + oMes.iTableWidth - iCellWidth) + "px", 'left', nTable.style); } }, /* * Function: _fnScrollFixedFooter * Purpose: Update the positioning of the scrolling elements * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnScrollFixedFooter: function (oCache) { var s = this.fnGetSettings(), oMes = s.oMes, oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc, nTable = oCache.nWrapper, iTheadHeight = $("thead", s.nTable).outerHeight(), iCellHeight = $(nTable).outerHeight(); if (oWin.iScrollBottom < oMes.iTableBottom) { /* Below */ this._fnUpdateCache(oCache, 'sPosition', 'absolute', 'position', nTable.style); this._fnUpdateCache(oCache, 'sTop', (oMes.iTableTop + oMes.iTableHeight - iCellHeight) + "px", 'top', nTable.style); this._fnUpdateCache(oCache, 'sLeft', oMes.iTableLeft + "px", 'left', nTable.style); } else if (oWin.iScrollBottom < oMes.iTableBottom + oMes.iTableHeight - iCellHeight - iTheadHeight) { this._fnUpdateCache(oCache, 'sPosition', 'fixed', 'position', nTable.style); this._fnUpdateCache(oCache, 'sTop', (oWin.iHeight - iCellHeight) + "px", 'top', nTable.style); this._fnUpdateCache(oCache, 'sLeft', (oMes.iTableLeft - oWin.iScrollLeft) + "px", 'left', nTable.style); } else { /* Above */ this._fnUpdateCache(oCache, 'sPosition', 'absolute', 'position', nTable.style); this._fnUpdateCache(oCache, 'sTop', (oMes.iTableTop + iCellHeight) + "px", 'top', nTable.style); this._fnUpdateCache(oCache, 'sLeft', oMes.iTableLeft + "px", 'left', nTable.style); } }, /* * Function: _fnScrollFixedHeader * Purpose: Update the positioning of the scrolling elements * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnScrollFixedHeader: function (oCache) { var s = this.fnGetSettings(), oMes = s.oMes, oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc, nTable = oCache.nWrapper, iTbodyHeight = 0, anTbodies = s.nTable.getElementsByTagName('tbody'); for (var i = 0; i < anTbodies.length; ++i) { iTbodyHeight += anTbodies[i].offsetHeight; } if (oMes.iTableTop > oWin.iScrollTop + s.oOffset.top) { /* Above the table */ this._fnUpdateCache(oCache, 'sPosition', "absolute", 'position', nTable.style); this._fnUpdateCache(oCache, 'sTop', oMes.iTableTop + "px", 'top', nTable.style); this._fnUpdateCache(oCache, 'sLeft', oMes.iTableLeft + "px", 'left', nTable.style); } else if (oWin.iScrollTop + s.oOffset.top > oMes.iTableTop + iTbodyHeight) { /* At the bottom of the table */ this._fnUpdateCache(oCache, 'sPosition', "absolute", 'position', nTable.style); this._fnUpdateCache(oCache, 'sTop', (oMes.iTableTop + iTbodyHeight) + "px", 'top', nTable.style); this._fnUpdateCache(oCache, 'sLeft', oMes.iTableLeft + "px", 'left', nTable.style); } else { /* In the middle of the table */ this._fnUpdateCache(oCache, 'sPosition', 'fixed', 'position', nTable.style); this._fnUpdateCache(oCache, 'sTop', s.oOffset.top + "px", 'top', nTable.style); this._fnUpdateCache(oCache, 'sLeft', (oMes.iTableLeft - oWin.iScrollLeft) + "px", 'left', nTable.style); } }, /* * Function: _fnUpdateCache * Purpose: Check the cache and update cache and value if needed * Returns: - * Inputs: object:oCache - local cache object * string:sCache - cache property * string:sSet - value to set * string:sProperty - object property to set * object:oObj - object to update */ _fnUpdateCache: function (oCache, sCache, sSet, sProperty, oObj) { if (oCache[sCache] != sSet) { oObj[sProperty] = sSet; oCache[sCache] = sSet; } }, /** * Copy the classes of all child nodes from one element to another. This implies * that the two have identical structure - no error checking is performed to that * fact. * @param {element} source Node to copy classes from * @param {element} dest Node to copy classes too */ _fnClassUpdate: function (source, dest) { var that = this; if (source.nodeName.toUpperCase() === "TR" || source.nodeName.toUpperCase() === "TH" || source.nodeName.toUpperCase() === "TD" || source.nodeName.toUpperCase() === "SPAN") { dest.className = source.className; } $(source).children().each(function (i) { that._fnClassUpdate($(source).children()[i], $(dest).children()[i]); }); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cloning functions */ /* * Function: _fnCloneThead * Purpose: Clone the thead element * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnCloneThead: function (oCache) { var s = this.fnGetSettings(); var nTable = oCache.nNode; if (s.bInitComplete && !s.oCloneOnDraw.top) { this._fnClassUpdate($('thead', s.nTable)[0], $('thead', nTable)[0]); return; } /* Set the wrapper width to match that of the cloned table */ var iDtWidth = $(s.nTable).outerWidth(); oCache.nWrapper.style.width = iDtWidth + "px"; nTable.style.width = iDtWidth + "px"; /* Remove any children the cloned table has */ while (nTable.childNodes.length > 0) { $('thead th', nTable).unbind('click'); nTable.removeChild(nTable.childNodes[0]); } /* Clone the DataTables header */ var nThead = $('thead', s.nTable).clone(true)[0]; nTable.appendChild(nThead); /* Copy the widths across - apparently a clone isn't good enough for this */ var a = []; var b = []; $("thead>tr th", s.nTable).each(function (i) { a.push($(this).width()); }); $("thead>tr td", s.nTable).each(function (i) { b.push($(this).width()); }); $("thead>tr th", s.nTable).each(function (i) { $("thead>tr th:eq(" + i + ")", nTable).width(a[i]); $(this).width(a[i]); }); $("thead>tr td", s.nTable).each(function (i) { $("thead>tr td:eq(" + i + ")", nTable).width(b[i]); $(this).width(b[i]); }); // Stop DataTables 1.9 from putting a focus ring on the headers when // clicked to sort $('th.sorting, th.sorting_desc, th.sorting_asc', nTable).bind('click', function () { this.blur(); }); }, /* * Function: _fnCloneTfoot * Purpose: Clone the tfoot element * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnCloneTfoot: function (oCache) { var s = this.fnGetSettings(); var nTable = oCache.nNode; /* Set the wrapper width to match that of the cloned table */ oCache.nWrapper.style.width = $(s.nTable).outerWidth() + "px"; /* Remove any children the cloned table has */ while (nTable.childNodes.length > 0) { nTable.removeChild(nTable.childNodes[0]); } /* Clone the DataTables footer */ var nTfoot = $('tfoot', s.nTable).clone(true)[0]; nTable.appendChild(nTfoot); /* Copy the widths across - apparently a clone isn't good enough for this */ $("tfoot:eq(0)>tr th", s.nTable).each(function (i) { $("tfoot:eq(0)>tr th:eq(" + i + ")", nTable).width($(this).width()); }); $("tfoot:eq(0)>tr td", s.nTable).each(function (i) { $("tfoot:eq(0)>tr td:eq(" + i + ")", nTable).width($(this).width()); }); }, /* * Function: _fnCloneTLeft * Purpose: Clone the left column(s) * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnCloneTLeft: function (oCache) { var s = this.fnGetSettings(); var nTable = oCache.nNode; var nBody = $('tbody', s.nTable)[0]; /* Remove any children the cloned table has */ while (nTable.childNodes.length > 0) { nTable.removeChild(nTable.childNodes[0]); } /* Is this the most efficient way to do this - it looks horrible... */ nTable.appendChild($("thead", s.nTable).clone(true)[0]); nTable.appendChild($("tbody", s.nTable).clone(true)[0]); if (s.bFooter) { nTable.appendChild($("tfoot", s.nTable).clone(true)[0]); } /* Remove unneeded cells */ var sSelector = 'gt(' + (oCache.iCells - 1) + ')'; $('thead tr', nTable).each(function (k) { $('th:' + sSelector, this).remove(); }); $('tfoot tr', nTable).each(function (k) { $('th:' + sSelector, this).remove(); }); $('tbody tr', nTable).each(function (k) { $('td:' + sSelector, this).remove(); }); this.fnEqualiseHeights('thead', nBody.parentNode, nTable); this.fnEqualiseHeights('tbody', nBody.parentNode, nTable); this.fnEqualiseHeights('tfoot', nBody.parentNode, nTable); var iWidth = 0; for (var i = 0; i < oCache.iCells; i++) { iWidth += $('thead tr th:eq(' + i + ')', s.nTable).outerWidth(); } nTable.style.width = iWidth + "px"; oCache.nWrapper.style.width = iWidth + "px"; }, /* * Function: _fnCloneTRight * Purpose: Clone the right most column(s) * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnCloneTRight: function (oCache) { var s = this.fnGetSettings(); var nBody = $('tbody', s.nTable)[0]; var nTable = oCache.nNode; var iCols = $('tbody tr:eq(0) td', s.nTable).length; /* Remove any children the cloned table has */ while (nTable.childNodes.length > 0) { nTable.removeChild(nTable.childNodes[0]); } /* Is this the most efficient way to do this - it looks horrible... */ nTable.appendChild($("thead", s.nTable).clone(true)[0]); nTable.appendChild($("tbody", s.nTable).clone(true)[0]); if (s.bFooter) { nTable.appendChild($("tfoot", s.nTable).clone(true)[0]); } $('thead tr th:lt(' + (iCols - oCache.iCells) + ')', nTable).remove(); $('tfoot tr th:lt(' + (iCols - oCache.iCells) + ')', nTable).remove(); /* Remove unneeded cells */ $('tbody tr', nTable).each(function (k) { $('td:lt(' + (iCols - oCache.iCells) + ')', this).remove(); }); this.fnEqualiseHeights('thead', nBody.parentNode, nTable); this.fnEqualiseHeights('tbody', nBody.parentNode, nTable); this.fnEqualiseHeights('tfoot', nBody.parentNode, nTable); var iWidth = 0; for (var i = 0; i < oCache.iCells; i++) { iWidth += $('thead tr th:eq(' + (iCols - 1 - i) + ')', s.nTable).outerWidth(); } nTable.style.width = iWidth + "px"; oCache.nWrapper.style.width = iWidth + "px"; }, /** * Equalise the heights of the rows in a given table node in a cross browser way. Note that this * is more or less lifted as is from FixedColumns * @method fnEqualiseHeights * @returns void * @param {string} parent Node type - thead, tbody or tfoot * @param {element} original Original node to take the heights from * @param {element} clone Copy the heights to * @private */ "fnEqualiseHeights": function (parent, original, clone) { var that = this; var originals = $(parent + ' tr', original); var height; $(parent + ' tr', clone).each(function (k) { height = originals.eq(k).css('height'); // This is nasty :-(. IE has a sub-pixel error even when setting // the height below (the Firefox fix) which causes the fixed column // to go out of alignment. Need to add a pixel before the assignment // Can this be feature detected? Not sure how... if (navigator.appName == 'Microsoft Internet Explorer') { height = parseInt(height, 10) + 1; } $(this).css('height', height); // For Firefox to work, we need to also set the height of the // original row, to the value that we read from it! Otherwise there // is a sub-pixel rounding error originals.eq(k).css('height', height); }); } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static properties and methods * We use these for speed! This information is common to all instances of FixedHeader, so no * point if having them calculated and stored for each different instance. */ /* * Variable: oWin * Purpose: Store information about the window positioning * Scope: FixedHeader */ FixedHeader.oWin = { "iScrollTop": 0, "iScrollRight": 0, "iScrollBottom": 0, "iScrollLeft": 0, "iHeight": 0, "iWidth": 0 }; /* * Variable: oDoc * Purpose: Store information about the document size * Scope: FixedHeader */ FixedHeader.oDoc = { "iHeight": 0, "iWidth": 0 }; /* * Variable: afnScroll * Purpose: Array of functions that are to be used for the scrolling components * Scope: FixedHeader */ FixedHeader.afnScroll = []; /* * Function: fnMeasure * Purpose: Update the measurements for the window and document * Returns: - * Inputs: - */ FixedHeader.fnMeasure = function () { var jqWin = $(window), jqDoc = $(document), oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc; oDoc.iHeight = jqDoc.height(); oDoc.iWidth = jqDoc.width(); oWin.iHeight = jqWin.height(); oWin.iWidth = jqWin.width(); oWin.iScrollTop = jqWin.scrollTop(); oWin.iScrollLeft = jqWin.scrollLeft(); oWin.iScrollRight = oDoc.iWidth - oWin.iScrollLeft - oWin.iWidth; oWin.iScrollBottom = oDoc.iHeight - oWin.iScrollTop - oWin.iHeight; }; FixedHeader.version = "2.1.0"; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Global processing */ /* * Just one 'scroll' event handler in FixedHeader, which calls the required components. This is * done as an optimisation, to reduce calculation and proagation time */ $(window).scroll(function () { FixedHeader.fnMeasure(); for (var i = 0, iLen = FixedHeader.afnScroll.length; i < iLen; i++) { FixedHeader.afnScroll[i](); } }); $.fn.dataTable.FixedHeader = FixedHeader; $.fn.DataTable.FixedHeader = FixedHeader; return FixedHeader; }; // /factory factory(jQuery, jQuery.fn.dataTable); })(window, document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-fixedHeader.js
jquery-dataTables-fixedHeader.js
(function ($) { 'use strict'; // PROGRESSBAR CLASS DEFINITION // ============================ var Progressbar = function (element, options) { this.$element = $(element); this.options = $.extend({}, Progressbar.defaults, options); }; Progressbar.defaults = { transition_delay: 300, refresh_speed: 50, display_text: 'none', use_percentage: true, percent_format: function (percent) { return percent + '%'; }, amount_format: function (amount_part, amount_total) { return amount_part + ' / ' + amount_total; }, update: $.noop, done: $.noop, fail: $.noop }; Progressbar.prototype.transition = function () { var $this = this.$element; var $parent = $this.parent(); var $back_text = this.$back_text; var $front_text = this.$front_text; var options = this.options; var aria_valuetransitiongoal = $this.attr('aria-valuetransitiongoal'); var aria_valuemin = $this.attr('aria-valuemin') || 0; var aria_valuemax = $this.attr('aria-valuemax') || 100; var is_vertical = $parent.hasClass('vertical'); var update = options.update && typeof options.update === 'function' ? options.update : Progressbar.defaults.update; var done = options.done && typeof options.done === 'function' ? options.done : Progressbar.defaults.done; var fail = options.fail && typeof options.fail === 'function' ? options.fail : Progressbar.defaults.fail; if (!aria_valuetransitiongoal) { fail('aria-valuetransitiongoal not set'); return; } var percentage = Math.round(100 * (aria_valuetransitiongoal - aria_valuemin) / (aria_valuemax - aria_valuemin)); if (options.display_text === 'center' && !$back_text && !$front_text) { this.$back_text = $back_text = $('<span>').addClass('progressbar-back-text').prependTo($parent); this.$front_text = $front_text = $('<span>').addClass('progressbar-front-text').prependTo($this); var parent_size; if (is_vertical) { parent_size = $parent.css('height'); $back_text.css({height: parent_size, 'line-height': parent_size}); $front_text.css({height: parent_size, 'line-height': parent_size}); $(window).resize(function () { parent_size = $parent.css('height'); $back_text.css({height: parent_size, 'line-height': parent_size}); $front_text.css({height: parent_size, 'line-height': parent_size}); }); // normal resizing would brick the structure because width is in px } else { parent_size = $parent.css('width'); $front_text.css({width: parent_size}); $(window).resize(function () { parent_size = $parent.css('width'); $front_text.css({width: parent_size}); }); // normal resizing would brick the structure because width is in px } } setTimeout(function () { var current_percentage; var current_value; var this_size; var parent_size; var text; if (is_vertical) { $this.css('height', percentage + '%'); } else { $this.css('width', percentage + '%'); } var progress = setInterval(function () { if (is_vertical) { this_size = $this.height(); parent_size = $parent.height(); } else { this_size = $this.width(); parent_size = $parent.width(); } current_percentage = Math.round(100 * this_size / parent_size); current_value = Math.round(this_size / parent_size * (aria_valuemax - aria_valuemin)); if (current_percentage >= percentage) { current_percentage = percentage; current_value = aria_valuetransitiongoal; done(); clearInterval(progress); } if (options.display_text !== 'none') { text = options.use_percentage ? options.percent_format(current_percentage) : options.amount_format(current_value, aria_valuemax); if (options.display_text === 'fill') { $this.text(text); } else if (options.display_text === 'center') { $back_text.text(text); $front_text.text(text); } } $this.attr('aria-valuenow', current_value); update(current_percentage); }, options.refresh_speed); }, options.transition_delay); }; // PROGRESSBAR PLUGIN DEFINITION // ============================= var old = $.fn.progressbar; $.fn.progressbar = function (option) { return this.each(function () { var $this = $(this); var data = $this.data('bs.progressbar'); var options = typeof option === 'object' && option; if (!data) { $this.data('bs.progressbar', (data = new Progressbar(this, options))); } data.transition(); }); }; $.fn.progressbar.Constructor = Progressbar; // PROGRESSBAR NO CONFLICT // ======================= $.fn.progressbar.noConflict = function () { $.fn.progressbar = old; return this; }; })(window.jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/bootstrap-progressbar-0.6.0.js
bootstrap-progressbar-0.6.0.js
(function($, globals) { 'use strict'; $.dndupload = { defaults: { action: 'upload-files', fieldname: 'files', autosubmit: true } }; var ams = MyAMS; var isAdvancedUpload = function() { var div = document.createElement('div'); return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && ('FormData' in window) && ('FileReader' in window); } (); // Initialize upload form function init(input, settings) { $(input).each(function() { var widget = $(this); if (widget.data('ams-dndupload-initialiazed')) { return; } settings = $.extend(true, {}, $.dndupload.defaults, settings); var uploader = widget.get(0); if (uploader.tagName !== 'FORM') { widget.removeClass('dndupload') .html('<form action="{action}" method="POST" enctype="multipart/form-data" class="dndupload"></form>'.replace(/{action}/, settings.action)); widget = $('form', widget); } var template = '<div class="box__input">\n' + ' <svg class="box__icon" xmlns="http://www.w3.org/2000/svg" width="50" height="43" viewBox="0 0 50 43">\n' + ' <path d="M48.4 26.5c-.9 0-1.7.7-1.7 1.7v11.6h-43.3v-11.6c0-.9-.7-1.7-1.7-1.7s-1.7.7-1.7 1.7v13.2c0 .9.7 1.7 1.7 1.7h46.7c.9 0 1.7-.7 1.7-1.7v-13.2c0-1-.7-1.7-1.7-1.7zm-24.5 6.1c.3.3.8.5 1.2.5.4 0 .9-.2 1.2-.5l10-11.6c.7-.7.7-1.7 0-2.4s-1.7-.7-2.4 0l-7.1 8.3v-25.3c0-.9-.7-1.7-1.7-1.7s-1.7.7-1.7 1.7v25.3l-7.1-8.3c-.7-.7-1.7-.7-2.4 0s-.7 1.7 0 2.4l10 11.6z" />\n' + ' </svg>\n' + ' <input type="file" name="{label}" id="file" class="box__file" multiple="multiple"\n'.replace(/{label}/, settings.fieldname) + ' data-multiple-caption="{label}" />\n'.replace(/{label}/, ams.plugins.i18n.dndupload.FILES_SELECTED) + ' <label for="file">\n' + ' <strong>{label}</strong> {add}<br />\n'.replace(/{label}/, ams.plugins.i18n.dndupload.CHOOSE_FILE).replace(/{add}/, ams.plugins.i18n.dndupload.ADD_INFO) + ' <span class="box__dragndrop">{label}</span></label>\n'.replace(/{label}/, ams.plugins.i18n.dndupload.DRAG_FILE) + ' <button type="submit" class="box__button">{label}</button>\n'.replace(/{label}/, ams.plugins.i18n.dndupload.UPLOAD) + '</div>\n' + '<div class="box__uploading">{label}</div>\n'.replace(/{label}/, ams.plugins.i18n.dndupload.UPLOADING) + '<div class="box__success">{label}\n'.replace(/{label}/, ams.plugins.i18n.dndupload.DONE) + ' <a href=".?" class="box__restart" role="button">{label}</a>\n'.replace(/{label}/, ams.plugins.i18n.dndupload.UPLOAD_MORE) + '</div>\n' + '<div class="box__error">{label}<span></span>. \n'.replace(/{label}/, ams.plugins.i18n.dndupload.ERROR) + ' <a href=".?" class="box__restart" role="button">{label}</a>\n'.replace(/{label}/, ams.plugins.i18n.dndupload.TRY_AGAIN) + '</div>'; widget.html(template); var form = widget, input = form.find('input[type="file"]'), label = form.find('label'), error = form.find('.box__error span'), restart = form.find('.box__restart'), droppedFiles = false; var showFiles = function(files) { label.text(files.length > 1 ? (input.attr('data-multiple-caption') || '').replace(/{count}/, files.length) : files[0].name); }; input.on('change', function(ev) { showFiles(ev.target.files); if (settings.autosubmit) { form.trigger('submit'); } }); if (isAdvancedUpload) { form.addClass('has-advanced-upload') .on('drag dragstart dragend dragover dragenter dragleave drop', function(ev) { ev.preventDefault(); ev.stopPropagation(); }) .on('dragover dragenter', function() { form.addClass('is-dragover'); }) .on('dragleave dragend drop', function() { form.removeClass('is-dragover'); }) .on('drop', function(ev) { droppedFiles = ev.originalEvent.dataTransfer.files; showFiles(droppedFiles); if (settings.autosubmit) { form.trigger('submit'); } }); } form.on('submit', function(ev) { if (form.hasClass('is-uploading')) { return false; } form.addClass('is-uploading') .removeClass('is-error'); if (isAdvancedUpload) { ev.preventDefault(); var ajaxData = new FormData(form.get(0)); if (droppedFiles) { $.each(droppedFiles, function(i, file) { ajaxData.append(input.attr('name'), file); }); } $.ajax({ url: form.attr('action'), type: form.attr('method'), data: ajaxData, dataType: 'json', cache: false, contentType: false, processData: false, success: function(data) { if (typeof(data) === 'string') { data = JSON.parse(data); } ams.ajax.handleJSON(data); }, complete: function() { form.removeClass('is-uploading'); } }); } else { var iframeName = 'uploadiframe_' + new Date().getTime(), iframe = $('<iframe>').attr('name', iframeName) .attr('style', 'display: none') .appendTo($('body')); form.attr('target', iframeName); iframe.one('load', function() { var data = JSON.parse(iframe.contents().find('body').text()); form.removeClass('is-uploading') .addClass(data.success === true ? 'is-success' : 'is-error') .removeAttr('target'); if (!data.success) { error.text(data.error); } iframe.remove(); }); } }); restart.on('click', function(ev) { ev.preventDefault(); form.removeClass('is-error is-success'); input.trigger('click'); }); input.on('focus', function() { input.addClass('has-focus'); }).on('blur', function() { input.removeClass('has-focus'); }); $(uploader).removeClass('hidden'); widget.data('ams-dndupload-initialized', true); }); return input; } function destroy(input) { } $.extend($.fn, { dndupload: function(method, data) { var input = $(this); switch(method) { case 'settings': if (data === undefined) { return input.data('dndupload-settings'); } else { input.each(function() { var settings = input.data('dndupload-settings') || {}; destroy($(this)); input.dndupload($.extend(true, settings, data)); }); } return input; case 'destroy': input.each(function() { destroy($(this)); }); return input; default: if (method !== 'create') { data = method; } input.each(function() { init($(this), data); }); return input; } } }); })(jQuery, this);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dndupload.js
jquery-dndupload.js
(function(a){if(typeof define==="function"&&define.amd){define(["jquery"],a)}else{if(typeof exports==="object"){module.exports=a(require("jquery"))}else{a(jQuery)}}}(function(f){f.minicolors={defaults:{animationSpeed:50,animationEasing:"swing",change:null,changeDelay:0,control:"hue",dataUris:true,defaultValue:"",hide:null,hideSpeed:100,inline:false,letterCase:"lowercase",opacity:false,position:"bottom left",show:null,showSpeed:100,theme:"default"}};f.extend(f.fn,{minicolors:function(v,u){switch(v){case"destroy":f(this).each(function(){t(f(this))});return f(this);case"hide":k();return f(this);case"opacity":if(u===undefined){return f(this).attr("data-opacity")}else{f(this).each(function(){b(f(this).attr("data-opacity",u))})}return f(this);case"rgbObject":return i(f(this),v==="rgbaObject");case"rgbString":case"rgbaString":return j(f(this),v==="rgbaString");case"settings":if(u===undefined){return f(this).data("minicolors-settings")}else{f(this).each(function(){var w=f(this).data("minicolors-settings")||{};t(f(this));f(this).minicolors(f.extend(true,w,u))})}return f(this);case"show":s(f(this).eq(0));return f(this);case"value":if(u===undefined){return f(this).val()}else{f(this).each(function(){b(f(this).val(u))})}return f(this);default:if(v!=="create"){u=v}f(this).each(function(){p(f(this),u)});return f(this)}}});function p(u,v){var x=f('<div class="minicolors" />'),w=f.minicolors.defaults;if(u.data("minicolors-initialized")){return}v=f.extend(true,{},w,v);x.addClass("minicolors-theme-"+v.theme).toggleClass("minicolors-with-opacity",v.opacity).toggleClass("minicolors-no-data-uris",v.dataUris!==true);if(v.position!==undefined){f.each(v.position.split(" "),function(){x.addClass("minicolors-position-"+this)})}u.addClass("minicolors-input").data("minicolors-initialized",false).data("minicolors-settings",v).prop("size",7).wrap(x).after('<div class="minicolors-panel minicolors-slider-'+v.control+'"><div class="minicolors-slider minicolors-sprite"><div class="minicolors-picker"></div></div><div class="minicolors-opacity-slider minicolors-sprite"><div class="minicolors-picker"></div></div><div class="minicolors-grid minicolors-sprite"><div class="minicolors-grid-inner"></div><div class="minicolors-picker"><div></div></div></div></div>');if(!v.inline){u.after('<span class="minicolors-swatch minicolors-sprite"><span class="minicolors-swatch-color"></span></span>');u.next(".minicolors-swatch").on("click",function(y){y.preventDefault();u.focus()})}u.parent().find(".minicolors-panel").on("selectstart",function(){return false}).end();if(v.inline){u.parent().addClass("minicolors-inline")}b(u,false);u.data("minicolors-initialized",true)}function t(u){var v=u.parent();u.removeData("minicolors-initialized").removeData("minicolors-settings").removeProp("size").removeClass("minicolors-input");v.before(u).remove()}function s(v){var x=v.parent(),u=x.find(".minicolors-panel"),w=v.data("minicolors-settings");if(!v.data("minicolors-initialized")||v.prop("disabled")||x.hasClass("minicolors-inline")||x.hasClass("minicolors-focus")){return}k();x.addClass("minicolors-focus");u.stop(true,true).fadeIn(w.showSpeed,function(){if(w.show){w.show.call(v.get(0))}})}function k(){f(".minicolors-focus").each(function(){var x=f(this),v=x.find(".minicolors-input"),u=x.find(".minicolors-panel"),w=v.data("minicolors-settings");u.fadeOut(w.hideSpeed,function(){if(w.hide){w.hide.call(v.get(0))}x.removeClass("minicolors-focus")})})}function o(H,v,w){var K=H.parents(".minicolors").find(".minicolors-input"),z=K.data("minicolors-settings"),F=H.find("[class$=-picker]"),E=H.offset().left,D=H.offset().top,J=Math.round(v.pageX-E),I=Math.round(v.pageY-D),B=w?z.animationSpeed:0,C,A,u,G;if(v.originalEvent.changedTouches){J=v.originalEvent.changedTouches[0].pageX-E;I=v.originalEvent.changedTouches[0].pageY-D}if(J<0){J=0}if(I<0){I=0}if(J>H.width()){J=H.width()}if(I>H.height()){I=H.height()}if(H.parent().is(".minicolors-slider-wheel")&&F.parent().is(".minicolors-grid")){C=75-J;A=75-I;u=Math.sqrt(C*C+A*A);G=Math.atan2(A,C);if(G<0){G+=Math.PI*2}if(u>75){u=75;J=75-(75*Math.cos(G));I=75-(75*Math.sin(G))}J=Math.round(J);I=Math.round(I)}if(H.is(".minicolors-grid")){F.stop(true).animate({top:I+"px",left:J+"px"},B,z.animationEasing,function(){h(K,H)})}else{F.stop(true).animate({top:I+"px"},B,z.animationEasing,function(){h(K,H)})}}function h(M,T){function P(y,x){var V,U;if(!y.length||!x){return null}V=y.offset().left;U=y.offset().top;return{x:V-x.offset().left+(y.outerWidth()/2),y:U-x.offset().top+(y.outerHeight()/2)}}var D,E,S,K,J,N,A,H=M.val(),B=M.attr("data-opacity"),C=M.parent(),R=M.data("minicolors-settings"),O=C.find(".minicolors-swatch"),u=C.find(".minicolors-grid"),Q=C.find(".minicolors-slider"),G=C.find(".minicolors-opacity-slider"),F=u.find("[class$=-picker]"),L=Q.find("[class$=-picker]"),z=G.find("[class$=-picker]"),w=P(F,u),v=P(L,Q),I=P(z,G);if(T.is(".minicolors-grid, .minicolors-slider")){switch(R.control){case"wheel":K=(u.width()/2)-w.x;J=(u.height()/2)-w.y;N=Math.sqrt(K*K+J*J);A=Math.atan2(J,K);if(A<0){A+=Math.PI*2}if(N>75){N=75;w.x=69-(75*Math.cos(A));w.y=69-(75*Math.sin(A))}E=m(N/0.75,0,100);D=m(A*180/Math.PI,0,360);S=m(100-Math.floor(v.y*(100/Q.height())),0,100);H=c({h:D,s:E,b:S});Q.css("backgroundColor",c({h:D,s:E,b:100}));break;case"saturation":D=m(parseInt(w.x*(360/u.width()),10),0,360);E=m(100-Math.floor(v.y*(100/Q.height())),0,100);S=m(100-Math.floor(w.y*(100/u.height())),0,100);H=c({h:D,s:E,b:S});Q.css("backgroundColor",c({h:D,s:100,b:S}));C.find(".minicolors-grid-inner").css("opacity",E/100);break;case"brightness":D=m(parseInt(w.x*(360/u.width()),10),0,360);E=m(100-Math.floor(w.y*(100/u.height())),0,100);S=m(100-Math.floor(v.y*(100/Q.height())),0,100);H=c({h:D,s:E,b:S});Q.css("backgroundColor",c({h:D,s:E,b:100}));C.find(".minicolors-grid-inner").css("opacity",1-(S/100));break;default:D=m(360-parseInt(v.y*(360/Q.height()),10),0,360);E=m(Math.floor(w.x*(100/u.width())),0,100);S=m(100-Math.floor(w.y*(100/u.height())),0,100);H=c({h:D,s:E,b:S});u.css("backgroundColor",c({h:D,s:100,b:100}));break}M.val(l(H,R.letterCase))}if(T.is(".minicolors-opacity-slider")){if(R.opacity){B=parseFloat(1-(I.y/G.height())).toFixed(2)}else{B=1}if(R.opacity){M.attr("data-opacity",B)}}O.find("SPAN").css({backgroundColor:H,opacity:B});e(M,H,B)}function b(H,I){var C,K,z,F,E,J,w,A=H.parent(),N=H.data("minicolors-settings"),L=A.find(".minicolors-swatch"),u=A.find(".minicolors-grid"),M=A.find(".minicolors-slider"),D=A.find(".minicolors-opacity-slider"),B=u.find("[class$=-picker]"),G=M.find("[class$=-picker]"),v=D.find("[class$=-picker]");C=l(q(H.val(),true),N.letterCase);if(!C){C=l(q(N.defaultValue,true),N.letterCase)}K=d(C);if(!I){H.val(C)}if(N.opacity){z=H.attr("data-opacity")===""?1:m(parseFloat(H.attr("data-opacity")).toFixed(2),0,1);if(isNaN(z)){z=1}H.attr("data-opacity",z);L.find("SPAN").css("opacity",z);E=m(D.height()-(D.height()*z),0,D.height());v.css("top",E+"px")}L.find("SPAN").css("backgroundColor",C);switch(N.control){case"wheel":J=m(Math.ceil(K.s*0.75),0,u.height()/2);w=K.h*Math.PI/180;F=m(75-Math.cos(w)*J,0,u.width());E=m(75-Math.sin(w)*J,0,u.height());B.css({top:E+"px",left:F+"px"});E=150-(K.b/(100/u.height()));if(C===""){E=0}G.css("top",E+"px");M.css("backgroundColor",c({h:K.h,s:K.s,b:100}));break;case"saturation":F=m((5*K.h)/12,0,150);E=m(u.height()-Math.ceil(K.b/(100/u.height())),0,u.height());B.css({top:E+"px",left:F+"px"});E=m(M.height()-(K.s*(M.height()/100)),0,M.height());G.css("top",E+"px");M.css("backgroundColor",c({h:K.h,s:100,b:K.b}));A.find(".minicolors-grid-inner").css("opacity",K.s/100);break;case"brightness":F=m((5*K.h)/12,0,150);E=m(u.height()-Math.ceil(K.s/(100/u.height())),0,u.height());B.css({top:E+"px",left:F+"px"});E=m(M.height()-(K.b*(M.height()/100)),0,M.height());G.css("top",E+"px");M.css("backgroundColor",c({h:K.h,s:K.s,b:100}));A.find(".minicolors-grid-inner").css("opacity",1-(K.b/100));break;default:F=m(Math.ceil(K.s/(100/u.width())),0,u.width());E=m(u.height()-Math.ceil(K.b/(100/u.height())),0,u.height());B.css({top:E+"px",left:F+"px"});E=m(M.height()-(K.h/(360/M.height())),0,M.height());G.css("top",E+"px");u.css("backgroundColor",c({h:K.h,s:100,b:100}));break}if(H.data("minicolors-initialized")){e(H,C,z)}}function e(u,y,v){var w=u.data("minicolors-settings"),x=u.data("minicolors-lastChange");if(!x||x.hex!==y||x.opacity!==v){u.data("minicolors-lastChange",{hex:y,opacity:v});if(w.change){if(w.changeDelay){clearTimeout(u.data("minicolors-changeTimeout"));u.data("minicolors-changeTimeout",setTimeout(function(){w.change.call(u.get(0),y,v)},w.changeDelay))}else{w.change.call(u.get(0),y,v)}}u.trigger("change").trigger("input")}}function i(u){var x=q(f(u).val(),true),w=n(x),v=f(u).attr("data-opacity");if(!w){return null}if(v!==undefined){f.extend(w,{a:parseFloat(v)})}return w}function j(u,y){var x=q(f(u).val(),true),w=n(x),v=f(u).attr("data-opacity");if(!w){return null}if(v===undefined){v=1}if(y){return"rgba("+w.r+", "+w.g+", "+w.b+", "+parseFloat(v)+")"}else{return"rgb("+w.r+", "+w.g+", "+w.b+")"}}function l(u,v){return v==="uppercase"?u.toUpperCase():u.toLowerCase()}function q(u,v){u=u.replace(/[^A-F0-9]/ig,"");if(u.length!==3&&u.length!==6){return""}if(u.length===3&&v){u=u[0]+u[0]+u[1]+u[1]+u[2]+u[2]}return"#"+u}function m(w,v,u){if(w<v){w=v}if(w>u){w=u}return w}function r(u){var x={};var B=Math.round(u.h);var A=Math.round(u.s*255/100);var w=Math.round(u.b*255/100);if(A===0){x.r=x.g=x.b=w}else{var C=w;var z=(255-A)*w/255;var y=(C-z)*(B%60)/60;if(B===360){B=0}if(B<60){x.r=C;x.b=z;x.g=z+y}else{if(B<120){x.g=C;x.b=z;x.r=C-y}else{if(B<180){x.g=C;x.r=z;x.b=z+y}else{if(B<240){x.b=C;x.r=z;x.g=C-y}else{if(B<300){x.b=C;x.g=z;x.r=z+y}else{if(B<360){x.r=C;x.g=z;x.b=C-y}else{x.r=0;x.g=0;x.b=0}}}}}}}return{r:Math.round(x.r),g:Math.round(x.g),b:Math.round(x.b)}}function a(u){var v=[u.r.toString(16),u.g.toString(16),u.b.toString(16)];f.each(v,function(w,x){if(x.length===1){v[w]="0"+x}});return"#"+v.join("")}function c(u){return a(r(u))}function d(v){var u=g(n(v));if(u.s===0){u.h=360}return u}function g(w){var v={h:0,s:0,b:0};var x=Math.min(w.r,w.g,w.b);var u=Math.max(w.r,w.g,w.b);var y=u-x;v.b=u;v.s=u!==0?255*y/u:0;if(v.s!==0){if(w.r===u){v.h=(w.g-w.b)/y}else{if(w.g===u){v.h=2+(w.b-w.r)/y}else{v.h=4+(w.r-w.g)/y}}}else{v.h=-1}v.h*=60;if(v.h<0){v.h+=360}v.s*=100/255;v.b*=100/255;return v}function n(u){u=parseInt(((u.indexOf("#")>-1)?u.substring(1):u),16);return{r:u>>16,g:(u&65280)>>8,b:(u&255)}}f(document).on("mousedown.minicolors touchstart.minicolors",function(u){if(!f(u.target).parents().add(u.target).hasClass("minicolors")){k()}}).on("mousedown.minicolors touchstart.minicolors",".minicolors-grid, .minicolors-slider, .minicolors-opacity-slider",function(u){var v=f(this);u.preventDefault();f(document).data("minicolors-target",v);o(v,u,true)}).on("mousemove.minicolors touchmove.minicolors",function(u){var v=f(document).data("minicolors-target");if(v){o(v,u)}}).on("mouseup.minicolors touchend.minicolors",function(){f(this).removeData("minicolors-target")}).on("mousedown.minicolors touchstart.minicolors",".minicolors-swatch",function(v){var u=f(this).parent().find(".minicolors-input");v.preventDefault();s(u)}).on("focus.minicolors",".minicolors-input",function(){var u=f(this);if(!u.data("minicolors-initialized")){return}s(u)}).on("blur.minicolors",".minicolors-input",function(){var u=f(this),v=u.data("minicolors-settings");if(!u.data("minicolors-initialized")){return}u.val(q(u.val(),true));if(u.val()===""){u.val(q(v.defaultValue,true))}u.val(l(u.val(),v.letterCase))}).on("keydown.minicolors",".minicolors-input",function(v){var u=f(this);if(!u.data("minicolors-initialized")){return}switch(v.keyCode){case 9:k();break;case 13:case 27:k();u.blur();break}}).on("keyup.minicolors",".minicolors-input",function(){var u=f(this);if(!u.data("minicolors-initialized")){return}b(u,true)}).on("paste.minicolors",".minicolors-input",function(){var u=f(this);if(!u.data("minicolors-initialized")){return}setTimeout(function(){b(u,true)},1)})}));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-minicolors.min.js
jquery-minicolors.min.js
(function ($, window, document, undefined) { /*global jQuery, console*/ 'use strict'; var pluginName = 'treeview'; var _default = {}; _default.settings = { injectStyle: true, levels: 2, expandIcon: 'glyphicon glyphicon-plus', collapseIcon: 'glyphicon glyphicon-minus', emptyIcon: 'glyphicon', nodeIcon: '', selectedIcon: '', checkedIcon: 'glyphicon glyphicon-check', uncheckedIcon: 'glyphicon glyphicon-unchecked', color: undefined, // '#000000', backColor: undefined, // '#FFFFFF', borderColor: undefined, // '#dddddd', onhoverColor: '#F5F5F5', selectedColor: '#FFFFFF', selectedBackColor: '#428bca', unselectableBackColor: undefined, //'#FFFFFF', searchResultColor: '#D9534F', searchResultBackColor: undefined, //'#FFFFFF', enableLinks: false, highlightSelected: true, highlightSearchResults: true, showBorder: true, showIcon: true, showCheckbox: false, showTags: false, toggleUnselectable: true, multiSelect: false, // Event handlers onNodeChecked: undefined, onNodeCollapsed: undefined, onNodeDisabled: undefined, onNodeEnabled: undefined, onNodeExpanded: undefined, onNodeSelected: undefined, onNodeUnchecked: undefined, onNodeUnselected: undefined, onSearchComplete: undefined, onSearchCleared: undefined }; _default.options = { silent: false, ignoreChildren: false }; _default.searchOptions = { ignoreCase: true, exactMatch: false, revealResults: true }; var Tree = function (element, options) { this.$element = $(element); this.elementId = element.id; this.styleId = this.elementId + '-style'; this.init(options); return { // Options (public access) options: this.options, // Initialize / destroy methods init: $.proxy(this.init, this), remove: $.proxy(this.remove, this), // Get methods getNode: $.proxy(this.getNode, this), getParent: $.proxy(this.getParent, this), getSiblings: $.proxy(this.getSiblings, this), getSelected: $.proxy(this.getSelected, this), getUnselected: $.proxy(this.getUnselected, this), getExpanded: $.proxy(this.getExpanded, this), getCollapsed: $.proxy(this.getCollapsed, this), getChecked: $.proxy(this.getChecked, this), getUnchecked: $.proxy(this.getUnchecked, this), getDisabled: $.proxy(this.getDisabled, this), getEnabled: $.proxy(this.getEnabled, this), // Select methods selectNode: $.proxy(this.selectNode, this), unselectNode: $.proxy(this.unselectNode, this), toggleNodeSelected: $.proxy(this.toggleNodeSelected, this), // Expand / collapse methods collapseAll: $.proxy(this.collapseAll, this), collapseNode: $.proxy(this.collapseNode, this), expandAll: $.proxy(this.expandAll, this), expandNode: $.proxy(this.expandNode, this), toggleNodeExpanded: $.proxy(this.toggleNodeExpanded, this), revealNode: $.proxy(this.revealNode, this), // Expand / collapse methods checkAll: $.proxy(this.checkAll, this), checkNode: $.proxy(this.checkNode, this), uncheckAll: $.proxy(this.uncheckAll, this), uncheckNode: $.proxy(this.uncheckNode, this), toggleNodeChecked: $.proxy(this.toggleNodeChecked, this), // Disable / enable methods disableAll: $.proxy(this.disableAll, this), disableNode: $.proxy(this.disableNode, this), enableAll: $.proxy(this.enableAll, this), enableNode: $.proxy(this.enableNode, this), toggleNodeDisabled: $.proxy(this.toggleNodeDisabled, this), // Search methods search: $.proxy(this.search, this), clearSearch: $.proxy(this.clearSearch, this) }; }; Tree.prototype.init = function (options) { this.tree = []; this.nodes = []; if (options.data) { if (typeof options.data === 'string') { options.data = $.parseJSON(options.data); } this.tree = $.extend(true, [], options.data); delete options.data; } this.options = $.extend({}, _default.settings, options); this.destroy(); this.subscribeEvents(); this.setInitialStates({ nodes: this.tree }, 0); this.render(); }; Tree.prototype.remove = function () { this.destroy(); $.removeData(this, pluginName); $('#' + this.styleId).remove(); }; Tree.prototype.destroy = function () { if (!this.initialized) return; this.$wrapper.remove(); this.$wrapper = null; // Switch off events this.unsubscribeEvents(); // Reset this.initialized flag this.initialized = false; }; Tree.prototype.unsubscribeEvents = function () { this.$element.off('click'); this.$element.off('nodeChecked'); this.$element.off('nodeCollapsed'); this.$element.off('nodeDisabled'); this.$element.off('nodeEnabled'); this.$element.off('nodeExpanded'); this.$element.off('nodeSelected'); this.$element.off('nodeUnchecked'); this.$element.off('nodeUnselected'); this.$element.off('searchComplete'); this.$element.off('searchCleared'); }; Tree.prototype.subscribeEvents = function () { this.unsubscribeEvents(); this.$element.on('click', $.proxy(this.clickHandler, this)); if (typeof (this.options.onNodeChecked) === 'function') { this.$element.on('nodeChecked', this.options.onNodeChecked); } if (typeof (this.options.onNodeCollapsed) === 'function') { this.$element.on('nodeCollapsed', this.options.onNodeCollapsed); } if (typeof (this.options.onNodeDisabled) === 'function') { this.$element.on('nodeDisabled', this.options.onNodeDisabled); } if (typeof (this.options.onNodeEnabled) === 'function') { this.$element.on('nodeEnabled', this.options.onNodeEnabled); } if (typeof (this.options.onNodeExpanded) === 'function') { this.$element.on('nodeExpanded', this.options.onNodeExpanded); } if (typeof (this.options.onNodeSelected) === 'function') { this.$element.on('nodeSelected', this.options.onNodeSelected); } if (typeof (this.options.onNodeUnchecked) === 'function') { this.$element.on('nodeUnchecked', this.options.onNodeUnchecked); } if (typeof (this.options.onNodeUnselected) === 'function') { this.$element.on('nodeUnselected', this.options.onNodeUnselected); } if (typeof (this.options.onSearchComplete) === 'function') { this.$element.on('searchComplete', this.options.onSearchComplete); } if (typeof (this.options.onSearchCleared) === 'function') { this.$element.on('searchCleared', this.options.onSearchCleared); } }; /* Recurse the tree structure and ensure all nodes have valid initial states. User defined states will be preserved. For performance we also take this opportunity to index nodes in a flattened structure */ Tree.prototype.setInitialStates = function (node, level) { if (!node.nodes) return; level += 1; var parent = node; var _this = this; $.each(node.nodes, function checkStates(index, node) { // nodeId : unique, incremental identifier node.nodeId = _this.nodes.length; // parentId : transversing up the tree node.parentId = parent.nodeId; // if not provided set selectable default value if (!node.hasOwnProperty('selectable')) { node.selectable = true; } // where provided we should preserve states node.state = node.state || {}; // set checked state; unless set always false if (!node.state.hasOwnProperty('checked')) { node.state.checked = false; } // set enabled state; unless set always false if (!node.state.hasOwnProperty('disabled')) { node.state.disabled = false; } // set expanded state; if not provided based on levels if (!node.state.hasOwnProperty('expanded')) { if (!node.state.disabled && (level < _this.options.levels) && (node.nodes && node.nodes.length > 0)) { node.state.expanded = true; } else { node.state.expanded = false; } } // set selected state; unless set always false if (!node.state.hasOwnProperty('selected')) { node.state.selected = false; } // index nodes in a flattened structure for use later _this.nodes.push(node); // recurse child nodes and transverse the tree if (node.nodes) { _this.setInitialStates(node, level); } }); }; Tree.prototype.clickHandler = function (event) { if (!this.options.enableLinks) event.preventDefault(); var target = $(event.target); var node = this.findNode(target); if (!node || node.state.disabled) return; var classList = target.attr('class') ? target.attr('class').split(' ') : []; if ((classList.indexOf('expand-icon') !== -1)) { this.toggleExpandedState(node, _default.options); this.render(); } else if ((classList.indexOf('check-icon') !== -1)) { this.toggleCheckedState(node, _default.options); this.render(); } else { if (node.selectable) { this.toggleSelectedState(node, _default.options); } else if (this.options.toggleUnselectable) { this.toggleExpandedState(node, _default.options); } this.render(); } }; // Looks up the DOM for the closest parent list item to retrieve the // data attribute nodeid, which is used to lookup the node in the flattened structure. Tree.prototype.findNode = function (target) { var nodeId = target.closest('li.list-group-item').attr('data-nodeid'); var node = this.nodes[nodeId]; if (!node) { console.log('Error: node does not exist'); } return node; }; Tree.prototype.toggleExpandedState = function (node, options) { if (!node) return; this.setExpandedState(node, !node.state.expanded, options); }; Tree.prototype.setExpandedState = function (node, state, options) { if (state === node.state.expanded) return; if (state && node.nodes) { // Expand a node node.state.expanded = true; if (!options.silent) { this.$element.trigger('nodeExpanded', $.extend(true, {}, node)); } } else if (!state) { // Collapse a node node.state.expanded = false; if (!options.silent) { this.$element.trigger('nodeCollapsed', $.extend(true, {}, node)); } // Collapse child nodes if (node.nodes && !options.ignoreChildren) { $.each(node.nodes, $.proxy(function (index, node) { this.setExpandedState(node, false, options); }, this)); } } }; Tree.prototype.toggleSelectedState = function (node, options) { if (!node) return; this.setSelectedState(node, !node.state.selected, options); }; Tree.prototype.setSelectedState = function (node, state, options) { if (state === node.state.selected) return; if (state) { // If multiSelect false, unselect previously selected if (!this.options.multiSelect) { $.each(this.findNodes('true', 'g', 'state.selected'), $.proxy(function (index, node) { this.setSelectedState(node, false, options); }, this)); } // Continue selecting node node.state.selected = true; if (!options.silent) { this.$element.trigger('nodeSelected', $.extend(true, {}, node)); } } else { // Unselect node node.state.selected = false; if (!options.silent) { this.$element.trigger('nodeUnselected', $.extend(true, {}, node)); } } }; Tree.prototype.toggleCheckedState = function (node, options) { if (!node) return; this.setCheckedState(node, !node.state.checked, options); }; Tree.prototype.setCheckedState = function (node, state, options) { if (state === node.state.checked) return; if (state) { // Check node node.state.checked = true; if (!options.silent) { this.$element.trigger('nodeChecked', $.extend(true, {}, node)); } } else { // Uncheck node node.state.checked = false; if (!options.silent) { this.$element.trigger('nodeUnchecked', $.extend(true, {}, node)); } } }; Tree.prototype.setDisabledState = function (node, state, options) { if (state === node.state.disabled) return; if (state) { // Disable node node.state.disabled = true; // Disable all other states this.setExpandedState(node, false, options); this.setSelectedState(node, false, options); this.setCheckedState(node, false, options); if (!options.silent) { this.$element.trigger('nodeDisabled', $.extend(true, {}, node)); } } else { // Enabled node node.state.disabled = false; if (!options.silent) { this.$element.trigger('nodeEnabled', $.extend(true, {}, node)); } } }; Tree.prototype.render = function () { if (!this.initialized) { // Setup first time only components this.$element.addClass(pluginName); this.$wrapper = $(this.template.list); this.injectStyle(); this.initialized = true; } this.$element.empty().append(this.$wrapper.empty()); // Build tree this.buildTree(this.tree, 0); }; // Starting from the root node, and recursing down the // structure we build the tree one node at a time Tree.prototype.buildTree = function (nodes, level) { if (!nodes) return; level += 1; var _this = this; $.each(nodes, function addNodes(id, node) { var treeItem = $(_this.template.item) .addClass('node-' + _this.elementId) .addClass(node.state.checked ? 'node-checked' : '') .addClass(node.state.disabled ? 'node-disabled': '') .addClass(node.state.selected ? 'node-selected' : '') .addClass(node.searchResult ? 'search-result' : '') .attr('data-nodeid', node.nodeId) .attr('style', _this.buildStyleOverride(node)); // Add indent/spacer to mimic tree structure for (var i = 0; i < (level - 1); i++) { treeItem.append(_this.template.indent); } // Add expand, collapse or empty spacer icons var classList = []; if (node.nodes) { classList.push('expand-icon'); if (node.state.expanded) { classList.push(_this.options.collapseIcon); } else { classList.push(_this.options.expandIcon); } } else { classList.push(_this.options.emptyIcon); } treeItem .append($(_this.template.icon) .addClass(classList.join(' ')) ); // Add node icon if (_this.options.showIcon) { var classList = ['node-icon']; classList.push(node.icon || _this.options.nodeIcon); if (node.state.selected) { classList.pop(); classList.push(node.selectedIcon || _this.options.selectedIcon || node.icon || _this.options.nodeIcon); } treeItem .append($(_this.template.icon) .addClass(classList.join(' ')) ); } // Add check / unchecked icon if (_this.options.showCheckbox) { var classList = ['check-icon']; if (node.state.checked) { classList.push(_this.options.checkedIcon); } else { classList.push(_this.options.uncheckedIcon); } treeItem .append($(_this.template.icon) .addClass(classList.join(' ')) ); } // Add text if (_this.options.enableLinks) { // Add hyperlink treeItem .append($(_this.template.link) .attr('href', node.href) .append(node.text) ); } else { // otherwise just text treeItem .append(node.text); } // Add tags as badges if (_this.options.showTags && node.tags) { $.each(node.tags, function addTag(id, tag) { treeItem .append($(_this.template.badge) .append(tag) ); }); } // Add item to the tree _this.$wrapper.append(treeItem); // Recursively add child ndoes if (node.nodes && node.state.expanded && !node.state.disabled) { return _this.buildTree(node.nodes, level); } }); }; // Define any node level style override for // 1. selectedNode // 2. node|data assigned color overrides Tree.prototype.buildStyleOverride = function (node) { if (node.state.disabled) return ''; var color = node.color; var backColor = node.backColor; if (!node.selectable) { if (this.options.unselectableColor) { color = this.options.unselectableColor; } if (this.options.unselectableBackColor) { backColor = this.options.unselectableBackColor; } } if (this.options.highlightSelected && node.state.selected) { if (this.options.selectedColor) { color = this.options.selectedColor; } if (this.options.selectedBackColor) { backColor = this.options.selectedBackColor; } } if (this.options.highlightSearchResults && node.searchResult && !node.state.disabled) { if (this.options.searchResultColor) { color = this.options.searchResultColor; } if (this.options.searchResultBackColor) { backColor = this.options.searchResultBackColor; } } return 'color:' + color + ';background-color:' + backColor + ';'; }; // Add inline style into head Tree.prototype.injectStyle = function () { if (this.options.injectStyle && !document.getElementById(this.styleId)) { $('<style type="text/css" id="' + this.styleId + '"> ' + this.buildStyle() + ' </style>').appendTo('head'); } }; // Construct trees style based on user options Tree.prototype.buildStyle = function () { var style = '.node-' + this.elementId + '{'; if (this.options.color) { style += 'color:' + this.options.color + ';'; } if (this.options.backColor) { style += 'background-color:' + this.options.backColor + ';'; } if (!this.options.showBorder) { style += 'border:none;'; } else if (this.options.borderColor) { style += 'border:1px solid ' + this.options.borderColor + ';'; } style += '}'; if (this.options.onhoverColor) { style += '.node-' + this.elementId + ':not(.node-disabled):hover{' + 'background-color:' + this.options.onhoverColor + ';' + '}'; } return this.css + style; }; Tree.prototype.template = { list: '<ul class="list-group"></ul>', item: '<li class="list-group-item"></li>', indent: '<span class="indent"></span>', icon: '<span class="icon"></span>', link: '<a href="#" style="color:inherit;"></a>', badge: '<span class="badge"></span>' }; Tree.prototype.css = '.treeview .list-group-item{cursor:pointer}.treeview span.indent{margin-left:10px;margin-right:10px}.treeview span.icon{width:12px;margin-right:5px}.treeview .node-disabled{color:silver;cursor:not-allowed}' /** Returns a single node object that matches the given node id. @param {Number} nodeId - A node's unique identifier @return {Object} node - Matching node */ Tree.prototype.getNode = function (nodeId) { return this.nodes[nodeId]; }; /** Returns the parent node of a given node, if valid otherwise returns undefined. @param {Object|Number} identifier - A valid node or node id @returns {Object} node - The parent node */ Tree.prototype.getParent = function (identifier) { var node = this.identifyNode(identifier); return this.nodes[node.parentId]; }; /** Returns an array of sibling nodes for a given node, if valid otherwise returns undefined. @param {Object|Number} identifier - A valid node or node id @returns {Array} nodes - Sibling nodes */ Tree.prototype.getSiblings = function (identifier) { var node = this.identifyNode(identifier); var parent = this.getParent(node); var nodes = parent ? parent.nodes : this.tree; return nodes.filter(function (obj) { return obj.nodeId !== node.nodeId; }); }; /** Returns an array of selected nodes. @returns {Array} nodes - Selected nodes */ Tree.prototype.getSelected = function () { return this.findNodes('true', 'g', 'state.selected'); }; /** Returns an array of unselected nodes. @returns {Array} nodes - Unselected nodes */ Tree.prototype.getUnselected = function () { return this.findNodes('false', 'g', 'state.selected'); }; /** Returns an array of expanded nodes. @returns {Array} nodes - Expanded nodes */ Tree.prototype.getExpanded = function () { return this.findNodes('true', 'g', 'state.expanded'); }; /** Returns an array of collapsed nodes. @returns {Array} nodes - Collapsed nodes */ Tree.prototype.getCollapsed = function () { return this.findNodes('false', 'g', 'state.expanded'); }; /** Returns an array of checked nodes. @returns {Array} nodes - Checked nodes */ Tree.prototype.getChecked = function () { return this.findNodes('true', 'g', 'state.checked'); }; /** Returns an array of unchecked nodes. @returns {Array} nodes - Unchecked nodes */ Tree.prototype.getUnchecked = function () { return this.findNodes('false', 'g', 'state.checked'); }; /** Returns an array of disabled nodes. @returns {Array} nodes - Disabled nodes */ Tree.prototype.getDisabled = function () { return this.findNodes('true', 'g', 'state.disabled'); }; /** Returns an array of enabled nodes. @returns {Array} nodes - Enabled nodes */ Tree.prototype.getEnabled = function () { return this.findNodes('false', 'g', 'state.disabled'); }; /** Set a node state to selected @param {Object|Number} identifiers - A valid node, node id or array of node identifiers @param {optional Object} options */ Tree.prototype.selectNode = function (identifiers, options) { this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setSelectedState(node, true, options); }, this)); this.render(); }; /** Set a node state to unselected @param {Object|Number} identifiers - A valid node, node id or array of node identifiers @param {optional Object} options */ Tree.prototype.unselectNode = function (identifiers, options) { this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setSelectedState(node, false, options); }, this)); this.render(); }; /** Toggles a node selected state; selecting if unselected, unselecting if selected. @param {Object|Number} identifiers - A valid node, node id or array of node identifiers @param {optional Object} options */ Tree.prototype.toggleNodeSelected = function (identifiers, options) { this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.toggleSelectedState(node, options); }, this)); this.render(); }; /** Collapse all tree nodes @param {optional Object} options */ Tree.prototype.collapseAll = function (options) { var identifiers = this.findNodes('true', 'g', 'state.expanded'); this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setExpandedState(node, false, options); }, this)); this.render(); }; /** Collapse a given tree node @param {Object|Number} identifiers - A valid node, node id or array of node identifiers @param {optional Object} options */ Tree.prototype.collapseNode = function (identifiers, options) { this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setExpandedState(node, false, options); }, this)); this.render(); }; /** Expand all tree nodes @param {optional Object} options */ Tree.prototype.expandAll = function (options) { options = $.extend({}, _default.options, options); if (options && options.levels) { this.expandLevels(this.tree, options.levels, options); } else { var identifiers = this.findNodes('false', 'g', 'state.expanded'); this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setExpandedState(node, true, options); }, this)); } this.render(); }; /** Expand a given tree node @param {Object|Number} identifiers - A valid node, node id or array of node identifiers @param {optional Object} options */ Tree.prototype.expandNode = function (identifiers, options) { this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setExpandedState(node, true, options); if (node.nodes && (options && options.levels)) { this.expandLevels(node.nodes, options.levels-1, options); } }, this)); this.render(); }; Tree.prototype.expandLevels = function (nodes, level, options) { options = $.extend({}, _default.options, options); $.each(nodes, $.proxy(function (index, node) { this.setExpandedState(node, (level > 0) ? true : false, options); if (node.nodes) { this.expandLevels(node.nodes, level-1, options); } }, this)); }; /** Reveals a given tree node, expanding the tree from node to root. @param {Object|Number|Array} identifiers - A valid node, node id or array of node identifiers @param {optional Object} options */ Tree.prototype.revealNode = function (identifiers, options) { this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { var parentNode = this.getParent(node); while (parentNode) { this.setExpandedState(parentNode, true, options); parentNode = this.getParent(parentNode); }; }, this)); this.render(); }; /** Toggles a nodes expanded state; collapsing if expanded, expanding if collapsed. @param {Object|Number} identifiers - A valid node, node id or array of node identifiers @param {optional Object} options */ Tree.prototype.toggleNodeExpanded = function (identifiers, options) { this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.toggleExpandedState(node, options); }, this)); this.render(); }; /** Check all tree nodes @param {optional Object} options */ Tree.prototype.checkAll = function (options) { var identifiers = this.findNodes('false', 'g', 'state.checked'); this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setCheckedState(node, true, options); }, this)); this.render(); }; /** Check a given tree node @param {Object|Number} identifiers - A valid node, node id or array of node identifiers @param {optional Object} options */ Tree.prototype.checkNode = function (identifiers, options) { this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setCheckedState(node, true, options); }, this)); this.render(); }; /** Uncheck all tree nodes @param {optional Object} options */ Tree.prototype.uncheckAll = function (options) { var identifiers = this.findNodes('true', 'g', 'state.checked'); this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setCheckedState(node, false, options); }, this)); this.render(); }; /** Uncheck a given tree node @param {Object|Number} identifiers - A valid node, node id or array of node identifiers @param {optional Object} options */ Tree.prototype.uncheckNode = function (identifiers, options) { this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setCheckedState(node, false, options); }, this)); this.render(); }; /** Toggles a nodes checked state; checking if unchecked, unchecking if checked. @param {Object|Number} identifiers - A valid node, node id or array of node identifiers @param {optional Object} options */ Tree.prototype.toggleNodeChecked = function (identifiers, options) { this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.toggleCheckedState(node, options); }, this)); this.render(); }; /** Disable all tree nodes @param {optional Object} options */ Tree.prototype.disableAll = function (options) { var identifiers = this.findNodes('false', 'g', 'state.disabled'); this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setDisabledState(node, true, options); }, this)); this.render(); }; /** Disable a given tree node @param {Object|Number} identifiers - A valid node, node id or array of node identifiers @param {optional Object} options */ Tree.prototype.disableNode = function (identifiers, options) { this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setDisabledState(node, true, options); }, this)); this.render(); }; /** Enable all tree nodes @param {optional Object} options */ Tree.prototype.enableAll = function (options) { var identifiers = this.findNodes('true', 'g', 'state.disabled'); this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setDisabledState(node, false, options); }, this)); this.render(); }; /** Enable a given tree node @param {Object|Number} identifiers - A valid node, node id or array of node identifiers @param {optional Object} options */ Tree.prototype.enableNode = function (identifiers, options) { this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setDisabledState(node, false, options); }, this)); this.render(); }; /** Toggles a nodes disabled state; disabling is enabled, enabling if disabled. @param {Object|Number} identifiers - A valid node, node id or array of node identifiers @param {optional Object} options */ Tree.prototype.toggleNodeDisabled = function (identifiers, options) { this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) { this.setDisabledState(node, !node.state.disabled, options); }, this)); this.render(); }; /** Common code for processing multiple identifiers */ Tree.prototype.forEachIdentifier = function (identifiers, options, callback) { options = $.extend({}, _default.options, options); if (!(identifiers instanceof Array)) { identifiers = [identifiers]; } $.each(identifiers, $.proxy(function (index, identifier) { callback(this.identifyNode(identifier), options); }, this)); }; /* Identifies a node from either a node id or object */ Tree.prototype.identifyNode = function (identifier) { return ((typeof identifier) === 'number') ? this.nodes[identifier] : identifier; }; /** Searches the tree for nodes (text) that match given criteria @param {String} pattern - A given string to match against @param {optional Object} options - Search criteria options @return {Array} nodes - Matching nodes */ Tree.prototype.search = function (pattern, options) { options = $.extend({}, _default.searchOptions, options); this.clearSearch({ render: false }); var results = []; if (pattern && pattern.length > 0) { if (options.exactMatch) { pattern = '^' + pattern + '$'; } var modifier = 'g'; if (options.ignoreCase) { modifier += 'i'; } results = this.findNodes(pattern, modifier); // Add searchResult property to all matching nodes // This will be used to apply custom styles // and when identifying result to be cleared $.each(results, function (index, node) { node.searchResult = true; }) } // If revealResults, then render is triggered from revealNode // otherwise we just call render. if (options.revealResults) { this.revealNode(results); } else { this.render(); } this.$element.trigger('searchComplete', $.extend(true, {}, results)); return results; }; /** Clears previous search results */ Tree.prototype.clearSearch = function (options) { options = $.extend({}, { render: true }, options); var results = $.each(this.findNodes('true', 'g', 'searchResult'), function (index, node) { node.searchResult = false; }); if (options.render) { this.render(); } this.$element.trigger('searchCleared', $.extend(true, {}, results)); }; /** Find nodes that match a given criteria @param {String} pattern - A given string to match against @param {optional String} modifier - Valid RegEx modifiers @param {optional String} attribute - Attribute to compare pattern against @return {Array} nodes - Nodes that match your criteria */ Tree.prototype.findNodes = function (pattern, modifier, attribute) { modifier = modifier || 'g'; attribute = attribute || 'text'; var _this = this; return $.grep(this.nodes, function (node) { var val = _this.getNodeValue(node, attribute); if (typeof val === 'string') { return val.match(new RegExp(pattern, modifier)); } }); }; /** Recursive find for retrieving nested attributes values All values are return as strings, unless invalid @param {Object} obj - Typically a node, could be any object @param {String} attr - Identifies an object property using dot notation @return {String} value - Matching attributes string representation */ Tree.prototype.getNodeValue = function (obj, attr) { var index = attr.indexOf('.'); if (index > 0) { var _obj = obj[attr.substring(0, index)]; var _attr = attr.substring(index + 1, attr.length); return this.getNodeValue(_obj, _attr); } else { if (obj.hasOwnProperty(attr)) { return obj[attr].toString(); } else { return undefined; } } }; var logError = function (message) { if (window.console) { window.console.error(message); } }; // Prevent against multiple instantiations, // handle updates and method calls $.fn[pluginName] = function (options, args) { var result; this.each(function () { var _this = $.data(this, pluginName); if (typeof options === 'string') { if (!_this) { logError('Not initialized, can not call method : ' + options); } else if (!$.isFunction(_this[options]) || options.charAt(0) === '_') { logError('No such method : ' + options); } else { if (!(args instanceof Array)) { args = [ args ]; } result = _this[options].apply(_this, args); } } else if (typeof options === 'boolean') { result = _this; } else { $.data(this, pluginName, new Tree(this, $.extend(true, {}, options))); } }); return result || this; }; })(jQuery, window, document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/bootstrap-treeview.js
bootstrap-treeview.js
* @summary KeyTable * @description Spreadsheet like keyboard navigation for DataTables * @version 1.2.0 * @file dataTables.keyTable.js * @author SpryMedia Ltd (www.sprymedia.co.uk) * @contact www.sprymedia.co.uk/contact * @copyright Copyright 2009-2014 SpryMedia Ltd. * * This source file is free software, available under the following license: * MIT license - http://datatables.net/license/mit * * 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 */ // Global scope for KeyTable for backwards compatibility. Will be removed in 1.3 var KeyTable; (function (window, document, undefined) { var factory = function ($, DataTable) { "use strict"; KeyTable = function (oInit) { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * API parameters * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Variable: block * Purpose: Flag whether or not KeyTable events should be processed * Scope: KeyTable - public */ this.block = false; /* * Variable: event * Purpose: Container for all event application methods * Scope: KeyTable - public * Notes: This object contains all the public methods for adding and removing events - these * are dynamically added later on */ this.event = { "remove": {} }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * API methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Function: fnGetCurrentPosition * Purpose: Get the currently focused cell's position * Returns: array int: [ x, y ] * Inputs: void */ this.fnGetCurrentPosition = function () { return [ _iOldX, _iOldY ]; }; /* * Function: fnGetCurrentData * Purpose: Get the currently focused cell's data (innerHTML) * Returns: string: - data requested * Inputs: void */ this.fnGetCurrentData = function () { return _nOldFocus.innerHTML; }; /* * Function: fnGetCurrentTD * Purpose: Get the currently focused cell * Returns: node: - focused element * Inputs: void */ this.fnGetCurrentTD = function () { return _nOldFocus; }; /* * Function: fnSetPosition * Purpose: Set the position of the focused cell * Returns: - * Inputs: int:x - x coordinate * int:y - y coordinate * Notes: Thanks to Rohan Daxini for the basis of this function */ this.fnSetPosition = function (x, y) { if (typeof x == 'object' && x.nodeName) { _fnSetFocus(x); } else { _fnSetFocus(_fnCellFromCoords(x, y)); } }; /* * Function: fnBlur * Purpose: Blur the current focus * Returns: - * Inputs: - */ this.fnBlur = function () { _fnBlur(); }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private parameters * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Variable: _nBody * Purpose: Body node of the table - cached for renference * Scope: KeyTable - private */ var _nBody = null; /* * Variable: * Purpose: * Scope: KeyTable - private */ var _nOldFocus = null; /* * Variable: _iOldX and _iOldY * Purpose: X and Y coords of the old elemet that was focused on * Scope: KeyTable - private */ var _iOldX = null; var _iOldY = null; /* * Variable: _that * Purpose: Scope saving for 'this' after a jQuery event * Scope: KeyTable - private */ var _that = null; /* * Variable: sFocusClass * Purpose: Class that should be used for focusing on a cell * Scope: KeyTable - private */ var _sFocusClass = "focus"; /* * Variable: _bKeyCapture * Purpose: Flag for should KeyTable capture key events or not * Scope: KeyTable - private */ var _bKeyCapture = false; /* * Variable: _oaoEvents * Purpose: Event cache object, one array for each supported event for speed of searching * Scope: KeyTable - private */ var _oaoEvents = { "action": [], "esc": [], "focus": [], "blur": [] }; /* * Variable: _oDatatable * Purpose: DataTables settings object for if we are actually using a * DataTables table * Scope: KeyTable - private */ var _oDatatable = null; var _bForm; var _nInput; var _bInputFocused = false; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Key table events */ /* * Function: _fnEventAddTemplate * Purpose: Create a function (with closure for sKey) event addition API * Returns: function: - template function * Inputs: string:sKey - type of event to detect */ function _fnEventAddTemplate(sKey) { /* * Function: - * Purpose: API function for adding event to cache * Returns: - * Inputs: 1. node:x - target node to add event for * 2. function:y - callback function to apply * or * 1. int:x - x coord. of target cell (can be null for live events) * 2. int:y - y coord. of target cell (can be null for live events) * 3. function:z - callback function to apply * Notes: This function is (interally) overloaded (in as much as javascript allows for * that) - the target cell can be given by either node or coords. */ return function (x, y, z) { if ((x === null || typeof x == "number") && (y === null || typeof y == "number") && typeof z == "function") { _fnEventAdd(sKey, x, y, z); } else if (typeof x == "object" && typeof y == "function") { var aCoords = _fnCoordsFromCell(x); _fnEventAdd(sKey, aCoords[0], aCoords[1], y); } else { alert("Unhandable event type was added: x" + x + " y:" + y + " z:" + z); } }; } /* * Function: _fnEventRemoveTemplate * Purpose: Create a function (with closure for sKey) event removal API * Returns: function: - template function * Inputs: string:sKey - type of event to detect */ function _fnEventRemoveTemplate(sKey) { /* * Function: - * Purpose: API function for removing event from cache * Returns: int: - number of events removed * Inputs: 1. node:x - target node to remove event from * 2. function:y - callback function to apply * or * 1. int:x - x coord. of target cell (can be null for live events) * 2. int:y - y coord. of target cell (can be null for live events) * 3. function:z - callback function to remove - optional * Notes: This function is (interally) overloaded (in as much as javascript allows for * that) - the target cell can be given by either node or coords and the function * to remove is optional */ return function (x, y, z) { if ((x === null || typeof arguments[0] == "number") && (y === null || typeof arguments[1] == "number" )) { if (typeof arguments[2] == "function") { _fnEventRemove(sKey, x, y, z); } else { _fnEventRemove(sKey, x, y); } } else if (typeof arguments[0] == "object") { var aCoords = _fnCoordsFromCell(x); if (typeof arguments[1] == "function") { _fnEventRemove(sKey, aCoords[0], aCoords[1], y); } else { _fnEventRemove(sKey, aCoords[0], aCoords[1]); } } else { alert("Unhandable event type was removed: x" + x + " y:" + y + " z:" + z); } }; } /* Use the template functions to add the event API functions */ for (var sKey in _oaoEvents) { if (sKey) { this.event[sKey] = _fnEventAddTemplate(sKey); this.event.remove[sKey] = _fnEventRemoveTemplate(sKey); } } /* * Function: _fnEventAdd * Purpose: Add an event to the internal cache * Returns: - * Inputs: string:sType - type of event to add, given by the available elements in _oaoEvents * int:x - x-coords to add event to - can be null for "blanket" event * int:y - y-coords to add event to - can be null for "blanket" event * function:fn - callback function for when triggered */ function _fnEventAdd(sType, x, y, fn) { _oaoEvents[sType].push({ "x": x, "y": y, "fn": fn }); } /* * Function: _fnEventRemove * Purpose: Remove an event from the event cache * Returns: int: - number of matching events removed * Inputs: string:sType - type of event to look for * node:nTarget - target table cell * function:fn - optional - remove this function. If not given all handlers of this * type will be removed */ function _fnEventRemove(sType, x, y, fn) { var iCorrector = 0; for (var i = 0, iLen = _oaoEvents[sType].length; i < iLen - iCorrector; i++) { if (typeof fn != 'undefined') { if (_oaoEvents[sType][i - iCorrector].x == x && _oaoEvents[sType][i - iCorrector].y == y && _oaoEvents[sType][i - iCorrector].fn == fn) { _oaoEvents[sType].splice(i - iCorrector, 1); iCorrector++; } } else { if (_oaoEvents[sType][i - iCorrector].x == x && _oaoEvents[sType][i - iCorrector].y == y) { _oaoEvents[sType].splice(i, 1); return 1; } } } return iCorrector; } /* * Function: _fnEventFire * Purpose: Look thought the events cache and fire off the event of interest * Returns: int:iFired - number of events fired * Inputs: string:sType - type of event to look for * int:x - x coord of cell * int:y - y coord of ell * Notes: It might be more efficient to return after the first event has been tirggered, * but that would mean that only one function of a particular type can be * subscribed to a particular node. */ function _fnEventFire(sType, x, y) { var iFired = 0; var aEvents = _oaoEvents[sType]; for (var i = 0; i < aEvents.length; i++) { if ((aEvents[i].x == x && aEvents[i].y == y ) || (aEvents[i].x === null && aEvents[i].y == y ) || (aEvents[i].x == x && aEvents[i].y === null ) || (aEvents[i].x === null && aEvents[i].y === null ) ) { aEvents[i].fn(_fnCellFromCoords(x, y), x, y); iFired++; } } return iFired; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Focus functions */ /* * Function: _fnSetFocus * Purpose: Set focus on a node, and remove from an old node if needed * Returns: - * Inputs: node:nTarget - node we want to focus on * bool:bAutoScroll - optional - should we scroll the view port to the display */ function _fnSetFocus(nTarget, bAutoScroll) { /* If node already has focus, just ignore this call */ if (_nOldFocus == nTarget) { return; } if (typeof bAutoScroll == 'undefined') { bAutoScroll = true; } /* Remove old focus (with blur event if needed) */ if (_nOldFocus !== null) { _fnRemoveFocus(_nOldFocus); } /* Add the new class to highlight the focused cell */ $(nTarget).addClass(_sFocusClass); $(nTarget).parent().addClass(_sFocusClass); /* If it's a DataTable then we need to jump the paging to the relevant page */ var oSettings; if (_oDatatable) { oSettings = _oDatatable; var iRow = _fnFindDtCell(nTarget)[1]; var bKeyCaptureCache = _bKeyCapture; /* Page forwards */ while (iRow >= oSettings.fnDisplayEnd()) { 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; } _oDatatable.oApi._fnCalculateEnd(oSettings); } /* Page backwards */ while (iRow < oSettings._iDisplayStart) { oSettings._iDisplayStart = oSettings._iDisplayLength >= 0 ? oSettings._iDisplayStart - oSettings._iDisplayLength : 0; if (oSettings._iDisplayStart < 0) { oSettings._iDisplayStart = 0; } _oDatatable.oApi._fnCalculateEnd(oSettings); } /* Re-draw the table */ _oDatatable.oApi._fnDraw(oSettings); /* Restore the key capture */ _bKeyCapture = bKeyCaptureCache; } /* Cache the information that we are interested in */ var aNewPos = _fnCoordsFromCell(nTarget); _nOldFocus = nTarget; _iOldX = aNewPos[0]; _iOldY = aNewPos[1]; var iViewportHeight, iViewportWidth, iScrollTop, iScrollLeft, iHeight, iWidth, aiPos; if (bAutoScroll) { /* Scroll the viewport such that the new cell is fully visible in the rendered window */ iViewportHeight = $(window).height(); iViewportWidth = $(window).width(); iScrollTop = $(document).scrollTop(); iScrollLeft = $(document).scrollLeft(); iHeight = nTarget.offsetHeight; iWidth = nTarget.offsetWidth; aiPos = _fnGetPos(nTarget); /* Take account of scrolling in DataTables 1.7 - remove scrolling since that would add to * the positioning calculation */ if (_oDatatable && typeof oSettings.oScroll != 'undefined' && (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "")) { aiPos[1] -= $(oSettings.nTable.parentNode).scrollTop(); aiPos[0] -= $(oSettings.nTable.parentNode).scrollLeft(); } /* Correct viewport positioning for vertical scrolling */ if (aiPos[1] + iHeight > iScrollTop + iViewportHeight) { /* Displayed element if off the bottom of the viewport */ _fnSetScrollTop(aiPos[1] + iHeight - iViewportHeight); } else if (aiPos[1] < iScrollTop) { /* Displayed element if off the top of the viewport */ _fnSetScrollTop(aiPos[1]); } /* Correct viewport positioning for horizontal scrolling */ if (aiPos[0] + iWidth > iScrollLeft + iViewportWidth) { /* Displayed element is off the bottom of the viewport */ _fnSetScrollLeft(aiPos[0] + iWidth - iViewportWidth); } else if (aiPos[0] < iScrollLeft) { /* Displayed element if off the Left of the viewport */ _fnSetScrollLeft(aiPos[0]); } } /* Take account of scrolling in DataTables 1.7 */ if (_oDatatable && typeof oSettings.oScroll != 'undefined' && (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "")) { var dtScrollBody = oSettings.nTable.parentNode; iViewportHeight = dtScrollBody.clientHeight; iViewportWidth = dtScrollBody.clientWidth; iScrollTop = dtScrollBody.scrollTop; iScrollLeft = dtScrollBody.scrollLeft; iHeight = nTarget.offsetHeight; iWidth = nTarget.offsetWidth; /* Correct for vertical scrolling */ if (nTarget.offsetTop + iHeight > iViewportHeight + iScrollTop) { dtScrollBody.scrollTop = (nTarget.offsetTop + iHeight) - iViewportHeight; } else if (nTarget.offsetTop < iScrollTop) { dtScrollBody.scrollTop = nTarget.offsetTop; } /* Correct for horizontal scrolling */ if (nTarget.offsetLeft + iWidth > iViewportWidth + iScrollLeft) { dtScrollBody.scrollLeft = (nTarget.offsetLeft + iWidth) - iViewportWidth; } else if (nTarget.offsetLeft < iScrollLeft) { dtScrollBody.scrollLeft = nTarget.offsetLeft; } } /* Focused - so we want to capture the keys */ _fnCaptureKeys(); /* Fire of the focus event if there is one */ _fnEventFire("focus", _iOldX, _iOldY); } /* * Function: _fnBlur * Purpose: Blur focus from the whole table * Returns: - * Inputs: - */ function _fnBlur() { _fnRemoveFocus(_nOldFocus); _iOldX = null; _iOldY = null; _nOldFocus = null; _fnReleaseKeys(); } /* * Function: _fnRemoveFocus * Purpose: Remove focus from a cell and fire any blur events which are attached * Returns: - * Inputs: node:nTarget - cell of interest */ function _fnRemoveFocus(nTarget) { $(nTarget).removeClass(_sFocusClass); $(nTarget).parent().removeClass(_sFocusClass); _fnEventFire("blur", _iOldX, _iOldY); } /* * Function: _fnClick * Purpose: Focus on the element that has been clicked on by the user * Returns: - * Inputs: event:e - click event */ function _fnClick(e) { var nTarget = this; while (nTarget.nodeName != "TD") { nTarget = nTarget.parentNode; } _fnSetFocus(nTarget); _fnCaptureKeys(); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Key events */ /* * Function: _fnKey * Purpose: Deal with a key events, be it moving the focus or return etc. * Returns: bool: - allow browser default action * Inputs: event:e - key event */ function _fnKey(e) { /* If user or system has blocked KeyTable from doing anything, just ignore this event */ if (_that.block || !_bKeyCapture) { return true; } /* If a modifier key is pressed (exapct shift), ignore the event */ if (e.metaKey || e.altKey || e.ctrlKey) { return true; } var x, y, iTableWidth = _nBody.getElementsByTagName('tr')[0].getElementsByTagName('td').length, iTableHeight; /* Get table height and width - done here so as to be dynamic (if table is updated) */ if (_oDatatable) { /* * Locate the current node in the DataTable overriding the old positions - the reason for * is is that there might have been some DataTables interaction between the last focus and * now */ iTableHeight = _oDatatable.aiDisplay.length; var aDtPos = _fnFindDtCell(_nOldFocus); if (aDtPos === null) { /* If the table has been updated such that the focused cell can't be seen - do nothing */ return; } _iOldX = aDtPos[ 0 ]; _iOldY = aDtPos[ 1 ]; } else { iTableHeight = _nBody.getElementsByTagName('tr').length; } /* Capture shift+tab to match the left arrow key */ var iKey = (e.keyCode == 9 && e.shiftKey) ? -1 : e.keyCode; switch (iKey) { case 13: /* return */ e.preventDefault(); e.stopPropagation(); _fnEventFire("action", _iOldX, _iOldY); return true; case 27: /* esc */ if (!_fnEventFire("esc", _iOldX, _iOldY)) { /* Only lose focus if there isn't an escape handler on the cell */ _fnBlur(); return; } x = _iOldX; y = _iOldY; break; case -1: case 37: /* left arrow */ if (_iOldX > 0) { x = _iOldX - 1; y = _iOldY; } else if (_iOldY > 0) { x = iTableWidth - 1; y = _iOldY - 1; } else { /* at start of table */ if (iKey == -1 && _bForm) { /* If we are in a form, return focus to the 'input' element such that tabbing will * follow correctly in the browser */ _bInputFocused = true; _nInput.focus(); /* This timeout is a little nasty - but IE appears to have some asyhnc behaviour for * focus */ setTimeout(function () { _bInputFocused = false; }, 0); _bKeyCapture = false; _fnBlur(); return true; } else { return false; } } break; case 38: /* up arrow */ if (_iOldY > 0) { x = _iOldX; y = _iOldY - 1; } else { return false; } break; case 36: /* home */ x = _iOldX; y = 0; break; case 33: /* page up */ x = _iOldX; y = _iOldY - 10; if (y < 0) { y = 0; } break; case 9: /* tab */ case 39: /* right arrow */ if (_iOldX < iTableWidth - 1) { x = _iOldX + 1; y = _iOldY; } else if (_iOldY < iTableHeight - 1) { x = 0; y = _iOldY + 1; } else { /* at end of table */ if (iKey == 9 && _bForm) { /* If we are in a form, return focus to the 'input' element such that tabbing will * follow correctly in the browser */ _bInputFocused = true; _nInput.focus(); /* This timeout is a little nasty - but IE appears to have some asyhnc behaviour for * focus */ setTimeout(function () { _bInputFocused = false; }, 0); _bKeyCapture = false; _fnBlur(); return true; } else { return false; } } break; case 40: /* down arrow */ if (_iOldY < iTableHeight - 1) { x = _iOldX; y = _iOldY + 1; } else { return false; } break; case 35: /* end */ x = _iOldX; y = iTableHeight - 1; break; case 34: /* page down */ x = _iOldX; y = _iOldY + 10; if (y > iTableHeight - 1) { y = iTableHeight - 1; } break; default: /* Nothing we are interested in */ return true; } _fnSetFocus(_fnCellFromCoords(x, y)); return false; } /* * Function: _fnCaptureKeys * Purpose: Start capturing key events for this table * Returns: - * Inputs: - */ function _fnCaptureKeys() { if (!_bKeyCapture) { _bKeyCapture = true; } } /* * Function: _fnReleaseKeys * Purpose: Stop capturing key events for this table * Returns: - * Inputs: - */ function _fnReleaseKeys() { _bKeyCapture = false; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Support functions */ /* * Function: _fnCellFromCoords * Purpose: Calulate the target TD cell from x and y coordinates * Returns: node: - TD target * Inputs: int:x - x coordinate * int:y - y coordinate */ function _fnCellFromCoords(x, y) { if (_oDatatable) { if (typeof _oDatatable.aoData[ _oDatatable.aiDisplay[ y ] ] != 'undefined') { return _oDatatable.aoData[ _oDatatable.aiDisplay[ y ] ].nTr.getElementsByTagName('td')[x]; } else { return null; } } else { return $('tr:eq(' + y + ')>td:eq(' + x + ')', _nBody)[0]; } } /* * Function: _fnCoordsFromCell * Purpose: Calculate the x and y position in a table from a TD cell * Returns: array[2] int: [x, y] * Inputs: node:n - TD cell of interest * Notes: Not actually interested in this for DataTables since it might go out of date */ function _fnCoordsFromCell(n) { if (_oDatatable) { return [ $('td', n.parentNode).index(n), $('tr', n.parentNode.parentNode).index(n.parentNode) + _oDatatable._iDisplayStart ]; } else { return [ $('td', n.parentNode).index(n), $('tr', n.parentNode.parentNode).index(n.parentNode) ]; } } /* * Function: _fnSetScrollTop * Purpose: Set the vertical scrolling position * Returns: - * Inputs: int:iPos - scrolltop * Notes: This is so nasty, but without browser detection you can't tell which you should set * So on browsers that support both, the scroll top will be set twice. I can live with * that :-) */ function _fnSetScrollTop(iPos) { document.documentElement.scrollTop = iPos; document.body.scrollTop = iPos; } /* * Function: _fnSetScrollLeft * Purpose: Set the horizontal scrolling position * Returns: - * Inputs: int:iPos - scrollleft */ function _fnSetScrollLeft(iPos) { document.documentElement.scrollLeft = iPos; document.body.scrollLeft = iPos; } /* * Function: _fnGetPos * Purpose: Get the position of an object on the rendered page * Returns: array[2] int: [left, right] * Inputs: node:obj - element of interest */ function _fnGetPos(obj) { var iLeft = 0; var iTop = 0; if (obj.offsetParent) { iLeft = obj.offsetLeft; iTop = obj.offsetTop; obj = obj.offsetParent; while (obj) { iLeft += obj.offsetLeft; iTop += obj.offsetTop; obj = obj.offsetParent; } } return [iLeft, iTop]; } /* * Function: _fnFindDtCell * Purpose: Get the coords. of a cell from the DataTables internal information * Returns: array[2] int: [x, y] coords. or null if not found * Inputs: node:nTarget - the node of interest */ function _fnFindDtCell(nTarget) { for (var i = 0, iLen = _oDatatable.aiDisplay.length; i < iLen; i++) { var nTr = _oDatatable.aoData[ _oDatatable.aiDisplay[i] ].nTr; var nTds = nTr.getElementsByTagName('td'); for (var j = 0, jLen = nTds.length; j < jLen; j++) { if (nTds[j] == nTarget) { return [ j, i ]; } } } return null; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation */ /* * Function: _fnInit * Purpose: Initialise the KeyTable * Returns: - * Inputs: object:oInit - optional - Initalisation object with the following parameters: * array[2] int:focus - x and y coordinates of the initial target * or * node:focus - the node to set initial focus on * node:table - the table to use, if not given, first table with class 'KeyTable' will be used * string:focusClass - focusing class to give to table elements * object:that - focus * bool:initScroll - scroll the view port on load, default true * int:tabIndex - the tab index to give the hidden input element */ function _fnInit(table, datatable, oInit, that) { /* Save scope */ _that = that; /* Capture undefined initialisation and apply the defaults */ if (typeof oInit == 'undefined') { oInit = {}; } if (typeof oInit.focus == 'undefined') { oInit.focus = [0, 0]; } oInit.table = table; $(oInit.table).addClass('KeyTable'); if (typeof oInit.focusClass != 'undefined') { _sFocusClass = oInit.focusClass; } if (typeof datatable != 'undefined') { _oDatatable = datatable; } if (typeof oInit.initScroll == 'undefined') { oInit.initScroll = true; } if (typeof oInit.form == 'undefined') { oInit.form = false; } _bForm = oInit.form; /* Cache the tbody node of interest */ _nBody = oInit.table.getElementsByTagName('tbody')[0]; /* If the table is inside a form, then we need a hidden input box which can be used by the * browser to catch the browser tabbing for our table */ if (_bForm) { var nDiv = document.createElement('div'); _nInput = document.createElement('input'); nDiv.style.height = "1px"; /* Opera requires a little something */ nDiv.style.width = "0px"; nDiv.style.overflow = "hidden"; if (typeof oInit.tabIndex != 'undefined') { _nInput.tabIndex = oInit.tabIndex; } nDiv.appendChild(_nInput); oInit.table.parentNode.insertBefore(nDiv, oInit.table.nextSibling); $(_nInput).focus(function () { /* See if we want to 'tab into' the table or out */ if (!_bInputFocused) { _bKeyCapture = true; _bInputFocused = false; if (typeof oInit.focus.nodeName != "undefined") { _fnSetFocus(oInit.focus, oInit.initScroll); } else { _fnSetFocus(_fnCellFromCoords(oInit.focus[0], oInit.focus[1]), oInit.initScroll); } /* Need to interup the thread for this to work */ setTimeout(function () { _nInput.blur(); }, 0); } }); _bKeyCapture = false; } else { /* Set the initial focus on the table */ if (typeof oInit.focus.nodeName != "undefined") { _fnSetFocus(oInit.focus, oInit.initScroll); } else { _fnSetFocus(_fnCellFromCoords(oInit.focus[0], oInit.focus[1]), oInit.initScroll); } _fnCaptureKeys(); } /* Add event listeners */ $(document).bind("keydown", _fnKey); if (_oDatatable) { $(_oDatatable.nTable).on('click', 'td', _fnClick); } else { $(_nBody).on('click', 'td', _fnClick); } /* Loose table focus when click outside the table */ $(document).click(function (e) { var nTarget = e.target; var bTableClick = false; while (nTarget) { if (nTarget == oInit.table) { bTableClick = true; break; } nTarget = nTarget.parentNode; } if (!bTableClick) { _fnBlur(); } }); } var table, datatable; if (oInit === undefined) { table = $('table.KeyTable')[0]; datatable = null; } else if ($.isPlainObject(oInit)) { table = oInit.table; datatable = oInit.datatable; } else { datatable = new $.fn.dataTable.Api(oInit).settings()[0]; table = datatable.nTable; } /* Initialise our new object */ _fnInit(table, datatable, oInit, this); }; KeyTable.version = "1.2.0"; $.fn.dataTable.KeyTable = KeyTable; $.fn.DataTable.KeyTable = KeyTable; return KeyTable; }; // /factory factory(jQuery, jQuery.fn.dataTable); })(window, document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-keyTable.js
jquery-dataTables-keyTable.js
!function($) { function Inputmask(alias, options) { return this instanceof Inputmask ? ($.isPlainObject(alias) ? options = alias : (options = options || {}, options.alias = alias), this.el = void 0, this.opts = $.extend(!0, {}, this.defaults, options), this.noMasksCache = options && void 0 !== options.definitions, this.userOptions = options || {}, this.events = {}, void resolveAlias(this.opts.alias, options, this.opts)) : new Inputmask(alias, options); } function isInputEventSupported(eventName) { var el = document.createElement("input"), evName = "on" + eventName, isSupported = evName in el; return isSupported || (el.setAttribute(evName, "return;"), isSupported = "function" == typeof el[evName]), el = null, isSupported; } function isElementTypeSupported(input, opts) { var elementType = input.getAttribute("type"), isSupported = "INPUT" === input.tagName && -1 !== $.inArray(elementType, opts.supportsInputType) || input.isContentEditable || "TEXTAREA" === input.tagName; if (!isSupported && "INPUT" === input.tagName) { var el = document.createElement("input"); el.setAttribute("type", elementType), isSupported = "text" === el.type, el = null; } return isSupported; } function resolveAlias(aliasStr, options, opts) { var aliasDefinition = opts.aliases[aliasStr]; return aliasDefinition ? (aliasDefinition.alias && resolveAlias(aliasDefinition.alias, void 0, opts), $.extend(!0, opts, aliasDefinition), $.extend(!0, opts, options), !0) : (null === opts.mask && (opts.mask = aliasStr), !1); } function importAttributeOptions(npt, opts, userOptions) { function importOption(option, optionData) { optionData = void 0 !== optionData ? optionData : npt.getAttribute("data-inputmask-" + option), null !== optionData && ("string" == typeof optionData && (0 === option.indexOf("on") ? optionData = window[optionData] : "false" === optionData ? optionData = !1 : "true" === optionData && (optionData = !0)), userOptions[option] = optionData); } var option, dataoptions, optionData, p, attrOptions = npt.getAttribute("data-inputmask"); if (attrOptions && "" !== attrOptions && (attrOptions = attrOptions.replace(new RegExp("'", "g"), '"'), dataoptions = JSON.parse("{" + attrOptions + "}")), dataoptions) { optionData = void 0; for (p in dataoptions) if ("alias" === p.toLowerCase()) { optionData = dataoptions[p]; break; } } importOption("alias", optionData), userOptions.alias && resolveAlias(userOptions.alias, userOptions, opts); for (option in opts) { if (dataoptions) { optionData = void 0; for (p in dataoptions) if (p.toLowerCase() === option.toLowerCase()) { optionData = dataoptions[p]; break; } } importOption(option, optionData); } return $.extend(!0, opts, userOptions), opts; } function generateMaskSet(opts, nocache) { function analyseMask(mask) { function MaskToken(isGroup, isOptional, isQuantifier, isAlternator) { this.matches = [], this.isGroup = isGroup || !1, this.isOptional = isOptional || !1, this.isQuantifier = isQuantifier || !1, this.isAlternator = isAlternator || !1, this.quantifier = { min: 1, max: 1 }; } function insertTestDefinition(mtoken, element, position) { var maskdef = opts.definitions[element]; position = void 0 !== position ? position : mtoken.matches.length; var prevMatch = mtoken.matches[position - 1]; if (maskdef && !escaped) { maskdef.placeholder = $.isFunction(maskdef.placeholder) ? maskdef.placeholder(opts) : maskdef.placeholder; for (var prevalidators = maskdef.prevalidator, prevalidatorsL = prevalidators ? prevalidators.length : 0, i = 1; i < maskdef.cardinality; i++) { var prevalidator = prevalidatorsL >= i ? prevalidators[i - 1] : [], validator = prevalidator.validator, cardinality = prevalidator.cardinality; mtoken.matches.splice(position++, 0, { fn: validator ? "string" == typeof validator ? new RegExp(validator) : new function() { this.test = validator; }() : new RegExp("."), cardinality: cardinality ? cardinality : 1, optionality: mtoken.isOptional, newBlockMarker: void 0 === prevMatch || prevMatch.def !== (maskdef.definitionSymbol || element), casing: maskdef.casing, def: maskdef.definitionSymbol || element, placeholder: maskdef.placeholder, mask: element }), prevMatch = mtoken.matches[position - 1]; } mtoken.matches.splice(position++, 0, { fn: maskdef.validator ? "string" == typeof maskdef.validator ? new RegExp(maskdef.validator) : new function() { this.test = maskdef.validator; }() : new RegExp("."), cardinality: maskdef.cardinality, optionality: mtoken.isOptional, newBlockMarker: void 0 === prevMatch || prevMatch.def !== (maskdef.definitionSymbol || element), casing: maskdef.casing, def: maskdef.definitionSymbol || element, placeholder: maskdef.placeholder, mask: element }); } else mtoken.matches.splice(position++, 0, { fn: null, cardinality: 0, optionality: mtoken.isOptional, newBlockMarker: void 0 === prevMatch || prevMatch.def !== element, casing: null, def: opts.staticDefinitionSymbol || element, placeholder: void 0 !== opts.staticDefinitionSymbol ? element : void 0, mask: element }), escaped = !1; } function verifyGroupMarker(lastMatch, isOpenGroup) { lastMatch.isGroup && (lastMatch.isGroup = !1, insertTestDefinition(lastMatch, opts.groupmarker.start, 0), isOpenGroup !== !0 && insertTestDefinition(lastMatch, opts.groupmarker.end)); } function maskCurrentToken(m, currentToken, lastMatch, extraCondition) { currentToken.matches.length > 0 && (void 0 === extraCondition || extraCondition) && (lastMatch = currentToken.matches[currentToken.matches.length - 1], verifyGroupMarker(lastMatch)), insertTestDefinition(currentToken, m); } function defaultCase() { if (openenings.length > 0) { if (currentOpeningToken = openenings[openenings.length - 1], maskCurrentToken(m, currentOpeningToken, lastMatch, !currentOpeningToken.isAlternator), currentOpeningToken.isAlternator) { alternator = openenings.pop(); for (var mndx = 0; mndx < alternator.matches.length; mndx++) alternator.matches[mndx].isGroup = !1; openenings.length > 0 ? (currentOpeningToken = openenings[openenings.length - 1], currentOpeningToken.matches.push(alternator)) : currentToken.matches.push(alternator); } } else maskCurrentToken(m, currentToken, lastMatch); } function reverseTokens(maskToken) { function reverseStatic(st) { return st === opts.optionalmarker.start ? st = opts.optionalmarker.end : st === opts.optionalmarker.end ? st = opts.optionalmarker.start : st === opts.groupmarker.start ? st = opts.groupmarker.end : st === opts.groupmarker.end && (st = opts.groupmarker.start), st; } maskToken.matches = maskToken.matches.reverse(); for (var match in maskToken.matches) { var intMatch = parseInt(match); if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) { var qt = maskToken.matches[match]; maskToken.matches.splice(match, 1), maskToken.matches.splice(intMatch + 1, 0, qt); } void 0 !== maskToken.matches[match].matches ? maskToken.matches[match] = reverseTokens(maskToken.matches[match]) : maskToken.matches[match] = reverseStatic(maskToken.matches[match]); } return maskToken; } for (var match, m, openingToken, currentOpeningToken, alternator, lastMatch, groupToken, tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g, escaped = !1, currentToken = new MaskToken(), openenings = [], maskTokens = []; match = tokenizer.exec(mask); ) if (m = match[0], escaped) defaultCase(); else switch (m.charAt(0)) { case opts.escapeChar: escaped = !0; break; case opts.optionalmarker.end: case opts.groupmarker.end: if (openingToken = openenings.pop(), void 0 !== openingToken) if (openenings.length > 0) { if (currentOpeningToken = openenings[openenings.length - 1], currentOpeningToken.matches.push(openingToken), currentOpeningToken.isAlternator) { alternator = openenings.pop(); for (var mndx = 0; mndx < alternator.matches.length; mndx++) alternator.matches[mndx].isGroup = !1; openenings.length > 0 ? (currentOpeningToken = openenings[openenings.length - 1], currentOpeningToken.matches.push(alternator)) : currentToken.matches.push(alternator); } } else currentToken.matches.push(openingToken); else defaultCase(); break; case opts.optionalmarker.start: openenings.push(new MaskToken(!1, !0)); break; case opts.groupmarker.start: openenings.push(new MaskToken(!0)); break; case opts.quantifiermarker.start: var quantifier = new MaskToken(!1, !1, !0); m = m.replace(/[{}]/g, ""); var mq = m.split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = 1 === mq.length ? mq0 : isNaN(mq[1]) ? mq[1] : parseInt(mq[1]); if (("*" === mq1 || "+" === mq1) && (mq0 = "*" === mq1 ? 0 : 1), quantifier.quantifier = { min: mq0, max: mq1 }, openenings.length > 0) { var matches = openenings[openenings.length - 1].matches; match = matches.pop(), match.isGroup || (groupToken = new MaskToken(!0), groupToken.matches.push(match), match = groupToken), matches.push(match), matches.push(quantifier); } else match = currentToken.matches.pop(), match.isGroup || (groupToken = new MaskToken(!0), groupToken.matches.push(match), match = groupToken), currentToken.matches.push(match), currentToken.matches.push(quantifier); break; case opts.alternatormarker: openenings.length > 0 ? (currentOpeningToken = openenings[openenings.length - 1], lastMatch = currentOpeningToken.matches.pop()) : lastMatch = currentToken.matches.pop(), lastMatch.isAlternator ? openenings.push(lastMatch) : (alternator = new MaskToken(!1, !1, !1, !0), alternator.matches.push(lastMatch), openenings.push(alternator)); break; default: defaultCase(); } for (;openenings.length > 0; ) openingToken = openenings.pop(), verifyGroupMarker(openingToken, !0), currentToken.matches.push(openingToken); return currentToken.matches.length > 0 && (lastMatch = currentToken.matches[currentToken.matches.length - 1], verifyGroupMarker(lastMatch), maskTokens.push(currentToken)), opts.numericInput && reverseTokens(maskTokens[0]), maskTokens; } function generateMask(mask, metadata) { if (null === mask || "" === mask) return void 0; if (1 === mask.length && opts.greedy === !1 && 0 !== opts.repeat && (opts.placeholder = ""), opts.repeat > 0 || "*" === opts.repeat || "+" === opts.repeat) { var repeatStart = "*" === opts.repeat ? 0 : "+" === opts.repeat ? 1 : opts.repeat; mask = opts.groupmarker.start + mask + opts.groupmarker.end + opts.quantifiermarker.start + repeatStart + "," + opts.repeat + opts.quantifiermarker.end; } var masksetDefinition; return void 0 === Inputmask.prototype.masksCache[mask] || nocache === !0 ? (masksetDefinition = { mask: mask, maskToken: analyseMask(mask), validPositions: {}, _buffer: void 0, buffer: void 0, tests: {}, metadata: metadata }, nocache !== !0 && (Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask] = masksetDefinition, masksetDefinition = $.extend(!0, {}, Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask]))) : masksetDefinition = $.extend(!0, {}, Inputmask.prototype.masksCache[opts.numericInput ? mask.split("").reverse().join("") : mask]), masksetDefinition; } function preProcessMask(mask) { return mask = mask.toString(); } var ms; if ($.isFunction(opts.mask) && (opts.mask = opts.mask(opts)), $.isArray(opts.mask)) { if (opts.mask.length > 1) { opts.keepStatic = null === opts.keepStatic ? !0 : opts.keepStatic; var altMask = "("; return $.each(opts.numericInput ? opts.mask.reverse() : opts.mask, function(ndx, msk) { altMask.length > 1 && (altMask += ")|("), altMask += preProcessMask(void 0 === msk.mask || $.isFunction(msk.mask) ? msk : msk.mask); }), altMask += ")", generateMask(altMask, opts.mask); } opts.mask = opts.mask.pop(); } return opts.mask && (ms = void 0 === opts.mask.mask || $.isFunction(opts.mask.mask) ? generateMask(preProcessMask(opts.mask), opts.mask) : generateMask(preProcessMask(opts.mask.mask), opts.mask)), ms; } function maskScope(actionObj, maskset, opts) { function getMaskTemplate(baseOnInput, minimalPos, includeInput) { minimalPos = minimalPos || 0; var ndxIntlzr, test, testPos, maskTemplate = [], pos = 0, lvp = getLastValidPosition(); do { if (baseOnInput === !0 && getMaskSet().validPositions[pos]) { var validPos = getMaskSet().validPositions[pos]; test = validPos.match, ndxIntlzr = validPos.locator.slice(), maskTemplate.push(includeInput === !0 ? validPos.input : getPlaceholder(pos, test)); } else testPos = getTestTemplate(pos, ndxIntlzr, pos - 1), test = testPos.match, ndxIntlzr = testPos.locator.slice(), (opts.jitMasking === !1 || lvp > pos || isFinite(opts.jitMasking) && opts.jitMasking > pos) && maskTemplate.push(getPlaceholder(pos, test)); pos++; } while ((void 0 === maxLength || maxLength > pos - 1) && null !== test.fn || null === test.fn && "" !== test.def || minimalPos >= pos); return "" === maskTemplate[maskTemplate.length - 1] && maskTemplate.pop(), maskTemplate; } function getMaskSet() { return maskset; } function resetMaskSet(soft) { var maskset = getMaskSet(); maskset.buffer = void 0, soft !== !0 && (maskset.tests = {}, maskset._buffer = void 0, maskset.validPositions = {}, maskset.p = 0); } function getLastValidPosition(closestTo, strict) { var before = -1, after = -1, valids = getMaskSet().validPositions; void 0 === closestTo && (closestTo = -1); for (var posNdx in valids) { var psNdx = parseInt(posNdx); valids[psNdx] && (strict || null !== valids[psNdx].match.fn) && (closestTo >= psNdx && (before = psNdx), psNdx >= closestTo && (after = psNdx)); } return -1 !== before && closestTo - before > 1 || closestTo > after ? before : after; } function setValidPosition(pos, validTest, fromSetValid, isSelection) { if (isSelection || opts.insertMode && void 0 !== getMaskSet().validPositions[pos] && void 0 === fromSetValid) { var i, positionsClone = $.extend(!0, {}, getMaskSet().validPositions), lvp = getLastValidPosition(); for (i = pos; lvp >= i; i++) delete getMaskSet().validPositions[i]; getMaskSet().validPositions[pos] = validTest; var j, valid = !0, vps = getMaskSet().validPositions; for (i = j = pos; lvp >= i; i++) { var t = positionsClone[i]; if (void 0 !== t) for (var posMatch = j, prevPosMatch = -1; posMatch < getMaskLength() && (null == t.match.fn && vps[i] && (vps[i].match.optionalQuantifier === !0 || vps[i].match.optionality === !0) || null != t.match.fn); ) if (null === t.match.fn || !opts.keepStatic && vps[i] && (void 0 !== vps[i + 1] && getTests(i + 1, vps[i].locator.slice(), i).length > 1 || void 0 !== vps[i].alternation) ? posMatch++ : posMatch = seekNext(j), positionCanMatchDefinition(posMatch, t.match.def)) { var result = isValid(posMatch, t.input, !0, !0); if (valid = result !== !1, j = result.caret || result.insert ? getLastValidPosition() : posMatch, valid) break; } else { if (valid = null == t.match.fn, prevPosMatch === posMatch) break; prevPosMatch = posMatch; } if (!valid) break; } if (!valid) return getMaskSet().validPositions = $.extend(!0, {}, positionsClone), resetMaskSet(!0), !1; } else getMaskSet().validPositions[pos] = validTest; return resetMaskSet(!0), !0; } function stripValidPositions(start, end, nocheck, strict) { function IsEnclosedStatic(pos) { var posMatch = getMaskSet().validPositions[pos]; if (void 0 !== posMatch && null === posMatch.match.fn) { var prevMatch = getMaskSet().validPositions[pos - 1], nextMatch = getMaskSet().validPositions[pos + 1]; return void 0 !== prevMatch && void 0 !== nextMatch; } return !1; } var i, startPos = start; for (getMaskSet().p = start, i = end - 1; i >= startPos; i--) void 0 !== getMaskSet().validPositions[i] && (nocheck === !0 || !IsEnclosedStatic(i) && opts.canClearPosition(getMaskSet(), i, getLastValidPosition(), strict, opts) !== !1) && delete getMaskSet().validPositions[i]; for (resetMaskSet(!0), i = startPos + 1; i <= getLastValidPosition(); ) { for (;void 0 !== getMaskSet().validPositions[startPos]; ) startPos++; var s = getMaskSet().validPositions[startPos]; if (startPos > i && (i = startPos + 1), void 0 === getMaskSet().validPositions[i] && isMask(i) || void 0 !== s) i++; else { var t = getTestTemplate(i); positionCanMatchDefinition(startPos, t.match.def) ? isValid(startPos, t.input || getPlaceholder(i), !0) !== !1 && (delete getMaskSet().validPositions[i], i++) : isMask(i) || (i++, startPos--), startPos++; } } resetMaskSet(!0); } function getTestTemplate(pos, ndxIntlzr, tstPs) { var testPos = getMaskSet().validPositions[pos]; if (void 0 === testPos) for (var testPositions = getTests(pos, ndxIntlzr, tstPs), lvp = getLastValidPosition(), lvTest = getMaskSet().validPositions[lvp] || getTests(0)[0], lvTestAltArr = void 0 !== lvTest.alternation ? lvTest.locator[lvTest.alternation].toString().split(",") : [], ndx = 0; ndx < testPositions.length && (testPos = testPositions[ndx], !(testPos.match && (opts.greedy && testPos.match.optionalQuantifier !== !0 || (testPos.match.optionality === !1 || testPos.match.newBlockMarker === !1) && testPos.match.optionalQuantifier !== !0) && (void 0 === lvTest.alternation || lvTest.alternation !== testPos.alternation || void 0 !== testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAltArr)))); ndx++) ; return testPos; } function getTest(pos) { return getMaskSet().validPositions[pos] ? getMaskSet().validPositions[pos].match : getTests(pos)[0].match; } function positionCanMatchDefinition(pos, def) { for (var valid = !1, tests = getTests(pos), tndx = 0; tndx < tests.length; tndx++) if (tests[tndx].match && tests[tndx].match.def === def) { valid = !0; break; } return valid; } function selectBestMatch(pos, alternateNdx) { var bestMatch, indexPos; return (getMaskSet().tests[pos] || getMaskSet().validPositions[pos]) && $.each(getMaskSet().tests[pos] || [ getMaskSet().validPositions[pos] ], function(ndx, lmnt) { var ndxPos = lmnt.alternation ? lmnt.locator[lmnt.alternation].toString().indexOf(alternateNdx) : -1; (void 0 === indexPos || indexPos > ndxPos) && -1 !== ndxPos && (bestMatch = lmnt, indexPos = ndxPos); }), bestMatch; } function getTests(pos, ndxIntlzr, tstPs) { function resolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) { function handleMatch(match, loopNdx, quantifierRecurse) { function isFirstMatch(latestMatch, tokenGroup) { var firstMatch = 0 === $.inArray(latestMatch, tokenGroup.matches); return firstMatch || $.each(tokenGroup.matches, function(ndx, match) { return match.isQuantifier === !0 && (firstMatch = isFirstMatch(latestMatch, tokenGroup.matches[ndx - 1])) ? !1 : void 0; }), firstMatch; } function resolveNdxInitializer(pos, alternateNdx) { var bestMatch = selectBestMatch(pos, alternateNdx); return bestMatch ? bestMatch.locator.slice(bestMatch.alternation + 1) : []; } if (testPos > 1e4) throw "Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + getMaskSet().mask; if (testPos === pos && void 0 === match.matches) return matches.push({ match: match, locator: loopNdx.reverse(), cd: cacheDependency }), !0; if (void 0 !== match.matches) { if (match.isGroup && quantifierRecurse !== match) { if (match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx)) return !0; } else if (match.isOptional) { var optionalToken = match; if (match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse)) { if (latestMatch = matches[matches.length - 1].match, !isFirstMatch(latestMatch, optionalToken)) return !0; insertStop = !0, testPos = pos; } } else if (match.isAlternator) { var maltMatches, alternateToken = match, malternateMatches = [], currentMatches = matches.slice(), loopNdxCnt = loopNdx.length, altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1; if (-1 === altIndex || "string" == typeof altIndex) { var amndx, currentPos = testPos, ndxInitializerClone = ndxInitializer.slice(), altIndexArr = []; if ("string" == typeof altIndex) altIndexArr = altIndex.split(","); else for (amndx = 0; amndx < alternateToken.matches.length; amndx++) altIndexArr.push(amndx); for (var ndx = 0; ndx < altIndexArr.length; ndx++) { if (amndx = parseInt(altIndexArr[ndx]), matches = [], ndxInitializer = resolveNdxInitializer(testPos, amndx), match = handleMatch(alternateToken.matches[amndx] || maskToken.matches[amndx], [ amndx ].concat(loopNdx), quantifierRecurse) || match, match !== !0 && void 0 !== match && altIndexArr[altIndexArr.length - 1] < alternateToken.matches.length) { var ntndx = $.inArray(match, maskToken.matches) + 1; maskToken.matches.length > ntndx && (match = handleMatch(maskToken.matches[ntndx], [ ntndx ].concat(loopNdx.slice(1, loopNdx.length)), quantifierRecurse), match && (altIndexArr.push(ntndx.toString()), $.each(matches, function(ndx, lmnt) { lmnt.alternation = loopNdx.length - 1; }))); } maltMatches = matches.slice(), testPos = currentPos, matches = []; for (var i = 0; i < ndxInitializerClone.length; i++) ndxInitializer[i] = ndxInitializerClone[i]; for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) { var altMatch = maltMatches[ndx1]; altMatch.alternation = altMatch.alternation || loopNdxCnt; for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) { var altMatch2 = malternateMatches[ndx2]; if (altMatch.match.def === altMatch2.match.def && ("string" != typeof altIndex || -1 !== $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr))) { altMatch.match.mask === altMatch2.match.mask && (maltMatches.splice(ndx1, 1), ndx1--), -1 === altMatch2.locator[altMatch.alternation].toString().indexOf(altMatch.locator[altMatch.alternation]) && (altMatch2.locator[altMatch.alternation] = altMatch2.locator[altMatch.alternation] + "," + altMatch.locator[altMatch.alternation], altMatch2.alternation = altMatch.alternation); break; } } } malternateMatches = malternateMatches.concat(maltMatches); } "string" == typeof altIndex && (malternateMatches = $.map(malternateMatches, function(lmnt, ndx) { if (isFinite(ndx)) { var mamatch, alternation = lmnt.alternation, altLocArr = lmnt.locator[alternation].toString().split(","); lmnt.locator[alternation] = void 0, lmnt.alternation = void 0; for (var alndx = 0; alndx < altLocArr.length; alndx++) mamatch = -1 !== $.inArray(altLocArr[alndx], altIndexArr), mamatch && (void 0 !== lmnt.locator[alternation] ? (lmnt.locator[alternation] += ",", lmnt.locator[alternation] += altLocArr[alndx]) : lmnt.locator[alternation] = parseInt(altLocArr[alndx]), lmnt.alternation = alternation); if (void 0 !== lmnt.locator[alternation]) return lmnt; } })), matches = currentMatches.concat(malternateMatches), testPos = pos, insertStop = matches.length > 0; } else match = handleMatch(alternateToken.matches[altIndex] || maskToken.matches[altIndex], [ altIndex ].concat(loopNdx), quantifierRecurse); if (match) return !0; } else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) for (var qt = match, qndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max) && pos >= testPos; qndx++) { var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1]; if (match = handleMatch(tokenGroup, [ qndx ].concat(loopNdx), tokenGroup)) { if (latestMatch = matches[matches.length - 1].match, latestMatch.optionalQuantifier = qndx > qt.quantifier.min - 1, isFirstMatch(latestMatch, tokenGroup)) { if (qndx > qt.quantifier.min - 1) { insertStop = !0, testPos = pos; break; } return !0; } return !0; } } else if (match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse)) return !0; } else testPos++; } for (var tndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; tndx < maskToken.matches.length; tndx++) if (maskToken.matches[tndx].isQuantifier !== !0) { var match = handleMatch(maskToken.matches[tndx], [ tndx ].concat(loopNdx), quantifierRecurse); if (match && testPos === pos) return match; if (testPos > pos) break; } } function mergeLocators(tests) { var test = tests[0] || tests; return test.locator.slice(); } var latestMatch, maskTokens = getMaskSet().maskToken, testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr || [ 0 ], matches = [], insertStop = !1, cacheDependency = ndxIntlzr ? ndxIntlzr.join("") : ""; if (pos > -1) { if (void 0 === ndxIntlzr) { for (var test, previousPos = pos - 1; void 0 === (test = getMaskSet().validPositions[previousPos] || getMaskSet().tests[previousPos]) && previousPos > -1; ) previousPos--; void 0 !== test && previousPos > -1 && (ndxInitializer = mergeLocators(test), cacheDependency = ndxInitializer.join(""), test = test[0] || test, testPos = previousPos); } if (getMaskSet().tests[pos] && getMaskSet().tests[pos][0].cd === cacheDependency) return getMaskSet().tests[pos]; for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) { var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [ mtndx ]); if (match && testPos === pos || testPos > pos) break; } } return (0 === matches.length || insertStop) && matches.push({ match: { fn: null, cardinality: 0, optionality: !0, casing: null, def: "" }, locator: [] }), getMaskSet().tests[pos] = $.extend(!0, [], matches), getMaskSet().tests[pos]; } function getBufferTemplate() { return void 0 === getMaskSet()._buffer && (getMaskSet()._buffer = getMaskTemplate(!1, 1)), getMaskSet()._buffer; } function getBuffer(noCache) { if (void 0 === getMaskSet().buffer || noCache === !0) { if (noCache === !0) for (var testNdx in getMaskSet().tests) void 0 === getMaskSet().validPositions[testNdx] && delete getMaskSet().tests[testNdx]; getMaskSet().buffer = getMaskTemplate(!0, getLastValidPosition(), !0); } return getMaskSet().buffer; } function refreshFromBuffer(start, end, buffer) { var i; if (buffer = buffer, start === !0) resetMaskSet(), start = 0, end = buffer.length; else for (i = start; end > i; i++) delete getMaskSet().validPositions[i], delete getMaskSet().tests[i]; for (i = start; end > i; i++) resetMaskSet(!0), buffer[i] !== opts.skipOptionalPartCharacter && isValid(i, buffer[i], !0, !0); } function casing(elem, test) { switch (test.casing) { case "upper": elem = elem.toUpperCase(); break; case "lower": elem = elem.toLowerCase(); } return elem; } function checkAlternationMatch(altArr1, altArr2) { for (var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1), isMatch = !1, alndx = 0; alndx < altArr1.length; alndx++) if (-1 !== $.inArray(altArr1[alndx], altArrC)) { isMatch = !0; break; } return isMatch; } function isValid(pos, c, strict, fromSetValid) { function isSelection(posObj) { return isRTL ? posObj.begin - posObj.end > 1 || posObj.begin - posObj.end === 1 && opts.insertMode : posObj.end - posObj.begin > 1 || posObj.end - posObj.begin === 1 && opts.insertMode; } function _isValid(position, c, strict, fromSetValid) { var rslt = !1; return $.each(getTests(position), function(ndx, tst) { for (var test = tst.match, loopend = c ? 1 : 0, chrs = "", i = test.cardinality; i > loopend; i--) chrs += getBufferElement(position - (i - 1)); if (c && (chrs += c), getBuffer(!0), rslt = null != test.fn ? test.fn.test(chrs, getMaskSet(), position, strict, opts) : c !== test.def && c !== opts.skipOptionalPartCharacter || "" === test.def ? !1 : { c: test.placeholder || test.def, pos: position }, rslt !== !1) { var elem = void 0 !== rslt.c ? rslt.c : c; elem = elem === opts.skipOptionalPartCharacter && null === test.fn ? test.placeholder || test.def : elem; var validatedPos = position, possibleModifiedBuffer = getBuffer(); if (void 0 !== rslt.remove && ($.isArray(rslt.remove) || (rslt.remove = [ rslt.remove ]), $.each(rslt.remove.sort(function(a, b) { return b - a; }), function(ndx, lmnt) { stripValidPositions(lmnt, lmnt + 1, !0); })), void 0 !== rslt.insert && ($.isArray(rslt.insert) || (rslt.insert = [ rslt.insert ]), $.each(rslt.insert.sort(function(a, b) { return a - b; }), function(ndx, lmnt) { isValid(lmnt.pos, lmnt.c, !1, fromSetValid); })), rslt.refreshFromBuffer) { var refresh = rslt.refreshFromBuffer; if (strict = !0, refreshFromBuffer(refresh === !0 ? refresh : refresh.start, refresh.end, possibleModifiedBuffer), void 0 === rslt.pos && void 0 === rslt.c) return rslt.pos = getLastValidPosition(), !1; if (validatedPos = void 0 !== rslt.pos ? rslt.pos : position, validatedPos !== position) return rslt = $.extend(rslt, isValid(validatedPos, elem, !0, fromSetValid)), !1; } else if (rslt !== !0 && void 0 !== rslt.pos && rslt.pos !== position && (validatedPos = rslt.pos, refreshFromBuffer(position, validatedPos, getBuffer().slice()), validatedPos !== position)) return rslt = $.extend(rslt, isValid(validatedPos, elem, !0)), !1; return rslt !== !0 && void 0 === rslt.pos && void 0 === rslt.c ? !1 : (ndx > 0 && resetMaskSet(!0), setValidPosition(validatedPos, $.extend({}, tst, { input: casing(elem, test) }), fromSetValid, isSelection(pos)) || (rslt = !1), !1); } }), rslt; } function alternate(pos, c, strict, fromSetValid) { for (var lastAlt, alternation, isValidRslt, altPos, i, validPos, validPsClone = $.extend(!0, {}, getMaskSet().validPositions), testsClone = $.extend(!0, {}, getMaskSet().tests), lAlt = getLastValidPosition(); lAlt >= 0 && (altPos = getMaskSet().validPositions[lAlt], !altPos || void 0 === altPos.alternation || (lastAlt = lAlt, alternation = getMaskSet().validPositions[lastAlt].alternation, getTestTemplate(lastAlt).locator[altPos.alternation] === altPos.locator[altPos.alternation])); lAlt--) ; if (void 0 !== alternation) { lastAlt = parseInt(lastAlt); for (var decisionPos in getMaskSet().validPositions) if (decisionPos = parseInt(decisionPos), altPos = getMaskSet().validPositions[decisionPos], decisionPos >= lastAlt && void 0 !== altPos.alternation) { var altNdxs; 0 === lastAlt ? (altNdxs = [], $.each(getMaskSet().tests[lastAlt], function(ndx, test) { void 0 !== test.locator[alternation] && (altNdxs = altNdxs.concat(test.locator[alternation].toString().split(","))); })) : altNdxs = getMaskSet().validPositions[lastAlt].locator[alternation].toString().split(","); var decisionTaker = void 0 !== altPos.locator[alternation] ? altPos.locator[alternation] : altNdxs[0]; decisionTaker.length > 0 && (decisionTaker = decisionTaker.split(",")[0]); for (var mndx = 0; mndx < altNdxs.length; mndx++) { var validInputs = [], staticInputsBeforePos = 0, staticInputsBeforePosAlternate = 0; if (decisionTaker < altNdxs[mndx]) { for (var possibilityPos, possibilities, dp = decisionPos; dp >= 0; dp--) if (possibilityPos = getMaskSet().validPositions[dp], void 0 !== possibilityPos) { var bestMatch = selectBestMatch(dp, altNdxs[mndx]); getMaskSet().validPositions[dp].match.def !== bestMatch.match.def && (validInputs.push(getMaskSet().validPositions[dp].input), getMaskSet().validPositions[dp] = bestMatch, getMaskSet().validPositions[dp].input = getPlaceholder(dp), null === getMaskSet().validPositions[dp].match.fn && staticInputsBeforePosAlternate++, possibilityPos = bestMatch), possibilities = possibilityPos.locator[alternation], possibilityPos.locator[alternation] = parseInt(altNdxs[mndx]); break; } if (decisionTaker !== possibilityPos.locator[alternation]) { for (i = decisionPos + 1; i < getLastValidPosition(void 0, !0) + 1; i++) validPos = getMaskSet().validPositions[i], validPos && null != validPos.match.fn ? validInputs.push(validPos.input) : pos > i && staticInputsBeforePos++, delete getMaskSet().validPositions[i], delete getMaskSet().tests[i]; for (resetMaskSet(!0), opts.keepStatic = !opts.keepStatic, isValidRslt = !0; validInputs.length > 0; ) { var input = validInputs.shift(); if (input !== opts.skipOptionalPartCharacter && !(isValidRslt = isValid(getLastValidPosition(void 0, !0) + 1, input, !1, fromSetValid))) break; } if (possibilityPos.alternation = alternation, possibilityPos.locator[alternation] = possibilities, isValidRslt) { var targetLvp = getLastValidPosition(pos) + 1; for (i = decisionPos + 1; i < getLastValidPosition() + 1; i++) validPos = getMaskSet().validPositions[i], (void 0 === validPos || null == validPos.match.fn) && pos > i && staticInputsBeforePosAlternate++; pos += staticInputsBeforePosAlternate - staticInputsBeforePos, isValidRslt = isValid(pos > targetLvp ? targetLvp : pos, c, strict, fromSetValid); } if (opts.keepStatic = !opts.keepStatic, isValidRslt) return isValidRslt; resetMaskSet(), getMaskSet().validPositions = $.extend(!0, {}, validPsClone), getMaskSet().tests = $.extend(!0, {}, testsClone); } } } break; } } return !1; } function trackbackAlternations(originalPos, newPos) { for (var vp = getMaskSet().validPositions[newPos], targetLocator = vp.locator, tll = targetLocator.length, ps = originalPos; newPos > ps; ps++) if (void 0 === getMaskSet().validPositions[ps] && !isMask(ps, !0)) { var tests = getTests(ps), bestMatch = tests[0], equality = -1; $.each(tests, function(ndx, tst) { for (var i = 0; tll > i && (void 0 !== tst.locator[i] && checkAlternationMatch(tst.locator[i].toString().split(","), targetLocator[i].toString().split(","))); i++) i > equality && (equality = i, bestMatch = tst); }), setValidPosition(ps, $.extend({}, bestMatch, { input: bestMatch.match.placeholder || bestMatch.match.def }), !0); } } strict = strict === !0; var maskPos = pos; void 0 !== pos.begin && (maskPos = isRTL && !isSelection(pos) ? pos.end : pos.begin); for (var result = !1, positionsClone = $.extend(!0, {}, getMaskSet().validPositions), pndx = maskPos - 1; pndx > -1 && !getMaskSet().validPositions[pndx]; pndx--) ; pndx++; for (var testTemplate; maskPos > pndx; pndx++) getBuffer(), void 0 === getMaskSet().validPositions[pndx] && ((testTemplate = getTestTemplate(pndx)).match.def === opts.radixPointDefinitionSymbol || !isMask(pndx, !0) || $.inArray(opts.radixPoint, getBuffer()) < pndx && testTemplate.match.fn && testTemplate.match.fn.test(getPlaceholder(pndx), getMaskSet(), pndx, !1, opts)) && _isValid(pndx, testTemplate.match.placeholder || (null == testTemplate.match.fn ? testTemplate.match.def : getPlaceholder(pndx)), !0, fromSetValid); if (isSelection(pos) && (handleRemove(void 0, Inputmask.keyCode.DELETE, pos), maskPos = getMaskSet().p), maskPos < getMaskLength() && (result = _isValid(maskPos, c, strict, fromSetValid), (!strict || fromSetValid === !0) && result === !1)) { var currentPosValid = getMaskSet().validPositions[maskPos]; if (!currentPosValid || null !== currentPosValid.match.fn || currentPosValid.match.def !== c && c !== opts.skipOptionalPartCharacter) { if ((opts.insertMode || void 0 === getMaskSet().validPositions[seekNext(maskPos)]) && !isMask(maskPos, !0)) { var staticChar = getTestTemplate(maskPos).match; staticChar = staticChar.placeholder || staticChar.def, _isValid(maskPos, staticChar, strict, fromSetValid); for (var nPos = maskPos + 1, snPos = seekNext(maskPos); snPos >= nPos; nPos++) if (result = _isValid(nPos, c, strict, fromSetValid), result !== !1) { trackbackAlternations(maskPos, nPos), maskPos = nPos; break; } } } else result = { caret: seekNext(maskPos) }; } return result === !1 && opts.keepStatic && (result = alternate(maskPos, c, strict, fromSetValid)), result === !0 && (result = { pos: maskPos }), $.isFunction(opts.postValidation) && result !== !1 && !strict && fromSetValid !== !0 && (result = opts.postValidation(getBuffer(!0), result, opts) ? result : !1), void 0 === result.pos && (result.pos = maskPos), result === !1 && (resetMaskSet(!0), getMaskSet().validPositions = $.extend(!0, {}, positionsClone)), result; } function isMask(pos, strict) { var test; if (strict ? (test = getTestTemplate(pos).match, "" === test.def && (test = getTest(pos))) : test = getTest(pos), null != test.fn) return test.fn; if (strict !== !0 && pos > -1 && !opts.keepStatic && void 0 === getMaskSet().validPositions[pos]) { var tests = getTests(pos); return tests.length > 2; } return !1; } function getMaskLength() { var maskLength; maxLength = void 0 !== el ? el.maxLength : void 0, -1 === maxLength && (maxLength = void 0); var pos, lvp = getLastValidPosition(), testPos = getMaskSet().validPositions[lvp], ndxIntlzr = void 0 !== testPos ? testPos.locator.slice() : void 0; for (pos = lvp + 1; void 0 === testPos || null !== testPos.match.fn || null === testPos.match.fn && "" !== testPos.match.def; pos++) testPos = getTestTemplate(pos, ndxIntlzr, pos - 1), ndxIntlzr = testPos.locator.slice(); var lastTest = getTest(pos - 1); return maskLength = "" !== lastTest.def ? pos : pos - 1, void 0 === maxLength || maxLength > maskLength ? maskLength : maxLength; } function seekNext(pos, newBlock) { var maskL = getMaskLength(); if (pos >= maskL) return maskL; for (var position = pos; ++position < maskL && (newBlock === !0 && (getTest(position).newBlockMarker !== !0 || !isMask(position)) || newBlock !== !0 && !isMask(position) && (opts.nojumps !== !0 || opts.nojumpsThreshold > position)); ) ; return position; } function seekPrevious(pos, newBlock) { var position = pos; if (0 >= position) return 0; for (;--position > 0 && (newBlock === !0 && getTest(position).newBlockMarker !== !0 || newBlock !== !0 && !isMask(position)); ) ; return position; } function getBufferElement(position) { return void 0 === getMaskSet().validPositions[position] ? getPlaceholder(position) : getMaskSet().validPositions[position].input; } function writeBuffer(input, buffer, caretPos, event, triggerInputEvent) { if (event && $.isFunction(opts.onBeforeWrite)) { var result = opts.onBeforeWrite(event, buffer, caretPos, opts); if (result) { if (result.refreshFromBuffer) { var refresh = result.refreshFromBuffer; refreshFromBuffer(refresh === !0 ? refresh : refresh.start, refresh.end, result.buffer || buffer), buffer = getBuffer(!0); } void 0 !== caretPos && (caretPos = void 0 !== result.caret ? result.caret : caretPos); } } input.inputmask._valueSet(buffer.join("")), void 0 === caretPos || void 0 !== event && "blur" === event.type || caret(input, caretPos), triggerInputEvent === !0 && (skipInputEvent = !0, $(input).trigger("input")); } function getPlaceholder(pos, test) { if (test = test || getTest(pos), void 0 !== test.placeholder) return test.placeholder; if (null === test.fn) { if (pos > -1 && !opts.keepStatic && void 0 === getMaskSet().validPositions[pos]) { var prevTest, tests = getTests(pos), staticAlternations = 0; if (tests.length > 2) for (var i = 0; i < tests.length; i++) if (tests[i].match.optionality !== !0 && tests[i].match.optionalQuantifier !== !0 && (null === tests[i].match.fn || void 0 === prevTest || tests[i].match.fn.test(prevTest.match.def, getMaskSet(), pos, !0, opts) !== !1) && (staticAlternations++, null === tests[i].match.fn && (prevTest = tests[i]), staticAlternations > 1)) return opts.placeholder.charAt(pos % opts.placeholder.length); } return test.def; } return opts.placeholder.charAt(pos % opts.placeholder.length); } function checkVal(input, writeOut, strict, nptvl) { function isTemplateMatch() { var isMatch = !1, charCodeNdx = getBufferTemplate().slice(initialNdx, seekNext(initialNdx)).join("").indexOf(charCodes); if (-1 !== charCodeNdx && !isMask(initialNdx)) { isMatch = !0; for (var bufferTemplateArr = getBufferTemplate().slice(initialNdx, initialNdx + charCodeNdx), i = 0; i < bufferTemplateArr.length; i++) if (" " !== bufferTemplateArr[i]) { isMatch = !1; break; } } return isMatch; } var inputValue = nptvl.slice(), charCodes = "", initialNdx = 0; if (resetMaskSet(), getMaskSet().p = seekNext(-1), !strict) if (opts.autoUnmask !== !0) { var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""), matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g")); matches && matches.length > 0 && (inputValue.splice(0, matches.length * staticInput.length), initialNdx = seekNext(initialNdx)); } else initialNdx = seekNext(initialNdx); $.each(inputValue, function(ndx, charCode) { if (void 0 !== charCode) { var keypress = new $.Event("keypress"); keypress.which = charCode.charCodeAt(0), charCodes += charCode; var lvp = getLastValidPosition(void 0, !0), lvTest = getMaskSet().validPositions[lvp], nextTest = getTestTemplate(lvp + 1, lvTest ? lvTest.locator.slice() : void 0, lvp); if (!isTemplateMatch() || strict || opts.autoUnmask) { var pos = strict ? ndx : null == nextTest.match.fn && nextTest.match.optionality && lvp + 1 < getMaskSet().p ? lvp + 1 : getMaskSet().p; keypressEvent.call(input, keypress, !0, !1, strict, pos), initialNdx = pos + 1, charCodes = ""; } else keypressEvent.call(input, keypress, !0, !1, !0, lvp + 1); } }), writeOut && writeBuffer(input, getBuffer(), document.activeElement === input ? seekNext(getLastValidPosition(0)) : void 0, new $.Event("checkval")); } function unmaskedvalue(input) { if (input && void 0 === input.inputmask) return input.value; var umValue = [], vps = getMaskSet().validPositions; for (var pndx in vps) vps[pndx].match && null != vps[pndx].match.fn && umValue.push(vps[pndx].input); var unmaskedValue = 0 === umValue.length ? null : (isRTL ? umValue.reverse() : umValue).join(""); if (null !== unmaskedValue) { var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join(""); $.isFunction(opts.onUnMask) && (unmaskedValue = opts.onUnMask(bufferValue, unmaskedValue, opts) || unmaskedValue); } return unmaskedValue; } function caret(input, begin, end, notranslate) { function translatePosition(pos) { if (notranslate !== !0 && isRTL && "number" == typeof pos && (!opts.greedy || "" !== opts.placeholder)) { var bffrLght = getBuffer().join("").length; pos = bffrLght - pos; } return pos; } var range; if ("number" != typeof begin) return input.setSelectionRange ? (begin = input.selectionStart, end = input.selectionEnd) : window.getSelection ? (range = window.getSelection().getRangeAt(0), (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) && (begin = range.startOffset, end = range.endOffset)) : document.selection && document.selection.createRange && (range = document.selection.createRange(), begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length), end = begin + range.text.length), { begin: translatePosition(begin), end: translatePosition(end) }; begin = translatePosition(begin), end = translatePosition(end), end = "number" == typeof end ? end : begin; var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end; if (input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0, mobile || opts.insertMode !== !1 || begin !== end || end++, input.setSelectionRange) input.selectionStart = begin, input.selectionEnd = end; else if (window.getSelection) { if (range = document.createRange(), void 0 === input.firstChild || null === input.firstChild) { var textNode = document.createTextNode(""); input.appendChild(textNode); } range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length), range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length), range.collapse(!0); var sel = window.getSelection(); sel.removeAllRanges(), sel.addRange(range); } else input.createTextRange && (range = input.createTextRange(), range.collapse(!0), range.moveEnd("character", end), range.moveStart("character", begin), range.select()); } function determineLastRequiredPosition(returnDefinition) { var pos, testPos, buffer = getBuffer(), bl = buffer.length, lvp = getLastValidPosition(), positions = {}, lvTest = getMaskSet().validPositions[lvp], ndxIntlzr = void 0 !== lvTest ? lvTest.locator.slice() : void 0; for (pos = lvp + 1; pos < buffer.length; pos++) testPos = getTestTemplate(pos, ndxIntlzr, pos - 1), ndxIntlzr = testPos.locator.slice(), positions[pos] = $.extend(!0, {}, testPos); var lvTestAlt = lvTest && void 0 !== lvTest.alternation ? lvTest.locator[lvTest.alternation] : void 0; for (pos = bl - 1; pos > lvp && (testPos = positions[pos], (testPos.match.optionality || testPos.match.optionalQuantifier || lvTestAlt && (lvTestAlt !== positions[pos].locator[lvTest.alternation] && null != testPos.match.fn || null === testPos.match.fn && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && "" !== getTests(pos)[0].def)) && buffer[pos] === getPlaceholder(pos, testPos.match)); pos--) bl--; return returnDefinition ? { l: bl, def: positions[bl] ? positions[bl].match : void 0 } : bl; } function clearOptionalTail(buffer) { for (var rl = determineLastRequiredPosition(), lmib = buffer.length - 1; lmib > rl && !isMask(lmib); lmib--) ; return buffer.splice(rl, lmib + 1 - rl), buffer; } function isComplete(buffer) { if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts); if ("*" === opts.repeat) return void 0; var complete = !1, lrp = determineLastRequiredPosition(!0), aml = seekPrevious(lrp.l); if (void 0 === lrp.def || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) { complete = !0; for (var i = 0; aml >= i; i++) { var test = getTestTemplate(i).match; if (null !== test.fn && void 0 === getMaskSet().validPositions[i] && test.optionality !== !0 && test.optionalQuantifier !== !0 || null === test.fn && buffer[i] !== getPlaceholder(i, test)) { complete = !1; break; } } } return complete; } function patchValueProperty(npt) { function patchValhook(type) { if ($.valHooks && (void 0 === $.valHooks[type] || $.valHooks[type].inputmaskpatch !== !0)) { var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function(elem) { return elem.value; }, valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function(elem, value) { return elem.value = value, elem; }; $.valHooks[type] = { get: function(elem) { if (elem.inputmask) { if (elem.inputmask.opts.autoUnmask) return elem.inputmask.unmaskedvalue(); var result = valhookGet(elem), maskset = elem.inputmask.maskset, bufferTemplate = maskset._buffer; return bufferTemplate = bufferTemplate ? bufferTemplate.join("") : "", result !== bufferTemplate ? result : ""; } return valhookGet(elem); }, set: function(elem, value) { var result, $elem = $(elem); return result = valhookSet(elem, value), elem.inputmask && $elem.trigger("setvalue"), result; }, inputmaskpatch: !0 }; } } function getter() { return this.inputmask ? this.inputmask.opts.autoUnmask ? this.inputmask.unmaskedvalue() : valueGet.call(this) !== getBufferTemplate().join("") ? document.activeElement === this && opts.clearMaskOnLostFocus ? (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") : valueGet.call(this) : "" : valueGet.call(this); } function setter(value) { valueSet.call(this, value), this.inputmask && $(this).trigger("setvalue"); } function installNativeValueSetFallback(npt) { EventRuler.on(npt, "mouseenter", function(event) { var $input = $(this), input = this, value = input.inputmask._valueGet(); value !== getBuffer().join("") && $input.trigger("setvalue"); }); } var valueGet, valueSet; if (!npt.inputmask.__valueGet) { if (Object.getOwnPropertyDescriptor) { var valueProperty = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value"); valueProperty && valueProperty.get && valueProperty.set ? (valueGet = valueProperty.get, valueSet = valueProperty.set, Object.defineProperty(npt, "value", { get: getter, set: setter, configurable: !0 })) : "INPUT" !== npt.tagName && (valueGet = function() { return this.textContent; }, valueSet = function(value) { this.textContent = value; }, Object.defineProperty(npt, "value", { get: getter, set: setter, configurable: !0 })); } else document.__lookupGetter__ && npt.__lookupGetter__("value") && (valueGet = npt.__lookupGetter__("value"), valueSet = npt.__lookupSetter__("value"), npt.__defineGetter__("value", getter), npt.__defineSetter__("value", setter)); void 0 === valueGet && (valueGet = function() { return npt.value; }, valueSet = function(value) { npt.value = value; }, patchValhook(npt.type), installNativeValueSetFallback(npt)), npt.inputmask.__valueGet = valueGet, npt.inputmask._valueGet = function(overruleRTL) { return isRTL && overruleRTL !== !0 ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el); }, npt.inputmask.__valueSet = valueSet, npt.inputmask._valueSet = function(value, overruleRTL) { valueSet.call(this.el, null === value || void 0 === value ? "" : overruleRTL !== !0 && isRTL ? value.split("").reverse().join("") : value); }; } } function handleRemove(input, k, pos, strict) { function generalize() { if (opts.keepStatic) { resetMaskSet(!0); var lastAlt, validInputs = [], positionsClone = $.extend(!0, {}, getMaskSet().validPositions); for (lastAlt = getLastValidPosition(); lastAlt >= 0; lastAlt--) { var validPos = getMaskSet().validPositions[lastAlt]; if (validPos && (null != validPos.match.fn && validInputs.push(validPos.input), delete getMaskSet().validPositions[lastAlt], void 0 !== validPos.alternation && validPos.locator[validPos.alternation] === getTestTemplate(lastAlt).locator[validPos.alternation])) break; } if (lastAlt > -1) for (;validInputs.length > 0; ) { getMaskSet().p = seekNext(getLastValidPosition()); var keypress = new $.Event("keypress"); keypress.which = validInputs.pop().charCodeAt(0), keypressEvent.call(input, keypress, !0, !1, !1, getMaskSet().p); } else getMaskSet().validPositions = $.extend(!0, {}, positionsClone); } } if ((opts.numericInput || isRTL) && (k === Inputmask.keyCode.BACKSPACE ? k = Inputmask.keyCode.DELETE : k === Inputmask.keyCode.DELETE && (k = Inputmask.keyCode.BACKSPACE), isRTL)) { var pend = pos.end; pos.end = pos.begin, pos.begin = pend; } k === Inputmask.keyCode.BACKSPACE && (pos.end - pos.begin < 1 || opts.insertMode === !1) ? (pos.begin = seekPrevious(pos.begin), void 0 === getMaskSet().validPositions[pos.begin] || getMaskSet().validPositions[pos.begin].input !== opts.groupSeparator && getMaskSet().validPositions[pos.begin].input !== opts.radixPoint || pos.begin--) : k === Inputmask.keyCode.DELETE && pos.begin === pos.end && (pos.end = isMask(pos.end) ? pos.end + 1 : seekNext(pos.end) + 1, void 0 === getMaskSet().validPositions[pos.begin] || getMaskSet().validPositions[pos.begin].input !== opts.groupSeparator && getMaskSet().validPositions[pos.begin].input !== opts.radixPoint || pos.end++), stripValidPositions(pos.begin, pos.end, !1, strict), strict !== !0 && generalize(); var lvp = getLastValidPosition(pos.begin); lvp < pos.begin ? (-1 === lvp && resetMaskSet(), getMaskSet().p = seekNext(lvp)) : strict !== !0 && (getMaskSet().p = pos.begin); } function keydownEvent(e) { var input = this, $input = $(input), k = e.keyCode, pos = caret(input); if (k === Inputmask.keyCode.BACKSPACE || k === Inputmask.keyCode.DELETE || iphone && k === Inputmask.keyCode.BACKSPACE_SAFARI || e.ctrlKey && k === Inputmask.keyCode.X && !isInputEventSupported("cut")) e.preventDefault(), handleRemove(input, k, pos), writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join("")), input.inputmask._valueGet() === getBufferTemplate().join("") ? $input.trigger("cleared") : isComplete(getBuffer()) === !0 && $input.trigger("complete"), opts.showTooltip && (input.title = opts.tooltip || getMaskSet().mask); else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) { e.preventDefault(); var caretPos = seekNext(getLastValidPosition()); opts.insertMode || caretPos !== getMaskLength() || e.shiftKey || caretPos--, caret(input, e.shiftKey ? pos.begin : caretPos, caretPos, !0); } else k === Inputmask.keyCode.HOME && !e.shiftKey || k === Inputmask.keyCode.PAGE_UP ? (e.preventDefault(), caret(input, 0, e.shiftKey ? pos.begin : 0, !0)) : (opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE || 90 === k && e.ctrlKey) && e.altKey !== !0 ? (checkVal(input, !0, !1, undoValue.split("")), $input.trigger("click")) : k !== Inputmask.keyCode.INSERT || e.shiftKey || e.ctrlKey ? opts.tabThrough === !0 && k === Inputmask.keyCode.TAB ? (e.shiftKey === !0 ? (null === getTest(pos.begin).fn && (pos.begin = seekNext(pos.begin)), pos.end = seekPrevious(pos.begin, !0), pos.begin = seekPrevious(pos.end, !0)) : (pos.begin = seekNext(pos.begin, !0), pos.end = seekNext(pos.begin, !0), pos.end < getMaskLength() && pos.end--), pos.begin < getMaskLength() && (e.preventDefault(), caret(input, pos.begin, pos.end))) : opts.insertMode !== !1 || e.shiftKey || (k === Inputmask.keyCode.RIGHT ? setTimeout(function() { var caretPos = caret(input); caret(input, caretPos.begin); }, 0) : k === Inputmask.keyCode.LEFT && setTimeout(function() { var caretPos = caret(input); caret(input, isRTL ? caretPos.begin + 1 : caretPos.begin - 1); }, 0)) : (opts.insertMode = !opts.insertMode, caret(input, opts.insertMode || pos.begin !== getMaskLength() ? pos.begin : pos.begin - 1)); opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts), ignorable = -1 !== $.inArray(k, opts.ignorables); } function keypressEvent(e, checkval, writeOut, strict, ndx) { var input = this, $input = $(input), k = e.which || e.charCode || e.keyCode; if (!(checkval === !0 || e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable)) return k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("") && (undoValue = getBuffer().join(""), setTimeout(function() { $input.trigger("change"); }, 0)), !0; if (k) { 46 === k && e.shiftKey === !1 && "," === opts.radixPoint && (k = 44); var forwardPosition, pos = checkval ? { begin: ndx, end: ndx } : caret(input), c = String.fromCharCode(k); getMaskSet().writeOutBuffer = !0; var valResult = isValid(pos, c, strict); if (valResult !== !1) { var p = valResult.pos; if (resetMaskSet(!0), void 0 !== valResult.caret) forwardPosition = valResult.caret; else { var vps = getMaskSet().validPositions; forwardPosition = !opts.keepStatic && (void 0 !== vps[p + 1] && getTests(p + 1, vps[p].locator.slice(), p).length > 1 || void 0 !== vps[p].alternation) ? p + 1 : seekNext(p); } getMaskSet().p = forwardPosition; } if (writeOut !== !1) { var self = this; if (setTimeout(function() { opts.onKeyValidation.call(self, k, valResult, opts); }, 0), getMaskSet().writeOutBuffer && valResult !== !1) { var buffer = getBuffer(); writeBuffer(input, buffer, opts.numericInput && void 0 === valResult.caret ? seekPrevious(forwardPosition) : forwardPosition, e, checkval !== !0), checkval !== !0 && setTimeout(function() { isComplete(buffer) === !0 && $input.trigger("complete"); }, 0); } } if (opts.showTooltip && (input.title = opts.tooltip || getMaskSet().mask), checkval && $.isFunction(opts.onBeforeWrite)) { var result = opts.onBeforeWrite(e, getBuffer(), forwardPosition, opts); if (result && result.refreshFromBuffer) { var refresh = result.refreshFromBuffer; refreshFromBuffer(refresh === !0 ? refresh : refresh.start, refresh.end, result.buffer), resetMaskSet(!0), result.caret && (getMaskSet().p = result.caret); } } if (e.preventDefault(), checkval) return valResult; } } function pasteEvent(e) { var tempValue, input = this, ev = e.originalEvent || e, $input = $(input), inputValue = input.inputmask._valueGet(!0), caretPos = caret(input); isRTL && (tempValue = caretPos.end, caretPos.end = caretPos.begin, caretPos.begin = tempValue); var valueBeforeCaret = inputValue.substr(0, caretPos.begin), valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length); valueBeforeCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(0, caretPos.begin).join("") && (valueBeforeCaret = ""), valueAfterCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(caretPos.end).join("") && (valueAfterCaret = ""), isRTL && (tempValue = valueBeforeCaret, valueBeforeCaret = valueAfterCaret, valueAfterCaret = tempValue), window.clipboardData && window.clipboardData.getData ? inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret : ev.clipboardData && ev.clipboardData.getData && (inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret); var pasteValue = inputValue; if ($.isFunction(opts.onBeforePaste)) { if (pasteValue = opts.onBeforePaste(inputValue, opts), pasteValue === !1) return e.preventDefault(); pasteValue || (pasteValue = inputValue); } return checkVal(input, !1, !1, isRTL ? pasteValue.split("").reverse() : pasteValue.toString().split("")), writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()), e, !0), isComplete(getBuffer()) === !0 && $input.trigger("complete"), e.preventDefault(); } function inputFallBackEvent(e) { var input = this, inputValue = input.inputmask._valueGet(); if (getBuffer().join("") !== inputValue) { var caretPos = caret(input); if (inputValue = inputValue.replace(new RegExp("(" + Inputmask.escapeRegex(getBufferTemplate().join("")) + ")*"), ""), iemobile) { var inputChar = inputValue.replace(getBuffer().join(""), ""); if (1 === inputChar.length) { var keypress = new $.Event("keypress"); return keypress.which = inputChar.charCodeAt(0), keypressEvent.call(input, keypress, !0, !0, !1, getMaskSet().validPositions[caretPos.begin - 1] ? caretPos.begin : caretPos.begin - 1), !1; } } if (caretPos.begin > inputValue.length && (caret(input, inputValue.length), caretPos = caret(input)), getBuffer().length - inputValue.length !== 1 || inputValue.charAt(caretPos.begin) === getBuffer()[caretPos.begin] || inputValue.charAt(caretPos.begin + 1) === getBuffer()[caretPos.begin] || isMask(caretPos.begin)) { for (var lvp = getLastValidPosition() + 1, bufferTemplate = getBuffer().slice(lvp).join(""); null === inputValue.match(Inputmask.escapeRegex(bufferTemplate) + "$"); ) bufferTemplate = bufferTemplate.slice(1); inputValue = inputValue.replace(bufferTemplate, ""), inputValue = inputValue.split(""), checkVal(input, !0, !1, inputValue), isComplete(getBuffer()) === !0 && $(input).trigger("complete"); } else e.keyCode = Inputmask.keyCode.BACKSPACE, keydownEvent.call(input, e); e.preventDefault(); } } function setValueEvent(e) { var input = this, value = input.inputmask._valueGet(); checkVal(input, !0, !1, ($.isFunction(opts.onBeforeMask) ? opts.onBeforeMask(value, opts) || value : value).split("")), undoValue = getBuffer().join(""), (opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("") && input.inputmask._valueSet(""); } function focusEvent(e) { var input = this, nptValue = input.inputmask._valueGet(); opts.showMaskOnFocus && (!opts.showMaskOnHover || opts.showMaskOnHover && "" === nptValue) ? input.inputmask._valueGet() !== getBuffer().join("") && writeBuffer(input, getBuffer(), seekNext(getLastValidPosition())) : mouseEnter === !1 && caret(input, seekNext(getLastValidPosition())), opts.positionCaretOnTab === !0 && setTimeout(function() { caret(input, seekNext(getLastValidPosition())); }, 0), undoValue = getBuffer().join(""); } function mouseleaveEvent(e) { var input = this; if (mouseEnter = !1, opts.clearMaskOnLostFocus && document.activeElement !== input) { var buffer = getBuffer().slice(), nptValue = input.inputmask._valueGet(); nptValue !== input.getAttribute("placeholder") && "" !== nptValue && (-1 === getLastValidPosition() && nptValue === getBufferTemplate().join("") ? buffer = [] : clearOptionalTail(buffer), writeBuffer(input, buffer)); } } function clickEvent(e) { function doRadixFocus(clickPos) { if (opts.radixFocus && "" !== opts.radixPoint) { var vps = getMaskSet().validPositions; if (void 0 === vps[clickPos] || vps[clickPos].input === getPlaceholder(clickPos)) { if (clickPos < seekNext(-1)) return !0; var radixPos = $.inArray(opts.radixPoint, getBuffer()); if (-1 !== radixPos) { for (var vp in vps) if (vp > radixPos && vps[vp].input !== getPlaceholder(vp)) return !1; return !0; } } } return !1; } var input = this; if (document.activeElement === input) { var selectedCaret = caret(input); if (selectedCaret.begin === selectedCaret.end) if (doRadixFocus(selectedCaret.begin)) caret(input, opts.numericInput ? seekNext($.inArray(opts.radixPoint, getBuffer())) : $.inArray(opts.radixPoint, getBuffer())); else { var clickPosition = selectedCaret.begin, lvclickPosition = getLastValidPosition(clickPosition, !0), lastPosition = seekNext(lvclickPosition); lastPosition > clickPosition ? caret(input, isMask(clickPosition) || isMask(clickPosition - 1) ? clickPosition : seekNext(clickPosition)) : ((getBuffer()[lastPosition] !== getPlaceholder(lastPosition) || !isMask(lastPosition, !0) && getTest(lastPosition).def === getPlaceholder(lastPosition)) && (lastPosition = seekNext(lastPosition)), caret(input, lastPosition)); } } } function dblclickEvent(e) { var input = this; setTimeout(function() { caret(input, 0, seekNext(getLastValidPosition())); }, 0); } function cutEvent(e) { var input = this, $input = $(input), pos = caret(input), ev = e.originalEvent || e, clipboardData = window.clipboardData || ev.clipboardData, clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end); clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join("")), document.execCommand && document.execCommand("copy"), handleRemove(input, Inputmask.keyCode.DELETE, pos), writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join("")), input.inputmask._valueGet() === getBufferTemplate().join("") && $input.trigger("cleared"), opts.showTooltip && (input.title = opts.tooltip || getMaskSet().mask); } function blurEvent(e) { var $input = $(this), input = this; if (input.inputmask) { var nptValue = input.inputmask._valueGet(), buffer = getBuffer().slice(); undoValue !== buffer.join("") && setTimeout(function() { $input.trigger("change"), undoValue = buffer.join(""); }, 0), "" !== nptValue && (opts.clearMaskOnLostFocus && (-1 === getLastValidPosition() && nptValue === getBufferTemplate().join("") ? buffer = [] : clearOptionalTail(buffer)), isComplete(buffer) === !1 && (setTimeout(function() { $input.trigger("incomplete"); }, 0), opts.clearIncomplete && (resetMaskSet(), buffer = opts.clearMaskOnLostFocus ? [] : getBufferTemplate().slice())), writeBuffer(input, buffer, void 0, e)); } } function mouseenterEvent(e) { var input = this; mouseEnter = !0, document.activeElement !== input && opts.showMaskOnHover && input.inputmask._valueGet() !== getBuffer().join("") && writeBuffer(input, getBuffer()); } function submitEvent(e) { undoValue !== getBuffer().join("") && $el.trigger("change"), opts.clearMaskOnLostFocus && -1 === getLastValidPosition() && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("") && el.inputmask._valueSet(""), opts.removeMaskOnSubmit && (el.inputmask._valueSet(el.inputmask.unmaskedvalue(), !0), setTimeout(function() { writeBuffer(el, getBuffer()); }, 0)); } function resetEvent(e) { setTimeout(function() { $el.trigger("setvalue"); }, 0); } function mask(elem) { if (el = elem, $el = $(el), opts.showTooltip && (el.title = opts.tooltip || getMaskSet().mask), ("rtl" === el.dir || opts.rightAlign) && (el.style.textAlign = "right"), ("rtl" === el.dir || opts.numericInput) && (el.dir = "ltr", el.removeAttribute("dir"), el.inputmask.isRTL = !0, isRTL = !0), EventRuler.off(el), patchValueProperty(el), isElementTypeSupported(el, opts) && (EventRuler.on(el, "submit", submitEvent), EventRuler.on(el, "reset", resetEvent), EventRuler.on(el, "mouseenter", mouseenterEvent), EventRuler.on(el, "blur", blurEvent), EventRuler.on(el, "focus", focusEvent), EventRuler.on(el, "mouseleave", mouseleaveEvent), EventRuler.on(el, "click", clickEvent), EventRuler.on(el, "dblclick", dblclickEvent), EventRuler.on(el, "paste", pasteEvent), EventRuler.on(el, "dragdrop", pasteEvent), EventRuler.on(el, "drop", pasteEvent), EventRuler.on(el, "cut", cutEvent), EventRuler.on(el, "complete", opts.oncomplete), EventRuler.on(el, "incomplete", opts.onincomplete), EventRuler.on(el, "cleared", opts.oncleared), EventRuler.on(el, "keydown", keydownEvent), EventRuler.on(el, "keypress", keypressEvent), EventRuler.on(el, "input", inputFallBackEvent)), EventRuler.on(el, "setvalue", setValueEvent), "" !== el.inputmask._valueGet() || opts.clearMaskOnLostFocus === !1 || document.activeElement === el) { var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask(el.inputmask._valueGet(), opts) || el.inputmask._valueGet() : el.inputmask._valueGet(); checkVal(el, !0, !1, initialValue.split("")); var buffer = getBuffer().slice(); undoValue = buffer.join(""), isComplete(buffer) === !1 && opts.clearIncomplete && resetMaskSet(), opts.clearMaskOnLostFocus && document.activeElement !== el && (buffer.join("") === getBufferTemplate().join("") ? buffer = [] : clearOptionalTail(buffer)), writeBuffer(el, buffer), document.activeElement === el && caret(el, seekNext(getLastValidPosition())); } } var undoValue, el, $el, maxLength, valueBuffer, isRTL = !1, skipKeyPressEvent = !1, skipInputEvent = !1, ignorable = !1, mouseEnter = !0, EventRuler = { on: function(input, eventName, eventHandler) { var ev = function(e) { if (void 0 === this.inputmask && "FORM" !== this.nodeName) { var imOpts = $.data(this, "_inputmask_opts"); imOpts ? new Inputmask(imOpts).mask(this) : EventRuler.off(this); } else { if ("setvalue" === e.type || !(this.disabled || this.readOnly && !("keydown" === e.type && e.ctrlKey && 67 === e.keyCode || opts.tabThrough === !1 && e.keyCode === Inputmask.keyCode.TAB))) { switch (e.type) { case "input": if (skipInputEvent === !0) return skipInputEvent = !1, e.preventDefault(); break; case "keydown": skipKeyPressEvent = !1, skipInputEvent = !1; break; case "keypress": if (skipKeyPressEvent === !0) return e.preventDefault(); skipKeyPressEvent = !0; break; case "click": if (iemobile) { var that = this; return setTimeout(function() { eventHandler.apply(that, arguments); }, 0), !1; } } var returnVal = eventHandler.apply(this, arguments); return returnVal === !1 && (e.preventDefault(), e.stopPropagation()), returnVal; } e.preventDefault(); } }; input.inputmask.events[eventName] = input.inputmask.events[eventName] || [], input.inputmask.events[eventName].push(ev), -1 !== $.inArray(eventName, [ "submit", "reset" ]) ? null != input.form && $(input.form).on(eventName, ev) : $(input).on(eventName, ev); }, off: function(input, event) { if (input.inputmask && input.inputmask.events) { var events; event ? (events = [], events[event] = input.inputmask.events[event]) : events = input.inputmask.events, $.each(events, function(eventName, evArr) { for (;evArr.length > 0; ) { var ev = evArr.pop(); -1 !== $.inArray(eventName, [ "submit", "reset" ]) ? null != input.form && $(input.form).off(eventName, ev) : $(input).off(eventName, ev); } delete input.inputmask.events[eventName]; }); } } }; if (void 0 !== actionObj) switch (actionObj.action) { case "isComplete": return el = actionObj.el, isComplete(getBuffer()); case "unmaskedvalue": return el = actionObj.el, void 0 !== el && void 0 !== el.inputmask ? (maskset = el.inputmask.maskset, opts = el.inputmask.opts, isRTL = el.inputmask.isRTL) : (valueBuffer = actionObj.value, opts.numericInput && (isRTL = !0), valueBuffer = ($.isFunction(opts.onBeforeMask) ? opts.onBeforeMask(valueBuffer, opts) || valueBuffer : valueBuffer).split(""), checkVal(void 0, !1, !1, isRTL ? valueBuffer.reverse() : valueBuffer), $.isFunction(opts.onBeforeWrite) && opts.onBeforeWrite(void 0, getBuffer(), 0, opts)), unmaskedvalue(el); case "mask": el = actionObj.el, maskset = el.inputmask.maskset, opts = el.inputmask.opts, isRTL = el.inputmask.isRTL, undoValue = getBuffer().join(""), mask(el); break; case "format": return opts.numericInput && (isRTL = !0), valueBuffer = ($.isFunction(opts.onBeforeMask) ? opts.onBeforeMask(actionObj.value, opts) || actionObj.value : actionObj.value).split(""), checkVal(void 0, !1, !1, isRTL ? valueBuffer.reverse() : valueBuffer), $.isFunction(opts.onBeforeWrite) && opts.onBeforeWrite(void 0, getBuffer(), 0, opts), actionObj.metadata ? { value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""), metadata: maskScope({ action: "getmetadata" }, maskset, opts) } : isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""); case "isValid": opts.numericInput && (isRTL = !0), actionObj.value ? (valueBuffer = actionObj.value.split(""), checkVal(void 0, !1, !0, isRTL ? valueBuffer.reverse() : valueBuffer)) : actionObj.value = getBuffer().join(""); for (var buffer = getBuffer(), rl = determineLastRequiredPosition(), lmib = buffer.length - 1; lmib > rl && !isMask(lmib); lmib--) ; return buffer.splice(rl, lmib + 1 - rl), isComplete(buffer) && actionObj.value === getBuffer().join(""); case "getemptymask": return getBufferTemplate().join(""); case "remove": el = actionObj.el, $el = $(el), maskset = el.inputmask.maskset, opts = el.inputmask.opts, el.inputmask._valueSet(unmaskedvalue(el)), EventRuler.off(el); var valueProperty; Object.getOwnPropertyDescriptor ? (valueProperty = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "value"), valueProperty && el.inputmask.__valueGet && Object.defineProperty(el, "value", { get: el.inputmask.__valueGet, set: el.inputmask.__valueSet, configurable: !0 })) : document.__lookupGetter__ && el.__lookupGetter__("value") && el.inputmask.__valueGet && (el.__defineGetter__("value", el.inputmask.__valueGet), el.__defineSetter__("value", el.inputmask.__valueSet)), el.inputmask = void 0; break; case "getmetadata": if ($.isArray(maskset.metadata)) { for (var alternation, lvp = getLastValidPosition(void 0, !0), firstAlt = lvp; firstAlt >= 0; firstAlt--) if (getMaskSet().validPositions[firstAlt] && void 0 !== getMaskSet().validPositions[firstAlt].alternation) { alternation = getMaskSet().validPositions[firstAlt].alternation; break; } return void 0 !== alternation ? maskset.metadata[getMaskSet().validPositions[firstAlt].locator[alternation]] : []; } return maskset.metadata; } } Inputmask.prototype = { defaults: { placeholder: "_", optionalmarker: { start: "[", end: "]" }, quantifiermarker: { start: "{", end: "}" }, groupmarker: { start: "(", end: ")" }, alternatormarker: "|", escapeChar: "\\", mask: null, oncomplete: $.noop, onincomplete: $.noop, oncleared: $.noop, repeat: 0, greedy: !0, autoUnmask: !1, removeMaskOnSubmit: !1, clearMaskOnLostFocus: !0, insertMode: !0, clearIncomplete: !1, aliases: {}, alias: null, onKeyDown: $.noop, onBeforeMask: null, onBeforePaste: function(pastedValue, opts) { return $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask(pastedValue, opts) : pastedValue; }, onBeforeWrite: null, onUnMask: null, showMaskOnFocus: !0, showMaskOnHover: !0, onKeyValidation: $.noop, skipOptionalPartCharacter: " ", showTooltip: !1, tooltip: void 0, numericInput: !1, rightAlign: !1, undoOnEscape: !0, radixPoint: "", radixPointDefinitionSymbol: void 0, groupSeparator: "", radixFocus: !1, nojumps: !1, nojumpsThreshold: 0, keepStatic: null, positionCaretOnTab: !1, tabThrough: !1, supportsInputType: [ "text", "tel", "password" ], definitions: { "9": { validator: "[0-9]", cardinality: 1, definitionSymbol: "*" }, a: { validator: "[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]", cardinality: 1, definitionSymbol: "*" }, "*": { validator: "[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]", cardinality: 1 } }, ignorables: [ 8, 9, 13, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123 ], isComplete: null, canClearPosition: $.noop, postValidation: null, staticDefinitionSymbol: void 0, jitMasking: !1 }, masksCache: {}, mask: function(elems) { var that = this; return "string" == typeof elems && (elems = document.getElementById(elems) || document.querySelectorAll(elems)), elems = elems.nodeName ? [ elems ] : elems, $.each(elems, function(ndx, el) { var scopedOpts = $.extend(!0, {}, that.opts); importAttributeOptions(el, scopedOpts, $.extend(!0, {}, that.userOptions)); var maskset = generateMaskSet(scopedOpts, that.noMasksCache); void 0 !== maskset && (void 0 !== el.inputmask && el.inputmask.remove(), el.inputmask = new Inputmask(), el.inputmask.opts = scopedOpts, el.inputmask.noMasksCache = that.noMasksCache, el.inputmask.userOptions = $.extend(!0, {}, that.userOptions), el.inputmask.el = el, el.inputmask.maskset = maskset, el.inputmask.isRTL = !1, $.data(el, "_inputmask_opts", scopedOpts), maskScope({ action: "mask", el: el })); }), elems && elems[0] ? elems[0].inputmask || this : this; }, option: function(options) { return "string" == typeof options ? this.opts[options] : "object" == typeof options ? ($.extend(this.opts, options), $.extend(this.userOptions, options), this.el && (void 0 !== options.mask || void 0 !== options.alias ? this.mask(this.el) : ($.data(this.el, "_inputmask_opts", this.opts), maskScope({ action: "mask", el: this.el }))), this) : void 0; }, unmaskedvalue: function(value) { return maskScope({ action: "unmaskedvalue", el: this.el, value: value }, this.el && this.el.inputmask ? this.el.inputmask.maskset : generateMaskSet(this.opts, this.noMasksCache), this.opts); }, remove: function() { return this.el ? (maskScope({ action: "remove", el: this.el }), this.el.inputmask = void 0, this.el) : void 0; }, getemptymask: function() { return maskScope({ action: "getemptymask" }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts); }, hasMaskedValue: function() { return !this.opts.autoUnmask; }, isComplete: function() { return maskScope({ action: "isComplete", el: this.el }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts); }, getmetadata: function() { return maskScope({ action: "getmetadata" }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts); }, isValid: function(value) { return maskScope({ action: "isValid", value: value }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts); }, format: function(value, metadata) { return maskScope({ action: "format", value: value, metadata: metadata }, this.maskset || generateMaskSet(this.opts, this.noMasksCache), this.opts); } }, Inputmask.extendDefaults = function(options) { $.extend(!0, Inputmask.prototype.defaults, options); }, Inputmask.extendDefinitions = function(definition) { $.extend(!0, Inputmask.prototype.defaults.definitions, definition); }, Inputmask.extendAliases = function(alias) { $.extend(!0, Inputmask.prototype.defaults.aliases, alias); }, Inputmask.format = function(value, options, metadata) { return Inputmask(options).format(value, metadata); }, Inputmask.unmask = function(value, options) { return Inputmask(options).unmaskedvalue(value); }, Inputmask.isValid = function(value, options) { return Inputmask(options).isValid(value); }, Inputmask.remove = function(elems) { $.each(elems, function(ndx, el) { el.inputmask && el.inputmask.remove(); }); }, Inputmask.escapeRegex = function(str) { var specials = [ "/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^" ]; return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1"); }, Inputmask.keyCode = { ALT: 18, BACKSPACE: 8, BACKSPACE_SAFARI: 127, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91, X: 88 }; var ua = navigator.userAgent, mobile = /mobile/i.test(ua), iemobile = /iemobile/i.test(ua), iphone = /iphone/i.test(ua) && !iemobile; /android.*safari.*/i.test(ua) && !iemobile; return window.Inputmask = Inputmask, Inputmask; }(jQuery), function($, Inputmask) { return void 0 === $.fn.inputmask && ($.fn.inputmask = function(fn, options) { var nptmask, input = this[0]; if (void 0 === options && (options = {}), "string" == typeof fn) switch (fn) { case "unmaskedvalue": return input && input.inputmask ? input.inputmask.unmaskedvalue() : $(input).val(); case "remove": return this.each(function() { this.inputmask && this.inputmask.remove(); }); case "getemptymask": return input && input.inputmask ? input.inputmask.getemptymask() : ""; case "hasMaskedValue": return input && input.inputmask ? input.inputmask.hasMaskedValue() : !1; case "isComplete": return input && input.inputmask ? input.inputmask.isComplete() : !0; case "getmetadata": return input && input.inputmask ? input.inputmask.getmetadata() : void 0; case "setvalue": $(input).val(options), input && void 0 !== input.inputmask && $(input).triggerHandler("setvalue"); break; case "option": if ("string" != typeof options) return this.each(function() { return void 0 !== this.inputmask ? this.inputmask.option(options) : void 0; }); if (input && void 0 !== input.inputmask) return input.inputmask.option(options); break; default: return options.alias = fn, nptmask = new Inputmask(options), this.each(function() { nptmask.mask(this); }); } else { if ("object" == typeof fn) return nptmask = new Inputmask(fn), void 0 === fn.mask && void 0 === fn.alias ? this.each(function() { return void 0 !== this.inputmask ? this.inputmask.option(fn) : void nptmask.mask(this); }) : this.each(function() { nptmask.mask(this); }); if (void 0 === fn) return this.each(function() { nptmask = new Inputmask(options), nptmask.mask(this); }); } }), $.fn.inputmask; }(jQuery, Inputmask), function($, Inputmask) { return Inputmask.extendDefinitions({ h: { validator: "[01][0-9]|2[0-3]", cardinality: 2, prevalidator: [ { validator: "[0-2]", cardinality: 1 } ] }, s: { validator: "[0-5][0-9]", cardinality: 2, prevalidator: [ { validator: "[0-5]", cardinality: 1 } ] }, d: { validator: "0[1-9]|[12][0-9]|3[01]", cardinality: 2, prevalidator: [ { validator: "[0-3]", cardinality: 1 } ] }, m: { validator: "0[1-9]|1[012]", cardinality: 2, prevalidator: [ { validator: "[01]", cardinality: 1 } ] }, y: { validator: "(19|20)\\d{2}", cardinality: 4, prevalidator: [ { validator: "[12]", cardinality: 1 }, { validator: "(19|20)", cardinality: 2 }, { validator: "(19|20)\\d", cardinality: 3 } ] } }), Inputmask.extendAliases({ "dd/mm/yyyy": { mask: "1/2/y", placeholder: "dd/mm/yyyy", regex: { val1pre: new RegExp("[0-3]"), val1: new RegExp("0[1-9]|[12][0-9]|3[01]"), val2pre: function(separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|[12][0-9]|3[01])" + escapedSeparator + "[01])"); }, val2: function(separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|[12][0-9])" + escapedSeparator + "(0[1-9]|1[012]))|(30" + escapedSeparator + "(0[13-9]|1[012]))|(31" + escapedSeparator + "(0[13578]|1[02]))"); } }, leapday: "29/02/", separator: "/", yearrange: { minyear: 1900, maxyear: 2099 }, isInYearRange: function(chrs, minyear, maxyear) { if (isNaN(chrs)) return !1; var enteredyear = parseInt(chrs.concat(minyear.toString().slice(chrs.length))), enteredyear2 = parseInt(chrs.concat(maxyear.toString().slice(chrs.length))); return (isNaN(enteredyear) ? !1 : enteredyear >= minyear && maxyear >= enteredyear) || (isNaN(enteredyear2) ? !1 : enteredyear2 >= minyear && maxyear >= enteredyear2); }, determinebaseyear: function(minyear, maxyear, hint) { var currentyear = new Date().getFullYear(); if (minyear > currentyear) return minyear; if (currentyear > maxyear) { for (var maxYearPrefix = maxyear.toString().slice(0, 2), maxYearPostfix = maxyear.toString().slice(2, 4); maxYearPrefix + hint > maxyear; ) maxYearPrefix--; var maxxYear = maxYearPrefix + maxYearPostfix; return minyear > maxxYear ? minyear : maxxYear; } if (currentyear >= minyear && maxyear >= currentyear) { for (var currentYearPrefix = currentyear.toString().slice(0, 2); currentYearPrefix + hint > maxyear; ) currentYearPrefix--; var currentYearAndHint = currentYearPrefix + hint; return minyear > currentYearAndHint ? minyear : currentYearAndHint; } return currentyear; }, onKeyDown: function(e, buffer, caretPos, opts) { var $input = $(this); if (e.ctrlKey && e.keyCode === Inputmask.keyCode.RIGHT) { var today = new Date(); $input.val(today.getDate().toString() + (today.getMonth() + 1).toString() + today.getFullYear().toString()), $input.trigger("setvalue"); } }, getFrontValue: function(mask, buffer, opts) { for (var start = 0, length = 0, i = 0; i < mask.length && "2" !== mask.charAt(i); i++) { var definition = opts.definitions[mask.charAt(i)]; definition ? (start += length, length = definition.cardinality) : length++; } return buffer.join("").substr(start, length); }, definitions: { "1": { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.regex.val1.test(chrs); return strict || isValid || chrs.charAt(1) !== opts.separator && -1 === "-./".indexOf(chrs.charAt(1)) || !(isValid = opts.regex.val1.test("0" + chrs.charAt(0))) ? isValid : (maskset.buffer[pos - 1] = "0", { refreshFromBuffer: { start: pos - 1, end: pos }, pos: pos, c: chrs.charAt(0) }); }, cardinality: 2, prevalidator: [ { validator: function(chrs, maskset, pos, strict, opts) { var pchrs = chrs; isNaN(maskset.buffer[pos + 1]) || (pchrs += maskset.buffer[pos + 1]); var isValid = 1 === pchrs.length ? opts.regex.val1pre.test(pchrs) : opts.regex.val1.test(pchrs); if (!strict && !isValid) { if (isValid = opts.regex.val1.test(chrs + "0")) return maskset.buffer[pos] = chrs, maskset.buffer[++pos] = "0", { pos: pos, c: "0" }; if (isValid = opts.regex.val1.test("0" + chrs)) return maskset.buffer[pos] = "0", pos++, { pos: pos }; } return isValid; }, cardinality: 1 } ] }, "2": { validator: function(chrs, maskset, pos, strict, opts) { var frontValue = opts.getFrontValue(maskset.mask, maskset.buffer, opts); -1 !== frontValue.indexOf(opts.placeholder[0]) && (frontValue = "01" + opts.separator); var isValid = opts.regex.val2(opts.separator).test(frontValue + chrs); if (!strict && !isValid && (chrs.charAt(1) === opts.separator || -1 !== "-./".indexOf(chrs.charAt(1))) && (isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs.charAt(0)))) return maskset.buffer[pos - 1] = "0", { refreshFromBuffer: { start: pos - 1, end: pos }, pos: pos, c: chrs.charAt(0) }; if (opts.mask.indexOf("2") === opts.mask.length - 1 && isValid) { var dayMonthValue = maskset.buffer.join("").substr(4, 4) + chrs; if (dayMonthValue !== opts.leapday) return !0; var year = parseInt(maskset.buffer.join("").substr(0, 4), 10); return year % 4 === 0 ? year % 100 === 0 ? year % 400 === 0 ? !0 : !1 : !0 : !1; } return isValid; }, cardinality: 2, prevalidator: [ { validator: function(chrs, maskset, pos, strict, opts) { isNaN(maskset.buffer[pos + 1]) || (chrs += maskset.buffer[pos + 1]); var frontValue = opts.getFrontValue(maskset.mask, maskset.buffer, opts); -1 !== frontValue.indexOf(opts.placeholder[0]) && (frontValue = "01" + opts.separator); var isValid = 1 === chrs.length ? opts.regex.val2pre(opts.separator).test(frontValue + chrs) : opts.regex.val2(opts.separator).test(frontValue + chrs); return strict || isValid || !(isValid = opts.regex.val2(opts.separator).test(frontValue + "0" + chrs)) ? isValid : (maskset.buffer[pos] = "0", pos++, { pos: pos }); }, cardinality: 1 } ] }, y: { validator: function(chrs, maskset, pos, strict, opts) { if (opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) { var dayMonthValue = maskset.buffer.join("").substr(0, 6); if (dayMonthValue !== opts.leapday) return !0; var year = parseInt(chrs, 10); return year % 4 === 0 ? year % 100 === 0 ? year % 400 === 0 ? !0 : !1 : !0 : !1; } return !1; }, cardinality: 4, prevalidator: [ { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); if (!strict && !isValid) { var yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs + "0").toString().slice(0, 1); if (isValid = opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) return maskset.buffer[pos++] = yearPrefix.charAt(0), { pos: pos }; if (yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs + "0").toString().slice(0, 2), isValid = opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) return maskset.buffer[pos++] = yearPrefix.charAt(0), maskset.buffer[pos++] = yearPrefix.charAt(1), { pos: pos }; } return isValid; }, cardinality: 1 }, { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); if (!strict && !isValid) { var yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs).toString().slice(0, 2); if (isValid = opts.isInYearRange(chrs[0] + yearPrefix[1] + chrs[1], opts.yearrange.minyear, opts.yearrange.maxyear)) return maskset.buffer[pos++] = yearPrefix.charAt(1), { pos: pos }; if (yearPrefix = opts.determinebaseyear(opts.yearrange.minyear, opts.yearrange.maxyear, chrs).toString().slice(0, 2), opts.isInYearRange(yearPrefix + chrs, opts.yearrange.minyear, opts.yearrange.maxyear)) { var dayMonthValue = maskset.buffer.join("").substr(0, 6); if (dayMonthValue !== opts.leapday) isValid = !0; else { var year = parseInt(chrs, 10); isValid = year % 4 === 0 ? year % 100 === 0 ? year % 400 === 0 ? !0 : !1 : !0 : !1; } } else isValid = !1; if (isValid) return maskset.buffer[pos - 1] = yearPrefix.charAt(0), maskset.buffer[pos++] = yearPrefix.charAt(1), maskset.buffer[pos++] = chrs.charAt(0), { refreshFromBuffer: { start: pos - 3, end: pos }, pos: pos }; } return isValid; }, cardinality: 2 }, { validator: function(chrs, maskset, pos, strict, opts) { return opts.isInYearRange(chrs, opts.yearrange.minyear, opts.yearrange.maxyear); }, cardinality: 3 } ] } }, insertMode: !1, autoUnmask: !1 }, "mm/dd/yyyy": { placeholder: "mm/dd/yyyy", alias: "dd/mm/yyyy", regex: { val2pre: function(separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[13-9]|1[012])" + escapedSeparator + "[0-3])|(02" + escapedSeparator + "[0-2])"); }, val2: function(separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "(0[1-9]|[12][0-9]))|((0[13-9]|1[012])" + escapedSeparator + "30)|((0[13578]|1[02])" + escapedSeparator + "31)"); }, val1pre: new RegExp("[01]"), val1: new RegExp("0[1-9]|1[012]") }, leapday: "02/29/", onKeyDown: function(e, buffer, caretPos, opts) { var $input = $(this); if (e.ctrlKey && e.keyCode === Inputmask.keyCode.RIGHT) { var today = new Date(); $input.val((today.getMonth() + 1).toString() + today.getDate().toString() + today.getFullYear().toString()), $input.trigger("setvalue"); } } }, "yyyy/mm/dd": { mask: "y/1/2", placeholder: "yyyy/mm/dd", alias: "mm/dd/yyyy", leapday: "/02/29", onKeyDown: function(e, buffer, caretPos, opts) { var $input = $(this); if (e.ctrlKey && e.keyCode === Inputmask.keyCode.RIGHT) { var today = new Date(); $input.val(today.getFullYear().toString() + (today.getMonth() + 1).toString() + today.getDate().toString()), $input.trigger("setvalue"); } } }, "dd.mm.yyyy": { mask: "1.2.y", placeholder: "dd.mm.yyyy", leapday: "29.02.", separator: ".", alias: "dd/mm/yyyy" }, "dd-mm-yyyy": { mask: "1-2-y", placeholder: "dd-mm-yyyy", leapday: "29-02-", separator: "-", alias: "dd/mm/yyyy" }, "mm.dd.yyyy": { mask: "1.2.y", placeholder: "mm.dd.yyyy", leapday: "02.29.", separator: ".", alias: "mm/dd/yyyy" }, "mm-dd-yyyy": { mask: "1-2-y", placeholder: "mm-dd-yyyy", leapday: "02-29-", separator: "-", alias: "mm/dd/yyyy" }, "yyyy.mm.dd": { mask: "y.1.2", placeholder: "yyyy.mm.dd", leapday: ".02.29", separator: ".", alias: "yyyy/mm/dd" }, "yyyy-mm-dd": { mask: "y-1-2", placeholder: "yyyy-mm-dd", leapday: "-02-29", separator: "-", alias: "yyyy/mm/dd" }, datetime: { mask: "1/2/y h:s", placeholder: "dd/mm/yyyy hh:mm", alias: "dd/mm/yyyy", regex: { hrspre: new RegExp("[012]"), hrs24: new RegExp("2[0-4]|1[3-9]"), hrs: new RegExp("[01][0-9]|2[0-4]"), ampm: new RegExp("^[a|p|A|P][m|M]"), mspre: new RegExp("[0-5]"), ms: new RegExp("[0-5][0-9]") }, timeseparator: ":", hourFormat: "24", definitions: { h: { validator: function(chrs, maskset, pos, strict, opts) { if ("24" === opts.hourFormat && 24 === parseInt(chrs, 10)) return maskset.buffer[pos - 1] = "0", maskset.buffer[pos] = "0", { refreshFromBuffer: { start: pos - 1, end: pos }, c: "0" }; var isValid = opts.regex.hrs.test(chrs); if (!strict && !isValid && (chrs.charAt(1) === opts.timeseparator || -1 !== "-.:".indexOf(chrs.charAt(1))) && (isValid = opts.regex.hrs.test("0" + chrs.charAt(0)))) return maskset.buffer[pos - 1] = "0", maskset.buffer[pos] = chrs.charAt(0), pos++, { refreshFromBuffer: { start: pos - 2, end: pos }, pos: pos, c: opts.timeseparator }; if (isValid && "24" !== opts.hourFormat && opts.regex.hrs24.test(chrs)) { var tmp = parseInt(chrs, 10); return 24 === tmp ? (maskset.buffer[pos + 5] = "a", maskset.buffer[pos + 6] = "m") : (maskset.buffer[pos + 5] = "p", maskset.buffer[pos + 6] = "m"), tmp -= 12, 10 > tmp ? (maskset.buffer[pos] = tmp.toString(), maskset.buffer[pos - 1] = "0") : (maskset.buffer[pos] = tmp.toString().charAt(1), maskset.buffer[pos - 1] = tmp.toString().charAt(0)), { refreshFromBuffer: { start: pos - 1, end: pos + 6 }, c: maskset.buffer[pos] }; } return isValid; }, cardinality: 2, prevalidator: [ { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.regex.hrspre.test(chrs); return strict || isValid || !(isValid = opts.regex.hrs.test("0" + chrs)) ? isValid : (maskset.buffer[pos] = "0", pos++, { pos: pos }); }, cardinality: 1 } ] }, s: { validator: "[0-5][0-9]", cardinality: 2, prevalidator: [ { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.regex.mspre.test(chrs); return strict || isValid || !(isValid = opts.regex.ms.test("0" + chrs)) ? isValid : (maskset.buffer[pos] = "0", pos++, { pos: pos }); }, cardinality: 1 } ] }, t: { validator: function(chrs, maskset, pos, strict, opts) { return opts.regex.ampm.test(chrs + "m"); }, casing: "lower", cardinality: 1 } }, insertMode: !1, autoUnmask: !1 }, datetime12: { mask: "1/2/y h:s t\\m", placeholder: "dd/mm/yyyy hh:mm xm", alias: "datetime", hourFormat: "12" }, "mm/dd/yyyy hh:mm xm": { mask: "1/2/y h:s t\\m", placeholder: "mm/dd/yyyy hh:mm xm", alias: "datetime12", regex: { val2pre: function(separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[13-9]|1[012])" + escapedSeparator + "[0-3])|(02" + escapedSeparator + "[0-2])"); }, val2: function(separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "(0[1-9]|[12][0-9]))|((0[13-9]|1[012])" + escapedSeparator + "30)|((0[13578]|1[02])" + escapedSeparator + "31)"); }, val1pre: new RegExp("[01]"), val1: new RegExp("0[1-9]|1[012]") }, leapday: "02/29/", onKeyDown: function(e, buffer, caretPos, opts) { var $input = $(this); if (e.ctrlKey && e.keyCode === Inputmask.keyCode.RIGHT) { var today = new Date(); $input.val((today.getMonth() + 1).toString() + today.getDate().toString() + today.getFullYear().toString()), $input.trigger("setvalue"); } } }, "hh:mm t": { mask: "h:s t\\m", placeholder: "hh:mm xm", alias: "datetime", hourFormat: "12" }, "h:s t": { mask: "h:s t\\m", placeholder: "hh:mm xm", alias: "datetime", hourFormat: "12" }, "hh:mm:ss": { mask: "h:s:s", placeholder: "hh:mm:ss", alias: "datetime", autoUnmask: !1 }, "hh:mm": { mask: "h:s", placeholder: "hh:mm", alias: "datetime", autoUnmask: !1 }, date: { alias: "dd/mm/yyyy" }, "mm/yyyy": { mask: "1/y", placeholder: "mm/yyyy", leapday: "donotuse", separator: "/", alias: "mm/dd/yyyy" }, shamsi: { regex: { val2pre: function(separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "[0-3])"); }, val2: function(separator) { var escapedSeparator = Inputmask.escapeRegex.call(this, separator); return new RegExp("((0[1-9]|1[012])" + escapedSeparator + "(0[1-9]|[12][0-9]))|((0[1-9]|1[012])" + escapedSeparator + "30)|((0[1-6])" + escapedSeparator + "31)"); }, val1pre: new RegExp("[01]"), val1: new RegExp("0[1-9]|1[012]") }, yearrange: { minyear: 1300, maxyear: 1499 }, mask: "y/1/2", leapday: "/12/30", placeholder: "yyyy/mm/dd", alias: "mm/dd/yyyy", clearIncomplete: !0 } }), Inputmask; }(jQuery, Inputmask), function($, Inputmask) { return Inputmask.extendDefinitions({ A: { validator: "[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]", cardinality: 1, casing: "upper" }, "&": { validator: "[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]", cardinality: 1, casing: "upper" }, "#": { validator: "[0-9A-Fa-f]", cardinality: 1, casing: "upper" } }), Inputmask.extendAliases({ url: { definitions: { i: { validator: ".", cardinality: 1 } }, mask: "(\\http://)|(\\http\\s://)|(ftp://)|(ftp\\s://)i{+}", insertMode: !1, autoUnmask: !1 }, ip: { mask: "i[i[i]].i[i[i]].i[i[i]].i[i[i]]", definitions: { i: { validator: function(chrs, maskset, pos, strict, opts) { return pos - 1 > -1 && "." !== maskset.buffer[pos - 1] ? (chrs = maskset.buffer[pos - 1] + chrs, chrs = pos - 2 > -1 && "." !== maskset.buffer[pos - 2] ? maskset.buffer[pos - 2] + chrs : "0" + chrs) : chrs = "00" + chrs, new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]").test(chrs); }, cardinality: 1 } }, onUnMask: function(maskedValue, unmaskedValue, opts) { return maskedValue; } }, email: { mask: "*{1,64}[.*{1,64}][.*{1,64}][.*{1,63}]@-{1,63}[.-{1,63}][.-{1,63}][.-{1,63}]", greedy: !1, onBeforePaste: function(pastedValue, opts) { return pastedValue = pastedValue.toLowerCase(), pastedValue.replace("mailto:", ""); }, definitions: { "*": { validator: "[0-9A-Za-z!#$%&'*+/=?^_`{|}~-]", cardinality: 1, casing: "lower" }, "-": { validator: "[0-9A-Za-z-]", cardinality: 1, casing: "lower" } }, onUnMask: function(maskedValue, unmaskedValue, opts) { return maskedValue; } }, mac: { mask: "##:##:##:##:##:##" }, vin: { mask: "V{8}vV{4}9{4}", definitions: { V: { validator: "[A-HJ-NPR-Za-hj-npr-z\\d]", cardinality: 1, casing: "upper" }, v: { validator: "[Xx\\d]", cardinality: 1, casing: "upper" } }, clearIncomplete: !0, autoUnmask: !0 } }), Inputmask; }(jQuery, Inputmask), function($, Inputmask) { return Inputmask.extendAliases({ numeric: { mask: function(opts) { function autoEscape(txt) { for (var escapedTxt = "", i = 0; i < txt.length; i++) escapedTxt += opts.definitions[txt.charAt(i)] ? "\\" + txt.charAt(i) : txt.charAt(i); return escapedTxt; } if (0 !== opts.repeat && isNaN(opts.integerDigits) && (opts.integerDigits = opts.repeat), opts.repeat = 0, opts.groupSeparator === opts.radixPoint && ("." === opts.radixPoint ? opts.groupSeparator = "," : "," === opts.radixPoint ? opts.groupSeparator = "." : opts.groupSeparator = ""), " " === opts.groupSeparator && (opts.skipOptionalPartCharacter = void 0), opts.autoGroup = opts.autoGroup && "" !== opts.groupSeparator, opts.autoGroup && ("string" == typeof opts.groupSize && isFinite(opts.groupSize) && (opts.groupSize = parseInt(opts.groupSize)), isFinite(opts.integerDigits))) { var seps = Math.floor(opts.integerDigits / opts.groupSize), mod = opts.integerDigits % opts.groupSize; opts.integerDigits = parseInt(opts.integerDigits) + (0 === mod ? seps - 1 : seps), opts.integerDigits < 1 && (opts.integerDigits = "*"); } opts.placeholder.length > 1 && (opts.placeholder = opts.placeholder.charAt(0)), opts.radixFocus = opts.radixFocus && "" !== opts.placeholder && opts.integerOptional === !0, opts.definitions[";"] = opts.definitions["~"], opts.definitions[";"].definitionSymbol = "~", 1 == opts.numericInput && (opts.radixFocus = !1, opts.digitsOptional = !1, isNaN(opts.digits) && (opts.digits = 2), opts.decimalProtect = !1); var mask = autoEscape(opts.prefix); return mask += "[+]", mask += opts.integerOptional === !0 ? "~{1," + opts.integerDigits + "}" : "~{" + opts.integerDigits + "}", void 0 !== opts.digits && (isNaN(opts.digits) || parseInt(opts.digits) > 0) && (opts.decimalProtect && (opts.radixPointDefinitionSymbol = ":"), mask += opts.digitsOptional ? "[" + (opts.decimalProtect ? ":" : opts.radixPoint) + ";{1," + opts.digits + "}]" : (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}"), "" !== opts.negationSymbol.back && (mask += "[-]"), mask += autoEscape(opts.suffix), opts.greedy = !1, mask; }, placeholder: "", greedy: !1, digits: "*", digitsOptional: !0, radixPoint: ".", radixFocus: !0, groupSize: 3, groupSeparator: "", autoGroup: !1, allowPlus: !0, allowMinus: !0, negationSymbol: { front: "-", back: "" }, integerDigits: "+", integerOptional: !0, prefix: "", suffix: "", rightAlign: !0, decimalProtect: !0, min: null, max: null, step: 1, insertMode: !0, autoUnmask: !1, unmaskAsNumber: !1, postFormat: function(buffer, pos, opts) { opts.numericInput === !0 && (buffer = buffer.reverse(), isFinite(pos) && (pos = buffer.join("").length - pos - 1)); var i, l, suffixStripped = !1; buffer.length >= opts.suffix.length && buffer.join("").indexOf(opts.suffix) === buffer.length - opts.suffix.length && (buffer.length = buffer.length - opts.suffix.length, suffixStripped = !0), pos = pos >= buffer.length ? buffer.length - 1 : pos < opts.prefix.length ? opts.prefix.length : pos; var needsRefresh = !1, charAtPos = buffer[pos], cbuf = buffer.slice(); charAtPos === opts.groupSeparator && (cbuf.splice(pos--, 1), charAtPos = cbuf[pos]), charAtPos !== opts.radixPoint && charAtPos !== opts.negationSymbol.front && charAtPos !== opts.negationSymbol.back && (cbuf[pos] = "?"); var bufVal = cbuf.join(""), bufValOrigin = bufVal; if (bufVal.length > 0 && opts.autoGroup || -1 !== bufVal.indexOf(opts.groupSeparator)) { var escapedGroupSeparator = Inputmask.escapeRegex(opts.groupSeparator); needsRefresh = 0 === bufVal.indexOf(opts.groupSeparator), bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), ""); var radixSplit = bufVal.split(opts.radixPoint); if (bufVal = "" === opts.radixPoint ? bufVal : radixSplit[0], bufVal !== opts.prefix + "?0" && bufVal.length >= opts.groupSize + opts.prefix.length) for (var reg = new RegExp("([-+]?[\\d?]+)([\\d?]{" + opts.groupSize + "})"); reg.test(bufVal) && "" !== opts.groupSeparator; ) bufVal = bufVal.replace(reg, "$1" + opts.groupSeparator + "$2"), bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator); "" !== opts.radixPoint && radixSplit.length > 1 && (bufVal += opts.radixPoint + radixSplit[1]); } for (needsRefresh = bufValOrigin !== bufVal, buffer.length = bufVal.length, i = 0, l = bufVal.length; l > i; i++) buffer[i] = bufVal.charAt(i); var newPos = $.inArray("?", buffer); if (-1 === newPos && (newPos = $.inArray(charAtPos, buffer)), buffer[newPos] = charAtPos, !needsRefresh && suffixStripped) for (i = 0, l = opts.suffix.length; l > i; i++) buffer.push(opts.suffix.charAt(i)); return newPos = opts.numericInput && isFinite(pos) ? buffer.join("").length - newPos - 1 : newPos, opts.numericInput && (buffer = buffer.reverse(), $.inArray(opts.radixPoint, buffer) < newPos && buffer.join("").length - opts.suffix.length !== newPos && (newPos -= 1)), { pos: newPos, refreshFromBuffer: needsRefresh, buffer: buffer }; }, onBeforeWrite: function(e, buffer, caretPos, opts) { var rslt; if (e && ("blur" === e.type || "checkval" === e.type || "keydown" === e.type)) { var maskedValue = opts.numericInput ? buffer.slice().reverse().join("") : buffer.join(""), processValue = maskedValue.replace(opts.prefix, ""), minmaxed = !1; processValue = processValue.replace(opts.suffix, ""), processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""), "," === opts.radixPoint && (processValue = processValue.replace(opts.radixPoint, ".")); var isNegative = processValue.match(new RegExp("[-" + Inputmask.escapeRegex(opts.negationSymbol.front) + "]", "g")); if (isNegative = null !== isNegative && 1 === isNegative.length, processValue = processValue.replace(new RegExp("[-" + Inputmask.escapeRegex(opts.negationSymbol.front) + "]", "g"), ""), processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.negationSymbol.back) + "$"), ""), processValue = processValue === opts.negationSymbol.front ? processValue + "0" : processValue, isFinite(processValue)) { var floatValue = parseFloat(processValue), signedFloatValue = isNegative ? -1 * floatValue : floatValue; if (null !== opts.min && isFinite(opts.min) && signedFloatValue < parseFloat(opts.min) && (floatValue = Math.abs(opts.min), isNegative = opts.min < 0, minmaxed = !0), !minmaxed && null !== opts.max && isFinite(opts.max) && signedFloatValue > parseFloat(opts.max) && (floatValue = Math.abs(opts.max), isNegative = opts.max < 0, minmaxed = !0), processValue = floatValue.toString().replace(".", opts.radixPoint).split(""), isFinite(opts.digits)) { var radixPosition = $.inArray(opts.radixPoint, processValue), rpb = $.inArray(opts.radixPoint, maskedValue); -1 === radixPosition && (processValue.push(opts.radixPoint), radixPosition = processValue.length - 1); for (var i = 1; i <= opts.digits; i++) opts.digitsOptional || void 0 !== processValue[radixPosition + i] && processValue[radixPosition + i] !== opts.placeholder.charAt(0) ? -1 !== rpb && void 0 !== maskedValue[rpb + i] && (processValue[radixPosition + i] = processValue[radixPosition + i] || maskedValue[rpb + i]) : processValue[radixPosition + i] = "0"; processValue[processValue.length - 1] === opts.radixPoint && delete processValue[processValue.length - 1]; } if (floatValue.toString() !== processValue && floatValue.toString() + "." !== processValue || isNegative) return !isNegative || 0 === floatValue && "blur" === e.type || (processValue.unshift(opts.negationSymbol.front), processValue.push(opts.negationSymbol.back)), processValue = (opts.prefix + processValue.join("")).split(""), opts.numericInput && (processValue = processValue.reverse()), rslt = opts.postFormat(processValue, opts.numericInput ? caretPos : caretPos - 1, opts), rslt.buffer && (rslt.refreshFromBuffer = rslt.buffer.join("") !== buffer.join("")), rslt; } } return opts.autoGroup ? (rslt = opts.postFormat(buffer, opts.numericInput ? caretPos : caretPos - 1, opts), rslt.caret = caretPos <= opts.prefix.length ? rslt.pos : rslt.pos + 1, rslt) : void 0; }, regex: { integerPart: function(opts) { return new RegExp("[" + Inputmask.escapeRegex(opts.negationSymbol.front) + "+]?\\d+"); }, integerNPart: function(opts) { return new RegExp("[\\d" + Inputmask.escapeRegex(opts.groupSeparator) + Inputmask.escapeRegex(opts.placeholder.charAt(0)) + "]+"); } }, signHandler: function(chrs, maskset, pos, strict, opts) { if (!strict && opts.allowMinus && "-" === chrs || opts.allowPlus && "+" === chrs) { var matchRslt = maskset.buffer.join("").match(opts.regex.integerPart(opts)); if (matchRslt && matchRslt[0].length > 0) return maskset.buffer[matchRslt.index] === ("-" === chrs ? "+" : opts.negationSymbol.front) ? "-" === chrs ? "" !== opts.negationSymbol.back ? { pos: matchRslt.index, c: opts.negationSymbol.front, remove: matchRslt.index, caret: pos, insert: { pos: maskset.buffer.length - opts.suffix.length - 1, c: opts.negationSymbol.back } } : { pos: matchRslt.index, c: opts.negationSymbol.front, remove: matchRslt.index, caret: pos } : "" !== opts.negationSymbol.back ? { pos: matchRslt.index, c: "+", remove: [ matchRslt.index, maskset.buffer.length - opts.suffix.length - 1 ], caret: pos } : { pos: matchRslt.index, c: "+", remove: matchRslt.index, caret: pos } : maskset.buffer[matchRslt.index] === ("-" === chrs ? opts.negationSymbol.front : "+") ? "-" === chrs && "" !== opts.negationSymbol.back ? { remove: [ matchRslt.index, maskset.buffer.length - opts.suffix.length - 1 ], caret: pos - 1 } : { remove: matchRslt.index, caret: pos - 1 } : "-" === chrs ? "" !== opts.negationSymbol.back ? { pos: matchRslt.index, c: opts.negationSymbol.front, caret: pos + 1, insert: { pos: maskset.buffer.length - opts.suffix.length, c: opts.negationSymbol.back } } : { pos: matchRslt.index, c: opts.negationSymbol.front, caret: pos + 1 } : { pos: matchRslt.index, c: chrs, caret: pos + 1 }; } return !1; }, radixHandler: function(chrs, maskset, pos, strict, opts) { if (!strict && (-1 !== $.inArray(chrs, [ ",", "." ]) && (chrs = opts.radixPoint), chrs === opts.radixPoint && void 0 !== opts.digits && (isNaN(opts.digits) || parseInt(opts.digits) > 0))) { var radixPos = $.inArray(opts.radixPoint, maskset.buffer), integerValue = maskset.buffer.join("").match(opts.regex.integerPart(opts)); if (-1 !== radixPos && maskset.validPositions[radixPos]) return maskset.validPositions[radixPos - 1] ? { caret: radixPos + 1 } : { pos: integerValue.index, c: integerValue[0], caret: radixPos + 1 }; if (!integerValue || "0" === integerValue[0] && integerValue.index + 1 !== pos) return maskset.buffer[integerValue ? integerValue.index : pos] = "0", { pos: (integerValue ? integerValue.index : pos) + 1, c: opts.radixPoint }; } return !1; }, leadingZeroHandler: function(chrs, maskset, pos, strict, opts) { if (opts.numericInput === !0) { if ("0" === maskset.buffer[maskset.buffer.length - opts.prefix.length - 1]) return { pos: pos, remove: maskset.buffer.length - opts.prefix.length - 1 }; } else { var radixPosition = $.inArray(opts.radixPoint, maskset.buffer), matchRslt = maskset.buffer.slice(0, -1 !== radixPosition ? radixPosition : void 0).join("").match(opts.regex.integerNPart(opts)); if (matchRslt && !strict && (-1 === radixPosition || radixPosition >= pos)) { if (0 === matchRslt[0].indexOf("" !== opts.placeholder ? opts.placeholder.charAt(0) : "0") && matchRslt.index + 1 === pos) return maskset.buffer.splice(matchRslt.index, 1), pos = matchRslt.index, { pos: pos, remove: matchRslt.index }; if ("0" === chrs && pos <= matchRslt.index && matchRslt[0] !== opts.groupSeparator) return !1; } } return !0; }, definitions: { "~": { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.signHandler(chrs, maskset, pos, strict, opts); if (!isValid && (isValid = opts.radixHandler(chrs, maskset, pos, strict, opts), !isValid && (isValid = strict ? new RegExp("[0-9" + Inputmask.escapeRegex(opts.groupSeparator) + "]").test(chrs) : new RegExp("[0-9]").test(chrs), isValid === !0 && (isValid = opts.leadingZeroHandler(chrs, maskset, pos, strict, opts), isValid === !0)))) { var radixPosition = $.inArray(opts.radixPoint, maskset.buffer); isValid = -1 !== radixPosition && (opts.digitsOptional === !1 || maskset.validPositions[pos]) && opts.numericInput !== !0 && pos > radixPosition && !strict ? { pos: pos, remove: pos } : { pos: pos }; } return isValid; }, cardinality: 1, prevalidator: null }, "+": { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.signHandler(chrs, maskset, pos, strict, opts); return !isValid && (strict && opts.allowMinus && chrs === opts.negationSymbol.front || opts.allowMinus && "-" === chrs || opts.allowPlus && "+" === chrs) && (isValid = "-" === chrs ? "" !== opts.negationSymbol.back ? { pos: pos, c: "-" === chrs ? opts.negationSymbol.front : "+", caret: pos + 1, insert: { pos: maskset.buffer.length, c: opts.negationSymbol.back } } : { pos: pos, c: "-" === chrs ? opts.negationSymbol.front : "+", caret: pos + 1 } : !0), isValid; }, cardinality: 1, prevalidator: null, placeholder: "" }, "-": { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.signHandler(chrs, maskset, pos, strict, opts); return !isValid && strict && opts.allowMinus && chrs === opts.negationSymbol.back && (isValid = !0), isValid; }, cardinality: 1, prevalidator: null, placeholder: "" }, ":": { validator: function(chrs, maskset, pos, strict, opts) { var isValid = opts.signHandler(chrs, maskset, pos, strict, opts); if (!isValid) { var radix = "[" + Inputmask.escapeRegex(opts.radixPoint) + ",\\.]"; isValid = new RegExp(radix).test(chrs), isValid && maskset.validPositions[pos] && maskset.validPositions[pos].match.placeholder === opts.radixPoint && (isValid = { caret: pos + 1 }); } return isValid ? { c: opts.radixPoint } : isValid; }, cardinality: 1, prevalidator: null, placeholder: function(opts) { return opts.radixPoint; } } }, onUnMask: function(maskedValue, unmaskedValue, opts) { var processValue = maskedValue.replace(opts.prefix, ""); return processValue = processValue.replace(opts.suffix, ""), processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""), opts.unmaskAsNumber ? ("" !== opts.radixPoint && -1 !== processValue.indexOf(opts.radixPoint) && (processValue = processValue.replace(Inputmask.escapeRegex.call(this, opts.radixPoint), ".")), Number(processValue)) : processValue; }, isComplete: function(buffer, opts) { var maskedValue = buffer.join(""), bufClone = buffer.slice(); if (opts.postFormat(bufClone, 0, opts), bufClone.join("") !== maskedValue) return !1; var processValue = maskedValue.replace(opts.prefix, ""); return processValue = processValue.replace(opts.suffix, ""), processValue = processValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""), "," === opts.radixPoint && (processValue = processValue.replace(Inputmask.escapeRegex(opts.radixPoint), ".")), isFinite(processValue); }, onBeforeMask: function(initialValue, opts) { if ("" !== opts.radixPoint && isFinite(initialValue)) initialValue = initialValue.toString().replace(".", opts.radixPoint); else { var kommaMatches = initialValue.match(/,/g), dotMatches = initialValue.match(/\./g); dotMatches && kommaMatches ? dotMatches.length > kommaMatches.length ? (initialValue = initialValue.replace(/\./g, ""), initialValue = initialValue.replace(",", opts.radixPoint)) : kommaMatches.length > dotMatches.length ? (initialValue = initialValue.replace(/,/g, ""), initialValue = initialValue.replace(".", opts.radixPoint)) : initialValue = initialValue.indexOf(".") < initialValue.indexOf(",") ? initialValue.replace(/\./g, "") : initialValue = initialValue.replace(/,/g, "") : initialValue = initialValue.replace(new RegExp(Inputmask.escapeRegex(opts.groupSeparator), "g"), ""); } if (0 === opts.digits && (-1 !== initialValue.indexOf(".") ? initialValue = initialValue.substring(0, initialValue.indexOf(".")) : -1 !== initialValue.indexOf(",") && (initialValue = initialValue.substring(0, initialValue.indexOf(",")))), "" !== opts.radixPoint && isFinite(opts.digits) && -1 !== initialValue.indexOf(opts.radixPoint)) { var valueParts = initialValue.split(opts.radixPoint), decPart = valueParts[1].match(new RegExp("\\d*"))[0]; if (parseInt(opts.digits) < decPart.toString().length) { var digitsFactor = Math.pow(10, parseInt(opts.digits)); initialValue = initialValue.replace(Inputmask.escapeRegex(opts.radixPoint), "."), initialValue = Math.round(parseFloat(initialValue) * digitsFactor) / digitsFactor, initialValue = initialValue.toString().replace(".", opts.radixPoint); } } return initialValue.toString(); }, canClearPosition: function(maskset, position, lvp, strict, opts) { var positionInput = maskset.validPositions[position].input, canClear = positionInput !== opts.radixPoint || null !== maskset.validPositions[position].match.fn && opts.decimalProtect === !1 || isFinite(positionInput) || position === lvp || positionInput === opts.groupSeparator || positionInput === opts.negationSymbol.front || positionInput === opts.negationSymbol.back; return canClear; }, onKeyDown: function(e, buffer, caretPos, opts) { var $input = $(this); if (e.ctrlKey) switch (e.keyCode) { case Inputmask.keyCode.UP: $input.val(parseFloat(this.inputmask.unmaskedvalue()) + parseInt(opts.step)), $input.trigger("setvalue"); break; case Inputmask.keyCode.DOWN: $input.val(parseFloat(this.inputmask.unmaskedvalue()) - parseInt(opts.step)), $input.trigger("setvalue"); } } }, currency: { prefix: "$ ", groupSeparator: ",", alias: "numeric", placeholder: "0", autoGroup: !0, digits: 2, digitsOptional: !1, clearMaskOnLostFocus: !1 }, decimal: { alias: "numeric" }, integer: { alias: "numeric", digits: 0, radixPoint: "" }, percentage: { alias: "numeric", digits: 2, radixPoint: ".", placeholder: "0", autoGroup: !1, min: 0, max: 100, suffix: " %", allowPlus: !1, allowMinus: !1 } }), Inputmask; }(jQuery, Inputmask), function($, Inputmask) { return Inputmask.extendAliases({ phone: { url: "phone-codes/phone-codes.js", countrycode: "", phoneCodeCache: {}, mask: function(opts) { if (void 0 === opts.phoneCodeCache[opts.url]) { var maskList = []; opts.definitions["#"] = opts.definitions[9], $.ajax({ url: opts.url, async: !1, type: "get", dataType: "json", success: function(response) { maskList = response; }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + " - " + opts.url); } }), opts.phoneCodeCache[opts.url] = maskList.sort(function(a, b) { return (a.mask || a) < (b.mask || b) ? -1 : 1; }); } return opts.phoneCodeCache[opts.url]; }, keepStatic: !1, nojumps: !0, nojumpsThreshold: 1, onBeforeMask: function(value, opts) { var processedValue = value.replace(/^0{1,2}/, "").replace(/[\s]/g, ""); return (processedValue.indexOf(opts.countrycode) > 1 || -1 === processedValue.indexOf(opts.countrycode)) && (processedValue = "+" + opts.countrycode + processedValue), processedValue; } }, phonebe: { alias: "phone", url: "phone-codes/phone-be.js", countrycode: "32", nojumpsThreshold: 4 } }), Inputmask; }(jQuery, Inputmask), function($, Inputmask) { return Inputmask.extendAliases({ Regex: { mask: "r", greedy: !1, repeat: "*", regex: null, regexTokens: null, tokenizer: /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g, quantifierFilter: /[0-9]+[^,]/, isComplete: function(buffer, opts) { return new RegExp(opts.regex).test(buffer.join("")); }, definitions: { r: { validator: function(chrs, maskset, pos, strict, opts) { function RegexToken(isGroup, isQuantifier) { this.matches = [], this.isGroup = isGroup || !1, this.isQuantifier = isQuantifier || !1, this.quantifier = { min: 1, max: 1 }, this.repeaterPart = void 0; } function analyseRegex() { var match, m, currentToken = new RegexToken(), opengroups = []; for (opts.regexTokens = []; match = opts.tokenizer.exec(opts.regex); ) switch (m = match[0], m.charAt(0)) { case "(": opengroups.push(new RegexToken(!0)); break; case ")": groupToken = opengroups.pop(), opengroups.length > 0 ? opengroups[opengroups.length - 1].matches.push(groupToken) : currentToken.matches.push(groupToken); break; case "{": case "+": case "*": var quantifierToken = new RegexToken(!1, !0); m = m.replace(/[{}]/g, ""); var mq = m.split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = 1 === mq.length ? mq0 : isNaN(mq[1]) ? mq[1] : parseInt(mq[1]); if (quantifierToken.quantifier = { min: mq0, max: mq1 }, opengroups.length > 0) { var matches = opengroups[opengroups.length - 1].matches; match = matches.pop(), match.isGroup || (groupToken = new RegexToken(!0), groupToken.matches.push(match), match = groupToken), matches.push(match), matches.push(quantifierToken); } else match = currentToken.matches.pop(), match.isGroup || (groupToken = new RegexToken(!0), groupToken.matches.push(match), match = groupToken), currentToken.matches.push(match), currentToken.matches.push(quantifierToken); break; default: opengroups.length > 0 ? opengroups[opengroups.length - 1].matches.push(m) : currentToken.matches.push(m); } currentToken.matches.length > 0 && opts.regexTokens.push(currentToken); } function validateRegexToken(token, fromGroup) { var isvalid = !1; fromGroup && (regexPart += "(", openGroupCount++); for (var mndx = 0; mndx < token.matches.length; mndx++) { var matchToken = token.matches[mndx]; if (matchToken.isGroup === !0) isvalid = validateRegexToken(matchToken, !0); else if (matchToken.isQuantifier === !0) { var crrntndx = $.inArray(matchToken, token.matches), matchGroup = token.matches[crrntndx - 1], regexPartBak = regexPart; if (isNaN(matchToken.quantifier.max)) { for (;matchToken.repeaterPart && matchToken.repeaterPart !== regexPart && matchToken.repeaterPart.length > regexPart.length && !(isvalid = validateRegexToken(matchGroup, !0)); ) ; isvalid = isvalid || validateRegexToken(matchGroup, !0), isvalid && (matchToken.repeaterPart = regexPart), regexPart = regexPartBak + matchToken.quantifier.max; } else { for (var i = 0, qm = matchToken.quantifier.max - 1; qm > i && !(isvalid = validateRegexToken(matchGroup, !0)); i++) ; regexPart = regexPartBak + "{" + matchToken.quantifier.min + "," + matchToken.quantifier.max + "}"; } } else if (void 0 !== matchToken.matches) for (var k = 0; k < matchToken.length && !(isvalid = validateRegexToken(matchToken[k], fromGroup)); k++) ; else { var testExp; if ("[" == matchToken.charAt(0)) { testExp = regexPart, testExp += matchToken; for (var j = 0; openGroupCount > j; j++) testExp += ")"; var exp = new RegExp("^(" + testExp + ")$"); isvalid = exp.test(bufferStr); } else for (var l = 0, tl = matchToken.length; tl > l; l++) if ("\\" !== matchToken.charAt(l)) { testExp = regexPart, testExp += matchToken.substr(0, l + 1), testExp = testExp.replace(/\|$/, ""); for (var j = 0; openGroupCount > j; j++) testExp += ")"; var exp = new RegExp("^(" + testExp + ")$"); if (isvalid = exp.test(bufferStr)) break; } regexPart += matchToken; } if (isvalid) break; } return fromGroup && (regexPart += ")", openGroupCount--), isvalid; } var bufferStr, groupToken, cbuffer = maskset.buffer.slice(), regexPart = "", isValid = !1, openGroupCount = 0; null === opts.regexTokens && analyseRegex(), cbuffer.splice(pos, 0, chrs), bufferStr = cbuffer.join(""); for (var i = 0; i < opts.regexTokens.length; i++) { var regexToken = opts.regexTokens[i]; if (isValid = validateRegexToken(regexToken, regexToken.isGroup)) break; } return isValid; }, cardinality: 1 } } } }), Inputmask; }(jQuery, Inputmask);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-inputmask-bundle-3.2.8.js
jquery-inputmask-bundle-3.2.8.js
(function( jQuery, undefined ) { var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor", // plusequals test for += 100 -= 100 rplusequals = /^([\-+])=\s*(\d+\.?\d*)/, // a set of RE's that can match strings and generate color tuples. stringParsers = [{ re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ], execResult[ 3 ], execResult[ 4 ] ]; } }, { re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ] * 2.55, execResult[ 2 ] * 2.55, execResult[ 3 ] * 2.55, execResult[ 4 ] ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ], 16 ), parseInt( execResult[ 2 ], 16 ), parseInt( execResult[ 3 ], 16 ) ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9])([a-f0-9])([a-f0-9])/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ), parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ), parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ) ]; } }, { re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, space: "hsla", parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ] / 100, execResult[ 3 ] / 100, execResult[ 4 ] ]; } }], // jQuery.Color( ) color = jQuery.Color = function( color, green, blue, alpha ) { return new jQuery.Color.fn.parse( color, green, blue, alpha ); }, spaces = { rgba: { props: { red: { idx: 0, type: "byte" }, green: { idx: 1, type: "byte" }, blue: { idx: 2, type: "byte" } } }, hsla: { props: { hue: { idx: 0, type: "degrees" }, saturation: { idx: 1, type: "percent" }, lightness: { idx: 2, type: "percent" } } } }, propTypes = { "byte": { floor: true, max: 255 }, "percent": { max: 1 }, "degrees": { mod: 360, floor: true } }, support = color.support = {}, // element for support tests supportElem = jQuery( "<p>" )[ 0 ], // colors = jQuery.Color.names colors, // local aliases of functions called often each = jQuery.each; // determine rgba support immediately supportElem.style.cssText = "background-color:rgba(1,1,1,.5)"; support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1; // define cache name and alpha properties // for rgba and hsla spaces each( spaces, function( spaceName, space ) { space.cache = "_" + spaceName; space.props.alpha = { idx: 3, type: "percent", def: 1 }; }); function clamp( value, prop, allowEmpty ) { var type = propTypes[ prop.type ] || {}; if ( value == null ) { return (allowEmpty || !prop.def) ? null : prop.def; } // ~~ is an short way of doing floor for positive numbers value = type.floor ? ~~value : parseFloat( value ); // IE will pass in empty strings as value for alpha, // which will hit this case if ( isNaN( value ) ) { return prop.def; } if ( type.mod ) { // we add mod before modding to make sure that negatives values // get converted properly: -10 -> 350 return (value + type.mod) % type.mod; } // for now all property types without mod have min and max return 0 > value ? 0 : type.max < value ? type.max : value; } function stringParse( string ) { var inst = color(), rgba = inst._rgba = []; string = string.toLowerCase(); each( stringParsers, function( i, parser ) { var parsed, match = parser.re.exec( string ), values = match && parser.parse( match ), spaceName = parser.space || "rgba"; if ( values ) { parsed = inst[ spaceName ]( values ); // if this was an rgba parse the assignment might happen twice // oh well.... inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ]; rgba = inst._rgba = parsed._rgba; // exit each( stringParsers ) here because we matched return false; } }); // Found a stringParser that handled it if ( rgba.length ) { // if this came from a parsed string, force "transparent" when alpha is 0 // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0) if ( rgba.join() === "0,0,0,0" ) { jQuery.extend( rgba, colors.transparent ); } return inst; } // named colors return colors[ string ]; } color.fn = jQuery.extend( color.prototype, { parse: function( red, green, blue, alpha ) { if ( red === undefined ) { this._rgba = [ null, null, null, null ]; return this; } if ( red.jquery || red.nodeType ) { red = jQuery( red ).css( green ); green = undefined; } var inst = this, type = jQuery.type( red ), rgba = this._rgba = []; // more than 1 argument specified - assume ( red, green, blue, alpha ) if ( green !== undefined ) { red = [ red, green, blue, alpha ]; type = "array"; } if ( type === "string" ) { return this.parse( stringParse( red ) || colors._default ); } if ( type === "array" ) { each( spaces.rgba.props, function( key, prop ) { rgba[ prop.idx ] = clamp( red[ prop.idx ], prop ); }); return this; } if ( type === "object" ) { if ( red instanceof color ) { each( spaces, function( spaceName, space ) { if ( red[ space.cache ] ) { inst[ space.cache ] = red[ space.cache ].slice(); } }); } else { each( spaces, function( spaceName, space ) { var cache = space.cache; each( space.props, function( key, prop ) { // if the cache doesn't exist, and we know how to convert if ( !inst[ cache ] && space.to ) { // if the value was null, we don't need to copy it // if the key was alpha, we don't need to copy it either if ( key === "alpha" || red[ key ] == null ) { return; } inst[ cache ] = space.to( inst._rgba ); } // this is the only case where we allow nulls for ALL properties. // call clamp with alwaysAllowEmpty inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true ); }); // everything defined but alpha? if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) { // use the default of 1 inst[ cache ][ 3 ] = 1; if ( space.from ) { inst._rgba = space.from( inst[ cache ] ); } } }); } return this; } }, is: function( compare ) { var is = color( compare ), same = true, inst = this; each( spaces, function( _, space ) { var localCache, isCache = is[ space.cache ]; if (isCache) { localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || []; each( space.props, function( _, prop ) { if ( isCache[ prop.idx ] != null ) { same = ( isCache[ prop.idx ] === localCache[ prop.idx ] ); return same; } }); } return same; }); return same; }, _space: function() { var used = [], inst = this; each( spaces, function( spaceName, space ) { if ( inst[ space.cache ] ) { used.push( spaceName ); } }); return used.pop(); }, transition: function( other, distance ) { var end = color( other ), spaceName = end._space(), space = spaces[ spaceName ], startColor = this.alpha() === 0 ? color( "transparent" ) : this, start = startColor[ space.cache ] || space.to( startColor._rgba ), result = start.slice(); end = end[ space.cache ]; each( space.props, function( key, prop ) { var index = prop.idx, startValue = start[ index ], endValue = end[ index ], type = propTypes[ prop.type ] || {}; // if null, don't override start value if ( endValue === null ) { return; } // if null - use end if ( startValue === null ) { result[ index ] = endValue; } else { if ( type.mod ) { if ( endValue - startValue > type.mod / 2 ) { startValue += type.mod; } else if ( startValue - endValue > type.mod / 2 ) { startValue -= type.mod; } } result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop ); } }); return this[ spaceName ]( result ); }, blend: function( opaque ) { // if we are already opaque - return ourself if ( this._rgba[ 3 ] === 1 ) { return this; } var rgb = this._rgba.slice(), a = rgb.pop(), blend = color( opaque )._rgba; return color( jQuery.map( rgb, function( v, i ) { return ( 1 - a ) * blend[ i ] + a * v; })); }, toRgbaString: function() { var prefix = "rgba(", rgba = jQuery.map( this._rgba, function( v, i ) { return v == null ? ( i > 2 ? 1 : 0 ) : v; }); if ( rgba[ 3 ] === 1 ) { rgba.pop(); prefix = "rgb("; } return prefix + rgba.join() + ")"; }, toHslaString: function() { var prefix = "hsla(", hsla = jQuery.map( this.hsla(), function( v, i ) { if ( v == null ) { v = i > 2 ? 1 : 0; } // catch 1 and 2 if ( i && i < 3 ) { v = Math.round( v * 100 ) + "%"; } return v; }); if ( hsla[ 3 ] === 1 ) { hsla.pop(); prefix = "hsl("; } return prefix + hsla.join() + ")"; }, toHexString: function( includeAlpha ) { var rgba = this._rgba.slice(), alpha = rgba.pop(); if ( includeAlpha ) { rgba.push( ~~( alpha * 255 ) ); } return "#" + jQuery.map( rgba, function( v ) { // default to 0 when nulls exist v = ( v || 0 ).toString( 16 ); return v.length === 1 ? "0" + v : v; }).join(""); }, toString: function() { return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString(); } }); color.fn.parse.prototype = color.fn; // hsla conversions adapted from: // https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021 function hue2rgb( p, q, h ) { h = ( h + 1 ) % 1; if ( h * 6 < 1 ) { return p + (q - p) * h * 6; } if ( h * 2 < 1) { return q; } if ( h * 3 < 2 ) { return p + (q - p) * ((2/3) - h) * 6; } return p; } spaces.hsla.to = function ( rgba ) { if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) { return [ null, null, null, rgba[ 3 ] ]; } var r = rgba[ 0 ] / 255, g = rgba[ 1 ] / 255, b = rgba[ 2 ] / 255, a = rgba[ 3 ], max = Math.max( r, g, b ), min = Math.min( r, g, b ), diff = max - min, add = max + min, l = add * 0.5, h, s; if ( min === max ) { h = 0; } else if ( r === max ) { h = ( 60 * ( g - b ) / diff ) + 360; } else if ( g === max ) { h = ( 60 * ( b - r ) / diff ) + 120; } else { h = ( 60 * ( r - g ) / diff ) + 240; } // chroma (diff) == 0 means greyscale which, by definition, saturation = 0% // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add) if ( diff === 0 ) { s = 0; } else if ( l <= 0.5 ) { s = diff / add; } else { s = diff / ( 2 - add ); } return [ Math.round(h) % 360, s, l, a == null ? 1 : a ]; }; spaces.hsla.from = function ( hsla ) { if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) { return [ null, null, null, hsla[ 3 ] ]; } var h = hsla[ 0 ] / 360, s = hsla[ 1 ], l = hsla[ 2 ], a = hsla[ 3 ], q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s, p = 2 * l - q; return [ Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ), Math.round( hue2rgb( p, q, h ) * 255 ), Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ), a ]; }; each( spaces, function( spaceName, space ) { var props = space.props, cache = space.cache, to = space.to, from = space.from; // makes rgba() and hsla() color.fn[ spaceName ] = function( value ) { // generate a cache for this space if it doesn't exist if ( to && !this[ cache ] ) { this[ cache ] = to( this._rgba ); } if ( value === undefined ) { return this[ cache ].slice(); } var ret, type = jQuery.type( value ), arr = ( type === "array" || type === "object" ) ? value : arguments, local = this[ cache ].slice(); each( props, function( key, prop ) { var val = arr[ type === "object" ? key : prop.idx ]; if ( val == null ) { val = local[ prop.idx ]; } local[ prop.idx ] = clamp( val, prop ); }); if ( from ) { ret = color( from( local ) ); ret[ cache ] = local; return ret; } else { return color( local ); } }; // makes red() green() blue() alpha() hue() saturation() lightness() each( props, function( key, prop ) { // alpha is included in more than one space if ( color.fn[ key ] ) { return; } color.fn[ key ] = function( value ) { var vtype = jQuery.type( value ), fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ), local = this[ fn ](), cur = local[ prop.idx ], match; if ( vtype === "undefined" ) { return cur; } if ( vtype === "function" ) { value = value.call( this, cur ); vtype = jQuery.type( value ); } if ( value == null && prop.empty ) { return this; } if ( vtype === "string" ) { match = rplusequals.exec( value ); if ( match ) { value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 ); } } local[ prop.idx ] = value; return this[ fn ]( local ); }; }); }); // add cssHook and .fx.step function for each named hook. // accept a space separated string of properties color.hook = function( hook ) { var hooks = hook.split( " " ); each( hooks, function( i, hook ) { jQuery.cssHooks[ hook ] = { set: function( elem, value ) { var parsed, curElem, backgroundColor = ""; if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) { value = color( parsed || value ); if ( !support.rgba && value._rgba[ 3 ] !== 1 ) { curElem = hook === "backgroundColor" ? elem.parentNode : elem; while ( (backgroundColor === "" || backgroundColor === "transparent") && curElem && curElem.style ) { try { backgroundColor = jQuery.css( curElem, "backgroundColor" ); curElem = curElem.parentNode; } catch ( e ) { } } value = value.blend( backgroundColor && backgroundColor !== "transparent" ? backgroundColor : "_default" ); } value = value.toRgbaString(); } try { elem.style[ hook ] = value; } catch( e ) { // wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit' } } }; jQuery.fx.step[ hook ] = function( fx ) { if ( !fx.colorInit ) { fx.start = color( fx.elem, hook ); fx.end = color( fx.end ); fx.colorInit = true; } jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) ); }; }); }; color.hook( stepHooks ); jQuery.cssHooks.borderColor = { expand: function( value ) { var expanded = {}; each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) { expanded[ "border" + part + "Color" ] = value; }); return expanded; } }; // Basic color names only. // Usage of any of the other color names requires adding yourself or including // jquery.color.svg-names.js. colors = jQuery.Color.names = { // 4.1. Basic color keywords aqua: "#00ffff", black: "#000000", blue: "#0000ff", fuchsia: "#ff00ff", gray: "#808080", green: "#008000", lime: "#00ff00", maroon: "#800000", navy: "#000080", olive: "#808000", purple: "#800080", red: "#ff0000", silver: "#c0c0c0", teal: "#008080", white: "#ffffff", yellow: "#ffff00", // 4.2.3. "transparent" color keyword transparent: [ null, null, null, 0 ], _default: "#ffffff" }; })( jQuery );
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-color-2.1.2.js
jquery-color-2.1.2.js
(function(a){var b={i18n:{ar:{months:["كانون الثاني","شباط","آذار","نيسان","مايو","حزيران","تموز","آب","أيلول","تشرين الأول","تشرين الثاني","كانون الأول"],dayOfWeek:["ن","ث","ع","خ","ج","س","ح"]},ro:{months:["ianuarie","februarie","martie","aprilie","mai","iunie","iulie","august","septembrie","octombrie","noiembrie","decembrie"],dayOfWeek:["l","ma","mi","j","v","s","d"]},id:{months:["Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember"],dayOfWeek:["Sen","Sel","Rab","Kam","Jum","Sab","Min"]},bg:{months:["Януари","Февруари","Март","Април","Май","Юни","Юли","Август","Септември","Октомври","Ноември","Декември"],dayOfWeek:["Нд","Пн","Вт","Ср","Чт","Пт","Сб"]},fa:{months:["فروردین","اردیبهشت","خرداد","تیر","مرداد","شهریور","مهر","آبان","آذر","دی","بهمن","اسفند"],dayOfWeek:["یکشنبه","دوشنبه","سه شنبه","چهارشنبه","پنجشنبه","جمعه","شنبه"]},ru:{months:["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"],dayOfWeek:["Вск","Пн","Вт","Ср","Чт","Пт","Сб"]},uk:{months:["Січень","Лютий","Березень","Квітень","Травень","Червень","Липень","Серпень","Вересень","Жовтень","Листопад","Грудень"],dayOfWeek:["Ндл","Пнд","Втр","Срд","Чтв","Птн","Сбт"]},en:{months:["January","February","March","April","May","June","July","August","September","October","November","December"],dayOfWeek:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},el:{months:["Ιανουάριος","Φεβρουάριος","Μάρτιος","Απρίλιος","Μάιος","Ιούνιος","Ιούλιος","Αύγουστος","Σεπτέμβριος","Οκτώβριος","Νοέμβριος","Δεκέμβριος"],dayOfWeek:["Κυρ","Δευ","Τρι","Τετ","Πεμ","Παρ","Σαβ"]},de:{months:["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],dayOfWeek:["So","Mo","Di","Mi","Do","Fr","Sa"]},nl:{months:["januari","februari","maart","april","mei","juni","juli","augustus","september","oktober","november","december"],dayOfWeek:["zo","ma","di","wo","do","vr","za"]},tr:{months:["Ocak","Şubat","Mart","Nisan","Mayıs","Haziran","Temmuz","Ağustos","Eylül","Ekim","Kasım","Aralık"],dayOfWeek:["Paz","Pts","Sal","Çar","Per","Cum","Cts"]},fr:{months:["Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre"],dayOfWeek:["Dim","Lun","Mar","Mer","Jeu","Ven","Sam"]},es:{months:["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],dayOfWeek:["Dom","Lun","Mar","Mié","Jue","Vie","Sáb"]},th:{months:["มกราคม","กุมภาพันธ์","มีนาคม","เมษายน","พฤษภาคม","มิถุนายน","กรกฎาคม","สิงหาคม","กันยายน","ตุลาคม","พฤศจิกายน","ธันวาคม"],dayOfWeek:["อา.","จ.","อ.","พ.","พฤ.","ศ.","ส."]},pl:{months:["styczeń","luty","marzec","kwiecień","maj","czerwiec","lipiec","sierpień","wrzesień","październik","listopad","grudzień"],dayOfWeek:["nd","pn","wt","śr","cz","pt","sb"]},pt:{months:["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],dayOfWeek:["Dom","Seg","Ter","Qua","Qui","Sex","Sab"]},ch:{months:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],dayOfWeek:["日","一","二","三","四","五","六"]},se:{months:["Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December"],dayOfWeek:["Sön","Mån","Tis","Ons","Tor","Fre","Lör"]},kr:{months:["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"],dayOfWeek:["일","월","화","수","목","금","토"]},it:{months:["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"],dayOfWeek:["Dom","Lun","Mar","Mer","Gio","Ven","Sab"]},da:{months:["January","Februar","Marts","April","Maj","Juni","July","August","September","Oktober","November","December"],dayOfWeek:["Søn","Man","Tir","Ons","Tor","Fre","Lør"]},no:{months:["Januar","Februar","Mars","April","Mai","Juni","Juli","August","September","Oktober","November","Desember"],dayOfWeek:["Søn","Man","Tir","Ons","Tor","Fre","Lør"]},ja:{months:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],dayOfWeek:["日","月","火","水","木","金","土"]},vi:{months:["Tháng 1","Tháng 2","Tháng 3","Tháng 4","Tháng 5","Tháng 6","Tháng 7","Tháng 8","Tháng 9","Tháng 10","Tháng 11","Tháng 12"],dayOfWeek:["CN","T2","T3","T4","T5","T6","T7"]},sl:{months:["Januar","Februar","Marec","April","Maj","Junij","Julij","Avgust","September","Oktober","November","December"],dayOfWeek:["Ned","Pon","Tor","Sre","Čet","Pet","Sob"]},cs:{months:["Leden","Únor","Březen","Duben","Květen","Červen","Červenec","Srpen","Září","Říjen","Listopad","Prosinec"],dayOfWeek:["Ne","Po","Út","St","Čt","Pá","So"]},hu:{months:["Január","Február","Március","Április","Május","Június","Július","Augusztus","Szeptember","Október","November","December"],dayOfWeek:["Va","Hé","Ke","Sze","Cs","Pé","Szo"]},az:{months:["Yanvar","Fevral","Mart","Aprel","May","Iyun","Iyul","Avqust","Sentyabr","Oktyabr","Noyabr","Dekabr"],dayOfWeek:["B","Be","Ça","Ç","Ca","C","Ş"]},bs:{months:["Januar","Februar","Mart","April","Maj","Jun","Jul","Avgust","Septembar","Oktobar","Novembar","Decembar"],dayOfWeek:["Ned","Pon","Uto","Sri","Čet","Pet","Sub"]},ca:{months:["Gener","Febrer","Març","Abril","Maig","Juny","Juliol","Agost","Setembre","Octubre","Novembre","Desembre"],dayOfWeek:["Dg","Dl","Dt","Dc","Dj","Dv","Ds"]},"en-GB":{months:["January","February","March","April","May","June","July","August","September","October","November","December"],dayOfWeek:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},et:{months:["Jaanuar","Veebruar","Märts","Aprill","Mai","Juuni","Juuli","August","September","Oktoober","November","Detsember"],dayOfWeek:["P","E","T","K","N","R","L"]},eu:{months:["Urtarrila","Otsaila","Martxoa","Apirila","Maiatza","Ekaina","Uztaila","Abuztua","Iraila","Urria","Azaroa","Abendua"],dayOfWeek:["Ig.","Al.","Ar.","Az.","Og.","Or.","La."]},fi:{months:["Tammikuu","Helmikuu","Maaliskuu","Huhtikuu","Toukokuu","Kesäkuu","Heinäkuu","Elokuu","Syyskuu","Lokakuu","Marraskuu","Joulukuu"],dayOfWeek:["Su","Ma","Ti","Ke","To","Pe","La"]},gl:{months:["Xan","Feb","Maz","Abr","Mai","Xun","Xul","Ago","Set","Out","Nov","Dec"],dayOfWeek:["Dom","Lun","Mar","Mer","Xov","Ven","Sab"]},hr:{months:["Siječanj","Veljača","Ožujak","Travanj","Svibanj","Lipanj","Srpanj","Kolovoz","Rujan","Listopad","Studeni","Prosinac"],dayOfWeek:["Ned","Pon","Uto","Sri","Čet","Pet","Sub"]},ko:{months:["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"],dayOfWeek:["일","월","화","수","목","금","토"]},lt:{months:["Sausio","Vasario","Kovo","Balandžio","Gegužės","Birželio","Liepos","Rugpjūčio","Rugsėjo","Spalio","Lapkričio","Gruodžio"],dayOfWeek:["Sek","Pir","Ant","Tre","Ket","Pen","Šeš"]},lv:{months:["Janvāris","Februāris","Marts","Aprīlis ","Maijs","Jūnijs","Jūlijs","Augusts","Septembris","Oktobris","Novembris","Decembris"],dayOfWeek:["Sv","Pr","Ot","Tr","Ct","Pk","St"]},mk:{months:["јануари","февруари","март","април","мај","јуни","јули","август","септември","октомври","ноември","декември"],dayOfWeek:["нед","пон","вто","сре","чет","пет","саб"]},mn:{months:["1-р сар","2-р сар","3-р сар","4-р сар","5-р сар","6-р сар","7-р сар","8-р сар","9-р сар","10-р сар","11-р сар","12-р сар"],dayOfWeek:["Дав","Мяг","Лха","Пүр","Бсн","Бям","Ням"]},"pt-BR":{months:["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],dayOfWeek:["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"]},sk:{months:["Január","Február","Marec","Apríl","Máj","Jún","Júl","August","September","Október","November","December"],dayOfWeek:["Ne","Po","Ut","St","Št","Pi","So"]},sq:{months:["January","February","March","April","May","June","July","August","September","October","November","December"],dayOfWeek:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},"sr-YU":{months:["Januar","Februar","Mart","April","Maj","Jun","Jul","Avgust","Septembar","Oktobar","Novembar","Decembar"],dayOfWeek:["Ned","Pon","Uto","Sre","čet","Pet","Sub"]},sr:{months:["јануар","фебруар","март","април","мај","јун","јул","август","септембар","октобар","новембар","децембар"],dayOfWeek:["нед","пон","уто","сре","чет","пет","суб"]},sv:{months:["Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December"],dayOfWeek:["Sön","Mån","Tis","Ons","Tor","Fre","Lör"]},"zh-TW":{months:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],dayOfWeek:["日","一","二","三","四","五","六"]},zh:{months:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],dayOfWeek:["日","一","二","三","四","五","六"]},he:{months:["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"],dayOfWeek:["א'","ב'","ג'","ד'","ה'","ו'","שבת"]},hy:{months:["Հունվար","Փետրվար","Մարտ","Ապրիլ","Մայիս","Հունիս","Հուլիս","Օգոստոս","Սեպտեմբեր","Հոկտեմբեր","Նոյեմբեր","Դեկտեմբեր"],dayOfWeek:["Կի","Երկ","Երք","Չոր","Հնգ","Ուրբ","Շբթ"]}},value:"",lang:"en",format:"Y/m/d H:i",formatTime:"H:i",formatDate:"Y/m/d",startDate:false,step:60,monthChangeSpinner:true,closeOnDateSelect:false,closeOnTimeSelect:false,closeOnWithoutClick:true,closeOnInputClick:true,timepicker:true,datepicker:true,weeks:false,defaultTime:false,defaultDate:false,minDate:false,maxDate:false,minTime:false,maxTime:false,allowTimes:[],opened:false,initTime:true,inline:false,theme:"",onSelectDate:function(){},onSelectTime:function(){},onChangeMonth:function(){},onChangeYear:function(){},onChangeDateTime:function(){},onShow:function(){},onClose:function(){},onGenerate:function(){},withoutCopyright:true,inverseButton:false,hours12:false,next:"xdsoft_next",prev:"xdsoft_prev",dayOfWeekStart:0,parentID:"body",timeHeightInTimePicker:25,timepickerScrollbar:true,todayButton:true,prevButton:true,nextButton:true,defaultSelect:true,scrollMonth:true,scrollTime:true,scrollInput:true,lazyInit:false,mask:false,validateOnBlur:true,allowBlank:true,yearStart:1950,yearEnd:2050,monthStart:0,monthEnd:11,style:"",id:"",fixed:false,roundTime:"round",className:"",weekends:[],disabledDates:[],yearOffset:0,beforeShowDay:null,enterLikeTab:true,showApplyButton:false};if(!Array.prototype.indexOf){Array.prototype.indexOf=function(e,f){var d,c;for(d=(f||0),c=this.length;d<c;d+=1){if(this[d]===e){return d}}return -1}}Date.prototype.countDaysInMonth=function(){return new Date(this.getFullYear(),this.getMonth()+1,0).getDate()};a.fn.xdsoftScroller=function(c){return this.each(function(){var m=a(this),n=function(u){var t={x:0,y:0},v;if(u.type==="touchstart"||u.type==="touchmove"||u.type==="touchend"||u.type==="touchcancel"){v=u.originalEvent.touches[0]||u.originalEvent.changedTouches[0];t.x=v.clientX;t.y=v.clientY}else{if(u.type==="mousedown"||u.type==="mouseup"||u.type==="mousemove"||u.type==="mouseover"||u.type==="mouseout"||u.type==="mouseenter"||u.type==="mouseleave"){t.x=u.clientX;t.y=u.clientY}}return t},g=0,q,k,r,s,j,p=100,e=false,i=0,l=0,o=0,f=false,d=0,h=function(){};if(c==="hide"){m.find(".xdsoft_scrollbar").hide();return}if(!a(this).hasClass("xdsoft_scroller_box")){q=m.children().eq(0);k=m[0].clientHeight;r=q[0].offsetHeight;s=a('<div class="xdsoft_scrollbar"></div>');j=a('<div class="xdsoft_scroller"></div>');s.append(j);m.addClass("xdsoft_scroller_box").append(s);h=function h(t){var u=n(t).y-i+d;if(u<0){u=0}if(u+j[0].offsetHeight>o){u=o-j[0].offsetHeight}m.trigger("scroll_element.xdsoft_scroller",[p?u/p:0])};j.on("touchstart.xdsoft_scroller mousedown.xdsoft_scroller",function(u){if(!k){m.trigger("resize_scroll.xdsoft_scroller",[c])}i=n(u).y;d=parseInt(j.css("margin-top"),10);o=s[0].offsetHeight;if(u.type==="mousedown"){if(document){a(document.body).addClass("xdsoft_noselect")}a([document.body,window]).on("mouseup.xdsoft_scroller",function t(){a([document.body,window]).off("mouseup.xdsoft_scroller",t).off("mousemove.xdsoft_scroller",h).removeClass("xdsoft_noselect")});a(document.body).on("mousemove.xdsoft_scroller",h)}else{f=true;u.stopPropagation();u.preventDefault()}}).on("touchmove",function(t){if(f){t.preventDefault();h(t)}}).on("touchend touchcancel",function(t){f=false;d=0});m.on("scroll_element.xdsoft_scroller",function(u,t){if(!k){m.trigger("resize_scroll.xdsoft_scroller",[t,true])}t=t>1?1:(t<0||isNaN(t))?0:t;j.css("margin-top",p*t);setTimeout(function(){q.css("marginTop",-parseInt((q[0].offsetHeight-k)*t,10))},10)}).on("resize_scroll.xdsoft_scroller",function(x,u,t){var w,v;k=m[0].clientHeight;r=q[0].offsetHeight;w=k/r;v=w*s[0].offsetHeight;if(w>1){j.hide()}else{j.show();j.css("height",parseInt(v>10?v:10,10));p=s[0].offsetHeight-j[0].offsetHeight;if(t!==true){m.trigger("scroll_element.xdsoft_scroller",[u||Math.abs(parseInt(q.css("marginTop"),10))/(r-k)])}}});m.on("mousewheel",function(t){var u=Math.abs(parseInt(q.css("marginTop"),10));u=u-(t.deltaY*20);if(u<0){u=0}m.trigger("scroll_element.xdsoft_scroller",[u/(r-k)]);t.stopPropagation();return false});m.on("touchstart",function(t){e=n(t);l=Math.abs(parseInt(q.css("marginTop"),10))});m.on("touchmove",function(t){if(e){t.preventDefault();var u=n(t);m.trigger("scroll_element.xdsoft_scroller",[(l-(u.y-e.y))/(r-k)])}});m.on("touchend touchcancel",function(t){e=false;l=0})}m.trigger("resize_scroll.xdsoft_scroller",[c])})};a.fn.datetimepicker=function(e){var t=48,o=57,i=96,c=105,l=17,q=46,m=13,C=27,y=8,u=37,r=38,A=39,B=40,h=9,v=116,w=65,d=67,z=86,p=90,k=89,x=false,g=(a.isPlainObject(e)||!e)?a.extend(true,{},b,e):a.extend(true,{},b),n=0,f,s,j=function(E){E.on("open.xdsoft focusin.xdsoft mousedown.xdsoft",function D(F){if(E.is(":disabled")||E.data("xdsoft_datetimepicker")){return}clearTimeout(n);n=setTimeout(function(){if(!E.data("xdsoft_datetimepicker")){f(E)}E.off("open.xdsoft focusin.xdsoft mousedown.xdsoft",D).trigger("open.xdsoft")},100)})};f=function(M){var O=a("<div "+(g.id?'id="'+g.id+'"':"")+" "+(g.style?'style="'+g.style+'"':"")+' class="xdsoft_datetimepicker xdsoft_'+g.theme+" xdsoft_noselect "+(g.weeks?" xdsoft_showweeks":"")+g.className+'"></div>'),S=a('<div class="xdsoft_copyright"><a target="_blank" href="http://xdsoft.net/jqplugins/datetimepicker/">xdsoft.net</a></div>'),K=a('<div class="xdsoft_datepicker active"></div>'),T=a('<div class="xdsoft_mounthpicker"><button type="button" class="xdsoft_prev"></button><button type="button" class="xdsoft_today_button"></button><div class="xdsoft_label xdsoft_month"><span></span><i></i></div><div class="xdsoft_label xdsoft_year"><span></span><i></i></div><button type="button" class="xdsoft_next"></button></div>'),Q=a('<div class="xdsoft_calendar"></div>'),V=a('<div class="xdsoft_timepicker active"><button type="button" class="xdsoft_prev"></button><div class="xdsoft_time_box"></div><button type="button" class="xdsoft_next"></button></div>'),G=V.find(".xdsoft_time_box").eq(0),F=a('<div class="xdsoft_time_variant"></div>'),P=a('<button class="xdsoft_save_selected blue-gradient-button">Save Selected</button>'),E=a('<div class="xdsoft_select xdsoft_monthselect"><div></div></div>'),U=a('<div class="xdsoft_select xdsoft_yearselect"><div></div></div>'),R=false,W,H,D,Y,I,L=0,X=0,N;T.find(".xdsoft_month span").after(E);T.find(".xdsoft_year span").after(U);T.find(".xdsoft_month,.xdsoft_year").on("mousedown.xdsoft",function(ac){var Z=a(this).find(".xdsoft_select").eq(0),af=0,ad=0,ae=Z.is(":visible"),aa,ab;T.find(".xdsoft_select").hide();if(N.currentTime){af=N.currentTime[a(this).hasClass("xdsoft_month")?"getMonth":"getFullYear"]()}Z[ae?"hide":"show"]();for(aa=Z.find("div.xdsoft_option"),ab=0;ab<aa.length;ab+=1){if(aa.eq(ab).data("value")===af){break}else{ad+=aa[0].offsetHeight}}Z.xdsoftScroller(ad/(Z.children()[0].offsetHeight-(Z[0].clientHeight)));ac.stopPropagation();return false});T.find(".xdsoft_select").xdsoftScroller().on("mousedown.xdsoft",function(Z){Z.stopPropagation();Z.preventDefault()}).on("mousedown.xdsoft",".xdsoft_option",function(aa){if(N.currentTime===undefined||N.currentTime===null){N.currentTime=N.now()}var Z=N.currentTime.getFullYear();if(N&&N.currentTime){N.currentTime[a(this).parent().parent().hasClass("xdsoft_monthselect")?"setMonth":"setFullYear"](a(this).data("value"))}a(this).parent().parent().hide();O.trigger("xchange.xdsoft");if(g.onChangeMonth&&a.isFunction(g.onChangeMonth)){g.onChangeMonth.call(O,N.currentTime,O.data("input"))}if(Z!==N.currentTime.getFullYear()&&a.isFunction(g.onChangeYear)){g.onChangeYear.call(O,N.currentTime,O.data("input"))}});O.setOptions=function(Z){g=a.extend(true,{},g,Z);if(Z.allowTimes&&a.isArray(Z.allowTimes)&&Z.allowTimes.length){g.allowTimes=a.extend(true,[],Z.allowTimes)}if(Z.weekends&&a.isArray(Z.weekends)&&Z.weekends.length){g.weekends=a.extend(true,[],Z.weekends)}if(Z.disabledDates&&a.isArray(Z.disabledDates)&&Z.disabledDates.length){g.disabledDates=a.extend(true,[],Z.disabledDates)}if((g.open||g.opened)&&(!g.inline)){M.trigger("open.xdsoft")}if(g.inline){R=true;O.addClass("xdsoft_inline");M.after(O).hide()}if(g.inverseButton){g.next="xdsoft_prev";g.prev="xdsoft_next"}if(g.datepicker){K.addClass("active")}else{K.removeClass("active")}if(g.timepicker){V.addClass("active")}else{V.removeClass("active")}if(g.value){if(M&&M.val){M.val(g.value)}N.setCurrentTime(g.value)}if(isNaN(g.dayOfWeekStart)){g.dayOfWeekStart=0}else{g.dayOfWeekStart=parseInt(g.dayOfWeekStart,10)%7}if(!g.timepickerScrollbar){G.xdsoftScroller("hide")}if(g.minDate&&/^-(.*)$/.test(g.minDate)){g.minDate=N.strToDateTime(g.minDate).dateFormat(g.formatDate)}if(g.maxDate&&/^\+(.*)$/.test(g.maxDate)){g.maxDate=N.strToDateTime(g.maxDate).dateFormat(g.formatDate)}P.toggle(g.showApplyButton);T.find(".xdsoft_today_button").css("visibility",!g.todayButton?"hidden":"visible");T.find("."+g.prev).css("visibility",!g.prevButton?"hidden":"visible");T.find("."+g.next).css("visibility",!g.nextButton?"hidden":"visible");if(g.mask){var ab,ac=function(af){try{if(document.selection&&document.selection.createRange){var ae=document.selection.createRange();return ae.getBookmark().charCodeAt(2)-2}if(af.setSelectionRange){return af.selectionStart}}catch(ag){return 0}},aa=function(af,ag){af=(typeof af==="string"||af instanceof String)?document.getElementById(af):af;if(!af){return false}if(af.createTextRange){var ae=af.createTextRange();ae.collapse(true);ae.moveEnd("character",ag);ae.moveStart("character",ag);ae.select();return true}if(af.setSelectionRange){af.setSelectionRange(ag,ag);return true}return false},ad=function(ae,ag){var af=ae.replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g,"\\$1").replace(/_/g,"{digit+}").replace(/([0-9]{1})/g,"{digit$1}").replace(/\{digit([0-9]{1})\}/g,"[0-$1_]{1}").replace(/\{digit[\+]\}/g,"[0-9_]{1}");return(new RegExp(af)).test(ag)};M.off("keydown.xdsoft");if(g.mask===true){g.mask=g.format.replace(/Y/g,"9999").replace(/F/g,"9999").replace(/m/g,"19").replace(/d/g,"39").replace(/H/g,"29").replace(/i/g,"59").replace(/s/g,"59")}if(a.type(g.mask)==="string"){if(!ad(g.mask,M.val())){M.val(g.mask.replace(/[0-9]/g,"_"))}M.on("keydown.xdsoft",function(af){var ag=this.value,ae=af.which,ai,ah;if(((ae>=t&&ae<=o)||(ae>=i&&ae<=c))||(ae===y||ae===q)){ai=ac(this);ah=(ae!==y&&ae!==q)?String.fromCharCode((i<=ae&&ae<=c)?ae-t:ae):"_";if((ae===y||ae===q)&&ai){ai-=1;ah="_"}while(/[^0-9_]/.test(g.mask.substr(ai,1))&&ai<g.mask.length&&ai>0){ai+=(ae===y||ae===q)?-1:1}ag=ag.substr(0,ai)+ah+ag.substr(ai+1);if(a.trim(ag)===""){ag=g.mask.replace(/[0-9]/g,"_")}else{if(ai===g.mask.length){af.preventDefault();return false}}ai+=(ae===y||ae===q)?0:1;while(/[^0-9_]/.test(g.mask.substr(ai,1))&&ai<g.mask.length&&ai>0){ai+=(ae===y||ae===q)?-1:1}if(ad(g.mask,ag)){this.value=ag;aa(this,ai)}else{if(a.trim(ag)===""){this.value=g.mask.replace(/[0-9]/g,"_")}else{M.trigger("error_input.xdsoft")}}}else{if(([w,d,z,p,k].indexOf(ae)!==-1&&x)||[C,r,B,u,A,v,l,h,m].indexOf(ae)!==-1){return true}}af.preventDefault();return false})}}if(g.validateOnBlur){M.off("blur.xdsoft").on("blur.xdsoft",function(){if(g.allowBlank&&!a.trim(a(this).val()).length){a(this).val(null);O.data("xdsoft_datetime").empty()}else{if(!Date.parseDate(a(this).val(),g.format)){var af=+([a(this).val()[0],a(this).val()[1]].join("")),ae=+([a(this).val()[2],a(this).val()[3]].join(""));if(!g.datepicker&&g.timepicker&&af>=0&&af<24&&ae>=0&&ae<60){a(this).val([af,ae].map(function(ag){return ag>9?ag:"0"+ag}).join(":"))}else{a(this).val((N.now()).dateFormat(g.format))}O.data("xdsoft_datetime").setCurrentTime(a(this).val())}else{O.data("xdsoft_datetime").setCurrentTime(a(this).val())}}O.trigger("changedatetime.xdsoft")})}g.dayOfWeekStartPrev=(g.dayOfWeekStart===0)?6:g.dayOfWeekStart-1;O.trigger("xchange.xdsoft").trigger("afterOpen.xdsoft")};O.data("options",g).on("mousedown.xdsoft",function(Z){Z.stopPropagation();Z.preventDefault();U.hide();E.hide();return false});G.append(F);G.xdsoftScroller();O.on("afterOpen.xdsoft",function(){G.xdsoftScroller()});O.append(K).append(V);if(g.withoutCopyright!==true){O.append(S)}K.append(T).append(Q).append(P);a(g.parentID).append(O);W=function(){var Z=this;Z.now=function(ac){var ad=new Date(),aa,ab;if(!ac&&g.defaultDate){aa=Z.strToDate(g.defaultDate);ad.setFullYear(aa.getFullYear());ad.setMonth(aa.getMonth());ad.setDate(aa.getDate())}if(g.yearOffset){ad.setFullYear(ad.getFullYear()+g.yearOffset)}if(!ac&&g.defaultTime){ab=Z.strtotime(g.defaultTime);ad.setHours(ab.getHours());ad.setMinutes(ab.getMinutes())}return ad};Z.isValidDate=function(aa){if(Object.prototype.toString.call(aa)!=="[object Date]"){return false}return !isNaN(aa.getTime())};Z.setCurrentTime=function(aa){Z.currentTime=(typeof aa==="string")?Z.strToDateTime(aa):Z.isValidDate(aa)?aa:Z.now();O.trigger("xchange.xdsoft")};Z.empty=function(){Z.currentTime=null};Z.getCurrentTime=function(aa){return Z.currentTime};Z.nextMonth=function(){if(Z.currentTime===undefined||Z.currentTime===null){Z.currentTime=Z.now()}var ab=Z.currentTime.getMonth()+1,aa;if(ab===12){Z.currentTime.setFullYear(Z.currentTime.getFullYear()+1);ab=0}aa=Z.currentTime.getFullYear();Z.currentTime.setDate(Math.min(new Date(Z.currentTime.getFullYear(),ab+1,0).getDate(),Z.currentTime.getDate()));Z.currentTime.setMonth(ab);if(g.onChangeMonth&&a.isFunction(g.onChangeMonth)){g.onChangeMonth.call(O,N.currentTime,O.data("input"))}if(aa!==Z.currentTime.getFullYear()&&a.isFunction(g.onChangeYear)){g.onChangeYear.call(O,N.currentTime,O.data("input"))}O.trigger("xchange.xdsoft");return ab};Z.prevMonth=function(){if(Z.currentTime===undefined||Z.currentTime===null){Z.currentTime=Z.now()}var aa=Z.currentTime.getMonth()-1;if(aa===-1){Z.currentTime.setFullYear(Z.currentTime.getFullYear()-1);aa=11}Z.currentTime.setDate(Math.min(new Date(Z.currentTime.getFullYear(),aa+1,0).getDate(),Z.currentTime.getDate()));Z.currentTime.setMonth(aa);if(g.onChangeMonth&&a.isFunction(g.onChangeMonth)){g.onChangeMonth.call(O,N.currentTime,O.data("input"))}O.trigger("xchange.xdsoft");return aa};Z.getWeekOfYear=function(ab){var aa=new Date(ab.getFullYear(),0,1);return Math.ceil((((ab-aa)/86400000)+aa.getDay()+1)/7)};Z.strToDateTime=function(ad){var ab=[],aa,ac;if(ad&&ad instanceof Date&&Z.isValidDate(ad)){return ad}ab=/^(\+|\-)(.*)$/.exec(ad);if(ab){ab[2]=Date.parseDate(ab[2],g.formatDate)}if(ab&&ab[2]){aa=ab[2].getTime()-(ab[2].getTimezoneOffset())*60000;ac=new Date((N.now()).getTime()+parseInt(ab[1]+"1",10)*aa)}else{ac=ad?Date.parseDate(ad,g.format):Z.now()}if(!Z.isValidDate(ac)){ac=Z.now()}return ac};Z.strToDate=function(ab){if(ab&&ab instanceof Date&&Z.isValidDate(ab)){return ab}var aa=ab?Date.parseDate(ab,g.formatDate):Z.now(true);if(!Z.isValidDate(aa)){aa=Z.now(true)}return aa};Z.strtotime=function(aa){if(aa&&aa instanceof Date&&Z.isValidDate(aa)){return aa}var ab=aa?Date.parseDate(aa,g.formatTime):Z.now(true);if(!Z.isValidDate(ab)){ab=Z.now(true)}return ab};Z.str=function(){return Z.currentTime.dateFormat(g.format)};Z.currentTime=this.now()};N=new W();P.on("click",function(Z){Z.preventDefault();O.data("changed",true);N.setCurrentTime(J());M.val(N.str());O.trigger("close.xdsoft")});T.find(".xdsoft_today_button").on("mousedown.xdsoft",function(){O.data("changed",true);N.setCurrentTime(0);O.trigger("afterOpen.xdsoft")}).on("dblclick.xdsoft",function(){M.val(N.str());O.trigger("close.xdsoft")});T.find(".xdsoft_prev,.xdsoft_next").on("mousedown.xdsoft",function(){var aa=a(this),ad=0,Z=false;(function ac(ae){if(aa.hasClass(g.next)){N.nextMonth()}else{if(aa.hasClass(g.prev)){N.prevMonth()}}if(g.monthChangeSpinner){if(!Z){ad=setTimeout(ac,ae||100)}}}(500));a([document.body,window]).on("mouseup.xdsoft",function ab(){clearTimeout(ad);Z=true;a([document.body,window]).off("mouseup.xdsoft",ab)})});V.find(".xdsoft_prev,.xdsoft_next").on("mousedown.xdsoft",function(){var ac=a(this),ae=0,Z=false,ad=110;(function ab(ag){var ai=G[0].clientHeight,af=F[0].offsetHeight,ah=Math.abs(parseInt(F.css("marginTop"),10));if(ac.hasClass(g.next)&&(af-ai)-g.timeHeightInTimePicker>=ah){F.css("marginTop","-"+(ah+g.timeHeightInTimePicker)+"px")}else{if(ac.hasClass(g.prev)&&ah-g.timeHeightInTimePicker>=0){F.css("marginTop","-"+(ah-g.timeHeightInTimePicker)+"px")}}G.trigger("scroll_element.xdsoft_scroller",[Math.abs(parseInt(F.css("marginTop"),10)/(af-ai))]);ad=(ad>10)?10:ad-10;if(!Z){ae=setTimeout(ab,ag||ad)}}(500));a([document.body,window]).on("mouseup.xdsoft",function aa(){clearTimeout(ae);Z=true;a([document.body,window]).off("mouseup.xdsoft",aa)})});H=0;O.on("xchange.xdsoft",function(Z){clearTimeout(H);H=setTimeout(function(){if(N.currentTime===undefined||N.currentTime===null){N.currentTime=N.now()}var ap="",ab=new Date(N.currentTime.getFullYear(),N.currentTime.getMonth(),1,12,0,0),ah=0,ag,al=N.now(),aa=false,af=false,ak,am,ad,an,ae=[],aq,ao=true,ac="",ai="",aj;while(ab.getDay()!==g.dayOfWeekStart){ab.setDate(ab.getDate()-1)}ap+="<table><thead><tr>";if(g.weeks){ap+="<th></th>"}for(ag=0;ag<7;ag+=1){ap+="<th>"+g.i18n[g.lang].dayOfWeek[(ag+g.dayOfWeekStart)%7]+"</th>"}ap+="</tr></thead>";ap+="<tbody>";if(g.maxDate!==false){aa=N.strToDate(g.maxDate);aa=new Date(aa.getFullYear(),aa.getMonth(),aa.getDate(),23,59,59,999)}if(g.minDate!==false){af=N.strToDate(g.minDate);af=new Date(af.getFullYear(),af.getMonth(),af.getDate())}while(ah<N.currentTime.countDaysInMonth()||ab.getDay()!==g.dayOfWeekStart||N.currentTime.getMonth()===ab.getMonth()){ae=[];ah+=1;ak=ab.getDate();am=ab.getFullYear();ad=ab.getMonth();an=N.getWeekOfYear(ab);ae.push("xdsoft_date");if(g.beforeShowDay&&a.isFunction(g.beforeShowDay.call)){aq=g.beforeShowDay.call(O,ab)}else{aq=null}if((aa!==false&&ab>aa)||(af!==false&&ab<af)||(aq&&aq[0]===false)){ae.push("xdsoft_disabled")}else{if(g.disabledDates.indexOf(ab.dateFormat(g.formatDate))!==-1){ae.push("xdsoft_disabled")}}if(aq&&aq[1]!==""){ae.push(aq[1])}if(N.currentTime.getMonth()!==ad){ae.push("xdsoft_other_month")}if((g.defaultSelect||O.data("changed"))&&N.currentTime.dateFormat(g.formatDate)===ab.dateFormat(g.formatDate)){ae.push("xdsoft_current")}if(al.dateFormat(g.formatDate)===ab.dateFormat(g.formatDate)){ae.push("xdsoft_today")}if(ab.getDay()===0||ab.getDay()===6||~g.weekends.indexOf(ab.dateFormat(g.formatDate))){ae.push("xdsoft_weekend")}if(g.beforeShowDay&&a.isFunction(g.beforeShowDay)){ae.push(g.beforeShowDay(ab))}if(ao){ap+="<tr>";ao=false;if(g.weeks){ap+="<th>"+an+"</th>"}}ap+='<td data-date="'+ak+'" data-month="'+ad+'" data-year="'+am+'" class="xdsoft_date xdsoft_day_of_week'+ab.getDay()+" "+ae.join(" ")+'"><div>'+ak+"</div></td>";if(ab.getDay()===g.dayOfWeekStartPrev){ap+="</tr>";ao=true}ab.setDate(ak+1)}ap+="</tbody></table>";Q.html(ap);T.find(".xdsoft_label span").eq(0).text(g.i18n[g.lang].months[N.currentTime.getMonth()]);T.find(".xdsoft_label span").eq(1).text(N.currentTime.getFullYear());ac="";ai="";ad="";aj=function aj(av,ar){var au=N.now();au.setHours(av);av=parseInt(au.getHours(),10);au.setMinutes(ar);ar=parseInt(au.getMinutes(),10);var at=new Date(N.currentTime);at.setHours(av);at.setMinutes(ar);ae=[];if((g.minDateTime!==false&&g.minDateTime>at)||(g.maxTime!==false&&N.strtotime(g.maxTime).getTime()<au.getTime())||(g.minTime!==false&&N.strtotime(g.minTime).getTime()>au.getTime())){ae.push("xdsoft_disabled")}var aw=new Date(N.currentTime);aw.setHours(parseInt(N.currentTime.getHours(),10));aw.setMinutes(Math[g.roundTime](N.currentTime.getMinutes()/g.step)*g.step);if((g.initTime||g.defaultSelect||O.data("changed"))&&aw.getHours()===parseInt(av,10)&&(g.step>59||aw.getMinutes()===parseInt(ar,10))){if(g.defaultSelect||O.data("changed")){ae.push("xdsoft_current")}else{if(g.initTime){ae.push("xdsoft_init_time")}}}if(parseInt(al.getHours(),10)===parseInt(av,10)&&parseInt(al.getMinutes(),10)===parseInt(ar,10)){ae.push("xdsoft_today")}ac+='<div class="xdsoft_time '+ae.join(" ")+'" data-hour="'+av+'" data-minute="'+ar+'">'+au.dateFormat(g.formatTime)+"</div>"};if(!g.allowTimes||!a.isArray(g.allowTimes)||!g.allowTimes.length){for(ah=0,ag=0;ah<(g.hours12?12:24);ah+=1){for(ag=0;ag<60;ag+=g.step){ai=(ah<10?"0":"")+ah;ad=(ag<10?"0":"")+ag;aj(ai,ad)}}}else{for(ah=0;ah<g.allowTimes.length;ah+=1){ai=N.strtotime(g.allowTimes[ah]).getHours();ad=N.strtotime(g.allowTimes[ah]).getMinutes();aj(ai,ad)}}F.html(ac);e="";ah=0;for(ah=parseInt(g.yearStart,10)+g.yearOffset;ah<=parseInt(g.yearEnd,10)+g.yearOffset;ah+=1){e+='<div class="xdsoft_option '+(N.currentTime.getFullYear()===ah?"xdsoft_current":"")+'" data-value="'+ah+'">'+ah+"</div>"}U.children().eq(0).html(e);for(ah=parseInt(g.monthStart),e="";ah<=parseInt(g.monthEnd);ah+=1){e+='<div class="xdsoft_option '+(N.currentTime.getMonth()===ah?"xdsoft_current":"")+'" data-value="'+ah+'">'+g.i18n[g.lang].months[ah]+"</div>"}E.children().eq(0).html(e);a(O).trigger("generate.xdsoft")},10);Z.stopPropagation()}).on("afterOpen.xdsoft",function(){if(g.timepicker){var aa,ac,Z,ab;if(F.find(".xdsoft_current").length){aa=".xdsoft_current"}else{if(F.find(".xdsoft_init_time").length){aa=".xdsoft_init_time"}}if(aa){ac=G[0].clientHeight;Z=F[0].offsetHeight;ab=F.find(aa).index()*g.timeHeightInTimePicker+1;if((Z-ac)<ab){ab=Z-ac}G.trigger("scroll_element.xdsoft_scroller",[parseInt(ab,10)/(Z-ac)])}else{G.trigger("scroll_element.xdsoft_scroller",[0])}}});D=0;Q.on("click.xdsoft","td",function(Z){Z.stopPropagation();D+=1;var ab=a(this),aa=N.currentTime;if(aa===undefined||aa===null){N.currentTime=N.now();aa=N.currentTime}if(ab.hasClass("xdsoft_disabled")){return false}aa.setDate(1);aa.setFullYear(ab.data("year"));aa.setMonth(ab.data("month"));aa.setDate(ab.data("date"));O.trigger("select.xdsoft",[aa]);M.val(N.str());if((D>1||(g.closeOnDateSelect===true||(g.closeOnDateSelect===0&&!g.timepicker)))&&!g.inline){O.trigger("close.xdsoft")}if(g.onSelectDate&&a.isFunction(g.onSelectDate)){g.onSelectDate.call(O,N.currentTime,O.data("input"),Z)}O.data("changed",true);O.trigger("xchange.xdsoft");O.trigger("changedatetime.xdsoft");setTimeout(function(){D=0},200)});F.on("click.xdsoft","div",function(Z){Z.stopPropagation();var ab=a(this),aa=N.currentTime;if(aa===undefined||aa===null){N.currentTime=N.now();aa=N.currentTime}if(ab.hasClass("xdsoft_disabled")){return false}aa.setHours(ab.data("hour"));aa.setMinutes(ab.data("minute"));O.trigger("select.xdsoft",[aa]);O.data("input").val(N.str());if(g.inline!==true&&g.closeOnTimeSelect===true){O.trigger("close.xdsoft")}if(g.onSelectTime&&a.isFunction(g.onSelectTime)){g.onSelectTime.call(O,N.currentTime,O.data("input"),Z)}O.data("changed",true);O.trigger("xchange.xdsoft");O.trigger("changedatetime.xdsoft")});K.on("mousewheel.xdsoft",function(Z){if(!g.scrollMonth){return true}if(Z.deltaY<0){N.nextMonth()}else{N.prevMonth()}return false});M.on("mousewheel.xdsoft",function(Z){if(!g.scrollInput){return true}if(!g.datepicker&&g.timepicker){Y=F.find(".xdsoft_current").length?F.find(".xdsoft_current").eq(0).index():0;if(Y+Z.deltaY>=0&&Y+Z.deltaY<F.children().length){Y+=Z.deltaY}if(F.children().eq(Y).length){F.children().eq(Y).trigger("mousedown")}return false}if(g.datepicker&&!g.timepicker){K.trigger(Z,[Z.deltaY,Z.deltaX,Z.deltaY]);if(M.val){M.val(N.str())}O.trigger("changedatetime.xdsoft");return false}});O.on("changedatetime.xdsoft",function(Z){if(g.onChangeDateTime&&a.isFunction(g.onChangeDateTime)){var aa=O.data("input");g.onChangeDateTime.call(O,N.currentTime,aa,Z);delete g.value;aa.trigger("change")}}).on("generate.xdsoft",function(){if(g.onGenerate&&a.isFunction(g.onGenerate)){g.onGenerate.call(O,N.currentTime,O.data("input"))}if(R){O.trigger("afterOpen.xdsoft");R=false}}).on("click.xdsoft",function(Z){Z.stopPropagation()});Y=0;I=function(){var ac=O.data("input").offset(),ab=ac.top+O.data("input")[0].offsetHeight-1,aa=ac.left,Z="absolute";if(g.fixed){ab-=a(window).scrollTop();aa-=a(window).scrollLeft();Z="fixed"}else{if(ab+O[0].offsetHeight>a(window).height()+a(window).scrollTop()){ab=ac.top-O[0].offsetHeight+1}if(ab<0){ab=0}if(aa+O[0].offsetWidth>a(window).width()){aa=a(window).width()-O[0].offsetWidth}}O.css({left:aa,top:ab,position:Z})};O.on("open.xdsoft",function(aa){var ab=true;if(g.onShow&&a.isFunction(g.onShow)){ab=g.onShow.call(O,N.currentTime,O.data("input"),aa)}if(ab!==false){O.show();I();a(window).off("resize.xdsoft",I).on("resize.xdsoft",I);if(g.closeOnWithoutClick){a([document.body,window]).on("mousedown.xdsoft",function Z(){O.trigger("close.xdsoft");a([document.body,window]).off("mousedown.xdsoft",Z)})}}}).on("close.xdsoft",function(aa){var Z=true;T.find(".xdsoft_month,.xdsoft_year").find(".xdsoft_select").hide();if(g.onClose&&a.isFunction(g.onClose)){Z=g.onClose.call(O,N.currentTime,O.data("input"),aa)}if(Z!==false&&!g.opened&&!g.inline){O.hide()}aa.stopPropagation()}).on("toggle.xdsoft",function(Z){if(O.is(":visible")){O.trigger("close.xdsoft")}else{O.trigger("open.xdsoft")}}).data("input",M);L=0;X=0;O.data("xdsoft_datetime",N);O.setOptions(g);function J(){var Z=false,aa;if(g.startDate){Z=N.strToDate(g.startDate)}else{Z=g.value||((M&&M.val&&M.val())?M.val():"");if(Z){Z=N.strToDateTime(Z)}else{if(g.defaultDate){Z=N.strToDate(g.defaultDate);if(g.defaultTime){aa=N.strtotime(g.defaultTime);Z.setHours(aa.getHours());Z.setMinutes(aa.getMinutes())}}}}if(Z&&N.isValidDate(Z)){O.data("changed",true)}else{Z=""}return Z||0}N.setCurrentTime(J());M.data("xdsoft_datetimepicker",O).on("open.xdsoft focusin.xdsoft mousedown.xdsoft",function(Z){if(M.is(":disabled")||(M.data("xdsoft_datetimepicker").is(":visible")&&g.closeOnInputClick)){return}clearTimeout(L);L=setTimeout(function(){if(M.is(":disabled")){return}R=true;N.setCurrentTime(J());O.trigger("open.xdsoft")},100)}).on("keydown.xdsoft",function(ab){var ac=this.value,aa,Z=ab.which;if([m].indexOf(Z)!==-1&&g.enterLikeTab){aa=a("input:visible,textarea:visible");O.trigger("close.xdsoft");aa.eq(aa.index(this)+1).focus();return false}if([h].indexOf(Z)!==-1){O.trigger("close.xdsoft");return true}})};s=function(D){var E=D.data("xdsoft_datetimepicker");if(E){E.data("xdsoft_datetime",null);E.remove();D.data("xdsoft_datetimepicker",null).off(".xdsoft");a(window).off("resize.xdsoft");a([window,document.body]).off("mousedown.xdsoft");if(D.unmousewheel){D.unmousewheel()}}};a(document).off("keydown.xdsoftctrl keyup.xdsoftctrl").on("keydown.xdsoftctrl",function(D){if(D.keyCode===l){x=true}}).on("keyup.xdsoftctrl",function(D){if(D.keyCode===l){x=false}});return this.each(function(){var D=a(this).data("xdsoft_datetimepicker");if(D){if(a.type(e)==="string"){switch(e){case"show":a(this).select().focus();D.trigger("open.xdsoft");break;case"hide":D.trigger("close.xdsoft");break;case"toggle":D.trigger("toggle.xdsoft");break;case"destroy":s(a(this));break;case"reset":this.value=this.defaultValue;if(!this.value||!D.data("xdsoft_datetime").isValidDate(Date.parseDate(this.value,g.format))){D.data("changed",false)}D.data("xdsoft_datetime").setCurrentTime(this.value);break;case"validate":var E=D.data("input");E.trigger("blur.xdsoft");break}}else{D.setOptions(e)}return 0}if(a.type(e)!=="string"){if(!g.lazyInit||g.open||g.inline){f(a(this))}else{j(a(this))}}})};a.fn.datetimepicker.defaults=b}(jQuery));(function(){ /* Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh) * Licensed under the MIT License (LICENSE.txt). * * Version: 3.1.12 * * Requires: jQuery 1.2.2+ */ !function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail" in g&&(m=-1*g.detail),"wheelDelta" in g&&(m=g.wheelDelta),"wheelDeltaY" in g&&(m=g.wheelDeltaY),"wheelDeltaX" in g&&(l=-1*g.wheelDeltaX),"axis" in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY" in g&&(m=-1*g.deltaY,j=m),"deltaX" in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else{if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel" in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks){for(var j=g.length;j;){a.event.fixHooks[g[--j]]=a.event.mouseHooks}}var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener){for(var c=h.length;c;){this.addEventListener(h[--c],b,!1)}}else{this.onmousewheel=b}a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener){for(var c=h.length;c;){this.removeEventListener(h[--c],b,!1)}}else{this.onmousewheel=null}a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent" in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})});Date.parseFunctions={count:0};Date.parseRegexes=[];Date.formatFunctions={count:0};Date.prototype.dateFormat=function(b){if(b=="unixtime"){return parseInt(this.getTime()/1000)}if(Date.formatFunctions[b]==null){Date.createNewFormat(b)}var a=Date.formatFunctions[b];return this[a]()};Date.createNewFormat=function(format){var funcName="format"+Date.formatFunctions.count++;Date.formatFunctions[format]=funcName;var codePrefix="Date.prototype."+funcName+" = function() {return ";var code="";var special=false;var ch="";for(var i=0;i<format.length;++i){ch=format.charAt(i);if(!special&&ch=="\\"){special=true}else{if(special){special=false;code+="'"+String.escape(ch)+"' + "}else{code+=Date.getFormatCode(ch)}}}if(code.length==0){code='""'}else{code=code.substring(0,code.length-3)}eval(codePrefix+code+";}")};Date.getFormatCode=function(a){switch(a){case"d":return"String.leftPad(this.getDate(), 2, '0') + ";case"D":return"Date.dayNames[this.getDay()].substring(0, 3) + ";case"j":return"this.getDate() + ";case"l":return"Date.dayNames[this.getDay()] + ";case"S":return"this.getSuffix() + ";case"w":return"this.getDay() + ";case"z":return"this.getDayOfYear() + ";case"W":return"this.getWeekOfYear() + ";case"F":return"Date.monthNames[this.getMonth()] + ";case"m":return"String.leftPad(this.getMonth() + 1, 2, '0') + ";case"M":return"Date.monthNames[this.getMonth()].substring(0, 3) + ";case"n":return"(this.getMonth() + 1) + ";case"t":return"this.getDaysInMonth() + ";case"L":return"(this.isLeapYear() ? 1 : 0) + ";case"Y":return"this.getFullYear() + ";case"y":return"('' + this.getFullYear()).substring(2, 4) + ";case"a":return"(this.getHours() < 12 ? 'am' : 'pm') + ";case"A":return"(this.getHours() < 12 ? 'AM' : 'PM') + ";case"g":return"((this.getHours() %12) ? this.getHours() % 12 : 12) + ";case"G":return"this.getHours() + ";case"h":return"String.leftPad((this.getHours() %12) ? this.getHours() % 12 : 12, 2, '0') + ";case"H":return"String.leftPad(this.getHours(), 2, '0') + ";case"i":return"String.leftPad(this.getMinutes(), 2, '0') + ";case"s":return"String.leftPad(this.getSeconds(), 2, '0') + ";case"O":return"this.getGMTOffset() + ";case"T":return"this.getTimezone() + ";case"Z":return"(this.getTimezoneOffset() * -60) + ";default:return"'"+String.escape(a)+"' + "}};Date.parseDate=function(a,c){if(c=="unixtime"){return new Date(!isNaN(parseInt(a))?parseInt(a)*1000:0)}if(Date.parseFunctions[c]==null){Date.createParser(c)}var b=Date.parseFunctions[c];return Date[b](a)};Date.createParser=function(format){var funcName="parse"+Date.parseFunctions.count++;var regexNum=Date.parseRegexes.length;var currentGroup=1;Date.parseFunctions[format]=funcName;var code="Date."+funcName+" = function(input) {\nvar y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, z = -1;\nvar d = new Date();\ny = d.getFullYear();\nm = d.getMonth();\nd = d.getDate();\nvar results = input.match(Date.parseRegexes["+regexNum+"]);\nif (results && results.length > 0) {";var regex="";var special=false;var ch="";for(var i=0;i<format.length;++i){ch=format.charAt(i);if(!special&&ch=="\\"){special=true}else{if(special){special=false;regex+=String.escape(ch)}else{obj=Date.formatCodeToRegex(ch,currentGroup);currentGroup+=obj.g;regex+=obj.s;if(obj.g&&obj.c){code+=obj.c}}}}code+="if (y > 0 && z > 0){\nvar doyDate = new Date(y,0);\ndoyDate.setDate(z);\nm = doyDate.getMonth();\nd = doyDate.getDate();\n}";code+="if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n{return new Date(y, m, d, h, i, s);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n{return new Date(y, m, d, h, i);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0)\n{return new Date(y, m, d, h);}\nelse if (y > 0 && m >= 0 && d > 0)\n{return new Date(y, m, d);}\nelse if (y > 0 && m >= 0)\n{return new Date(y, m);}\nelse if (y > 0)\n{return new Date(y);}\n}return null;}";Date.parseRegexes[regexNum]=new RegExp("^"+regex+"$");eval(code)};Date.formatCodeToRegex=function(b,a){switch(b){case"D":return{g:0,c:null,s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};case"j":case"d":return{g:1,c:"d = parseInt(results["+a+"], 10);\n",s:"(\\d{1,2})"};case"l":return{g:0,c:null,s:"(?:"+Date.dayNames.join("|")+")"};case"S":return{g:0,c:null,s:"(?:st|nd|rd|th)"};case"w":return{g:0,c:null,s:"\\d"};case"z":return{g:1,c:"z = parseInt(results["+a+"], 10);\n",s:"(\\d{1,3})"};case"W":return{g:0,c:null,s:"(?:\\d{2})"};case"F":return{g:1,c:"m = parseInt(Date.monthNumbers[results["+a+"].substring(0, 3)], 10);\n",s:"("+Date.monthNames.join("|")+")"};case"M":return{g:1,c:"m = parseInt(Date.monthNumbers[results["+a+"]], 10);\n",s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};case"n":case"m":return{g:1,c:"m = parseInt(results["+a+"], 10) - 1;\n",s:"(\\d{1,2})"};case"t":return{g:0,c:null,s:"\\d{1,2}"};case"L":return{g:0,c:null,s:"(?:1|0)"};case"Y":return{g:1,c:"y = parseInt(results["+a+"], 10);\n",s:"(\\d{4})"};case"y":return{g:1,c:"var ty = parseInt(results["+a+"], 10);\ny = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",s:"(\\d{1,2})"};case"a":return{g:1,c:"if (results["+a+"] == 'am') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}",s:"(am|pm)"};case"A":return{g:1,c:"if (results["+a+"] == 'AM') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}",s:"(AM|PM)"};case"g":case"G":case"h":case"H":return{g:1,c:"h = parseInt(results["+a+"], 10);\n",s:"(\\d{1,2})"};case"i":return{g:1,c:"i = parseInt(results["+a+"], 10);\n",s:"(\\d{2})"};case"s":return{g:1,c:"s = parseInt(results["+a+"], 10);\n",s:"(\\d{2})"};case"O":return{g:0,c:null,s:"[+-]\\d{4}"};case"T":return{g:0,c:null,s:"[A-Z]{3}"};case"Z":return{g:0,c:null,s:"[+-]\\d{1,5}"};default:return{g:0,c:null,s:String.escape(b)}}};Date.prototype.getTimezone=function(){return this.toString().replace(/^.*? ([A-Z]{3}) [0-9]{4}.*$/,"$1").replace(/^.*?\(([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+\)$/,"$1$2$3")};Date.prototype.getGMTOffset=function(){return(this.getTimezoneOffset()>0?"-":"+")+String.leftPad(Math.floor(Math.abs(this.getTimezoneOffset())/60),2,"0")+String.leftPad(Math.abs(this.getTimezoneOffset())%60,2,"0")};Date.prototype.getDayOfYear=function(){var a=0;Date.daysInMonth[1]=this.isLeapYear()?29:28;for(var b=0;b<this.getMonth();++b){a+=Date.daysInMonth[b]}return a+this.getDate()};Date.prototype.getWeekOfYear=function(){var b=this.getDayOfYear()+(4-this.getDay());var a=new Date(this.getFullYear(),0,1);var c=(7-a.getDay()+4);return String.leftPad(Math.ceil((b-c)/7)+1,2,"0")};Date.prototype.isLeapYear=function(){var a=this.getFullYear();return((a&3)==0&&(a%100||(a%400==0&&a)))};Date.prototype.getFirstDayOfMonth=function(){var a=(this.getDay()-(this.getDate()-1))%7;return(a<0)?(a+7):a};Date.prototype.getLastDayOfMonth=function(){var a=(this.getDay()+(Date.daysInMonth[this.getMonth()]-this.getDate()))%7;return(a<0)?(a+7):a};Date.prototype.getDaysInMonth=function(){Date.daysInMonth[1]=this.isLeapYear()?29:28;return Date.daysInMonth[this.getMonth()]};Date.prototype.getSuffix=function(){switch(this.getDate()){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th"}};String.escape=function(a){return a.replace(/('|\\)/g,"\\$1")};String.leftPad=function(d,b,c){var a=new String(d);if(c==null){c=" "}while(a.length<b){a=c+a}return a};Date.daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31];Date.monthNames=["January","February","March","April","May","June","July","August","September","October","November","December"];Date.dayNames=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];Date.y2kYear=50;Date.monthNumbers={Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11};Date.patterns={ISO8601LongPattern:"Y-m-d H:i:s",ISO8601ShortPattern:"Y-m-d",ShortDatePattern:"n/j/Y",LongDatePattern:"l, F d, Y",FullDateTimePattern:"l, F d, Y g:i:s A",MonthDayPattern:"F d",ShortTimePattern:"g:i A",LongTimePattern:"g:i:s A",SortableDateTimePattern:"Y-m-d\\TH:i:s",UniversalSortableDateTimePattern:"Y-m-d H:i:sO",YearMonthPattern:"F, Y"}}());
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-datetimepicker.min.js
jquery-datetimepicker.min.js
!function(a,e){"use strict";function n(e,n){return a(e).each(function(){var e=a(this);if(!e.data("ams-dndupload-initialiazed")){n=a.extend(!0,{},a.dndupload.defaults,n);var t=e.get(0);"FORM"!==t.tagName&&(e.removeClass("dndupload").html('<form action="{action}" method="POST" enctype="multipart/form-data" class="dndupload"></form>'.replace(/{action}/,n.action)),e=a("form",e));var s='<div class="box__input">\n\t<svg class="box__icon" xmlns="http://www.w3.org/2000/svg" width="50" height="43" viewBox="0 0 50 43">\n\t\t<path d="M48.4 26.5c-.9 0-1.7.7-1.7 1.7v11.6h-43.3v-11.6c0-.9-.7-1.7-1.7-1.7s-1.7.7-1.7 1.7v13.2c0 .9.7 1.7 1.7 1.7h46.7c.9 0 1.7-.7 1.7-1.7v-13.2c0-1-.7-1.7-1.7-1.7zm-24.5 6.1c.3.3.8.5 1.2.5.4 0 .9-.2 1.2-.5l10-11.6c.7-.7.7-1.7 0-2.4s-1.7-.7-2.4 0l-7.1 8.3v-25.3c0-.9-.7-1.7-1.7-1.7s-1.7.7-1.7 1.7v25.3l-7.1-8.3c-.7-.7-1.7-.7-2.4 0s-.7 1.7 0 2.4l10 11.6z" />\n\t</svg>\n'+'\t<input type="file" name="{label}" id="file" class="box__file" multiple="multiple"\n'.replace(/{label}/,n.fieldname)+'\t\t data-multiple-caption="{label}" />\n'.replace(/{label}/,l.plugins.i18n.dndupload.FILES_SELECTED)+'\t<label for="file">\n'+"\t\t<strong>{label}</strong> {add}<br />\n".replace(/{label}/,l.plugins.i18n.dndupload.CHOOSE_FILE).replace(/{add}/,l.plugins.i18n.dndupload.ADD_INFO)+'\t\t<span class="box__dragndrop">{label}</span></label>\n'.replace(/{label}/,l.plugins.i18n.dndupload.DRAG_FILE)+'\t<button type="submit" class="box__button">{label}</button>\n'.replace(/{label}/,l.plugins.i18n.dndupload.UPLOAD)+"</div>\n"+'<div class="box__uploading">{label}</div>\n'.replace(/{label}/,l.plugins.i18n.dndupload.UPLOADING)+'<div class="box__success">{label}\n'.replace(/{label}/,l.plugins.i18n.dndupload.DONE)+'\t<a href=".?" class="box__restart" role="button">{label}</a>\n'.replace(/{label}/,l.plugins.i18n.dndupload.UPLOAD_MORE)+"</div>\n"+'<div class="box__error">{label}<span></span>. \n'.replace(/{label}/,l.plugins.i18n.dndupload.ERROR)+'\t<a href=".?" class="box__restart" role="button">{label}</a>\n'.replace(/{label}/,l.plugins.i18n.dndupload.TRY_AGAIN)+"</div>";e.html(s);var i=e,o=i.find('input[type="file"]'),r=i.find("label"),u=i.find(".box__error span"),c=i.find(".box__restart"),p=!1,f=function(a){r.text(a.length>1?(o.attr("data-multiple-caption")||"").replace(/{count}/,a.length):a[0].name)};o.on("change",function(a){f(a.target.files),n.autosubmit&&i.trigger("submit")}),d&&i.addClass("has-advanced-upload").on("drag dragstart dragend dragover dragenter dragleave drop",function(a){a.preventDefault(),a.stopPropagation()}).on("dragover dragenter",function(){i.addClass("is-dragover")}).on("dragleave dragend drop",function(){i.removeClass("is-dragover")}).on("drop",function(a){p=a.originalEvent.dataTransfer.files,f(p),n.autosubmit&&i.trigger("submit")}),i.on("submit",function(e){if(i.hasClass("is-uploading"))return!1;if(i.addClass("is-uploading").removeClass("is-error"),d){e.preventDefault();var n=new FormData(i.get(0));p&&a.each(p,function(a,e){n.append(o.attr("name"),e)}),a.ajax({url:i.attr("action"),type:i.attr("method"),data:n,dataType:"json",cache:!1,contentType:!1,processData:!1,success:function(a){"string"==typeof a&&(a=JSON.parse(a)),l.ajax.handleJSON(a)},complete:function(){i.removeClass("is-uploading")}})}else{var t="uploadiframe_"+(new Date).getTime(),s=a("<iframe>").attr("name",t).attr("style","display: none").appendTo(a("body"));i.attr("target",t),s.one("load",function(){var a=JSON.parse(s.contents().find("body").text());i.removeClass("is-uploading").addClass(!0===a.success?"is-success":"is-error").removeAttr("target"),a.success||u.text(a.error),s.remove()})}}),c.on("click",function(a){a.preventDefault(),i.removeClass("is-error is-success"),o.trigger("click")}),o.on("focus",function(){o.addClass("has-focus")}).on("blur",function(){o.removeClass("has-focus")}),a(t).removeClass("hidden"),e.data("ams-dndupload-initialized",!0)}}),e}function t(a){}a.dndupload={defaults:{action:"upload-files",fieldname:"files",autosubmit:!0}};var l=MyAMS,d=function(){var a=document.createElement("div");return("draggable"in a||"ondragstart"in a&&"ondrop"in a)&&"FormData"in window&&"FileReader"in window}();a.extend(a.fn,{dndupload:function(e,l){var d=a(this);switch(e){case"settings":return void 0===l?d.data("dndupload-settings"):(d.each(function(){var e=d.data("dndupload-settings")||{};t(a(this)),d.dndupload(a.extend(!0,e,l))}),d);case"destroy":return d.each(function(){t(a(this))}),d;default:return"create"!==e&&(l=e),d.each(function(){n(a(this),l)}),d}}})}(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dndupload.min.js
jquery-dndupload.min.js
(function(f,d,a){function e(k){var j=[];for(var h=0,g=k.length;h<g;h++){j[k[h]]=h}return j}function c(h,j,i){var g=h.splice(j,1)[0];h.splice(i,0,g)}function b(k,n,m){var j=[];for(var h=0,g=k.childNodes.length;h<g;h++){if(k.childNodes[h].nodeType==1){j.push(k.childNodes[h])}}var l=j[n];if(m!==null){k.insertBefore(l,j[m])}else{k.appendChild(l)}}f.fn.dataTableExt.oApi.fnColReorder=function(k,g,r){var o,l,n,u,v=k.aoColumns.length,t,m;if(g==r){return}if(g<0||g>=v){this.oApi._fnLog(k,1,"ColReorder 'from' index is out of bounds: "+g);return}if(r<0||r>=v){this.oApi._fnLog(k,1,"ColReorder 'to' index is out of bounds: "+r);return}var q=[];for(o=0,l=v;o<l;o++){q[o]=o}c(q,g,r);var s=e(q);for(o=0,l=k.aaSorting.length;o<l;o++){k.aaSorting[o][0]=s[k.aaSorting[o][0]]}if(k.aaSortingFixed!==null){for(o=0,l=k.aaSortingFixed.length;o<l;o++){k.aaSortingFixed[o][0]=s[k.aaSortingFixed[o][0]]}}for(o=0,l=v;o<l;o++){m=k.aoColumns[o];for(n=0,u=m.aDataSort.length;n<u;n++){m.aDataSort[n]=s[m.aDataSort[n]]}}for(o=0,l=v;o<l;o++){m=k.aoColumns[o];if(typeof m.mData=="number"){m.mData=s[m.mData];m.fnGetData=k.oApi._fnGetObjectDataFn(m.mData);m.fnSetData=k.oApi._fnSetObjectDataFn(m.mData)}}if(k.aoColumns[g].bVisible){var h=this.oApi._fnColumnIndexToVisible(k,g);var p=null;o=r<g?r:r+1;while(p===null&&o<v){p=this.oApi._fnColumnIndexToVisible(k,o);o++}t=k.nTHead.getElementsByTagName("tr");for(o=0,l=t.length;o<l;o++){b(t[o],h,p)}if(k.nTFoot!==null){t=k.nTFoot.getElementsByTagName("tr");for(o=0,l=t.length;o<l;o++){b(t[o],h,p)}}for(o=0,l=k.aoData.length;o<l;o++){if(k.aoData[o].nTr!==null){b(k.aoData[o].nTr,h,p)}}}c(k.aoColumns,g,r);c(k.aoPreSearchCols,g,r);for(o=0,l=k.aoData.length;o<l;o++){if(f.isArray(k.aoData[o]._aData)){c(k.aoData[o]._aData,g,r)}c(k.aoData[o]._anHidden,g,r)}for(o=0,l=k.aoHeader.length;o<l;o++){c(k.aoHeader[o],g,r)}if(k.aoFooter!==null){for(o=0,l=k.aoFooter.length;o<l;o++){c(k.aoFooter[o],g,r)}}for(o=0,l=v;o<l;o++){k.aoColumns[o].aDataSort=[o];k.aoColumns[o]._ColReorder_iOrigCol=o;f(k.aoColumns[o].nTh).unbind("click");this.oApi._fnSortAttachListener(k,k.aoColumns[o].nTh,o)}if(typeof ColVis!="undefined"){ColVis.fnRebuild(k.oInstance)}f(k.oInstance).trigger("column-reorder",[k,{iFrom:g,iTo:r,aiInvertMapping:s}]);if(typeof k.oInstance._oPluginFixedHeader!="undefined"){k.oInstance._oPluginFixedHeader.fnUpdate()}};ColReorder=function(h,g){if(!this.CLASS||this.CLASS!="ColReorder"){alert("Warning: ColReorder must be initialised with the keyword 'new'")}if(typeof g=="undefined"){g={}}this.s={dt:null,init:g,allowReorder:true,allowResize:true,fixed:0,dropCallback:null,mouse:{startX:-1,startY:-1,offsetX:-1,offsetY:-1,target:-1,targetIndex:-1,fromIndex:-1},aoTargets:[]};this.dom={drag:null,resize:null,pointer:null};this.table_size=-1;this.s.dt=h.oInstance.fnSettings();this._fnConstruct();h.oApi._fnCallbackReg(h,"aoDestroyCallback",jQuery.proxy(this._fnDestroy,this),"ColReorder");ColReorder.aoInstances.push(this);return this};ColReorder.prototype={fnReset:function(){var h=[];for(var j=0,g=this.s.dt.aoColumns.length;j<g;j++){h.push(this.s.dt.aoColumns[j]._ColReorder_iOrigCol)}this._fnOrderColumns(h)},_fnConstruct:function(){var m=this;var l,g;if(typeof this.s.init.allowReorder!="undefined"){this.s.allowReorder=this.s.init.allowReorder}if(typeof this.s.init.allowResize!="undefined"){this.s.allowResize=this.s.init.allowResize}if(typeof this.s.init.iFixedColumns!="undefined"){this.s.fixed=this.s.init.iFixedColumns}if(typeof this.s.init.fnReorderCallback!="undefined"){this.s.dropCallback=this.s.init.fnReorderCallback}for(l=0,g=this.s.dt.aoColumns.length;l<g;l++){if(l>this.s.fixed-1){this._fnMouseListener(l,this.s.dt.aoColumns[l].nTh)}this.s.dt.aoColumns[l]._ColReorder_iOrigCol=l}this.s.dt.oApi._fnCallbackReg(this.s.dt,"aoStateSaveParams",function(i,n){m._fnStateSave.call(m,n)},"ColReorder_State");var h=null;if(typeof this.s.init.aiOrder!="undefined"){h=this.s.init.aiOrder.slice()}if(this.s.dt.oLoadedState&&typeof this.s.dt.oLoadedState.ColReorder!="undefined"&&this.s.dt.oLoadedState.ColReorder.length==this.s.dt.aoColumns.length){h=this.s.dt.oLoadedState.ColReorder}if(h){if(!m.s.dt._bInitComplete){var k=false;this.s.dt.aoDrawCallback.push({fn:function(){if(!m.s.dt._bInitComplete&&!k){k=true;var i=e(h);m._fnOrderColumns.call(m,i)}},sName:"ColReorder_Pre"})}else{var j=e(h);m._fnOrderColumns.call(m,j)}}},_fnOrderColumns:function(h){if(h.length!=this.s.dt.aoColumns.length){this.s.dt.oInstance.oApi._fnLog(oDTSettings,1,"ColReorder - array reorder does not match known number of columns. Skipping.");return}for(var j=0,g=h.length;j<g;j++){var k=f.inArray(j,h);if(j!=k){c(h,k,j);this.s.dt.oInstance.fnColReorder(k,j)}}if(this.s.dt.oScroll.sX!==""||this.s.dt.oScroll.sY!==""){this.s.dt.oInstance.fnAdjustColumnSizing()}this.s.dt.oInstance.oApi._fnSaveState(this.s.dt)},_fnStateSave:function(h){var j,g,k,l;var m=this.s.dt;for(j=0;j<h.aaSorting.length;j++){h.aaSorting[j][0]=m.aoColumns[h.aaSorting[j][0]]._ColReorder_iOrigCol}aSearchCopy=f.extend(true,[],h.aoSearchCols);h.ColReorder=[];for(j=0,g=m.aoColumns.length;j<g;j++){l=m.aoColumns[j]._ColReorder_iOrigCol;h.aoSearchCols[l]=aSearchCopy[j];h.abVisCols[l]=m.aoColumns[j].bVisible;h.ColReorder.push(l)}},_fnMouseListener:function(g,j){var h=this;f(j).unbind("mousemove.ColReorder");f(j).unbind("mousedown.ColReorder");if(this.s.allowResize){f(j).bind("mousemove.ColReorder",function(l){if(h.dom.drag===null&&h.dom.resize===null){var i=l.target.nodeName=="TH"?l.target:f(l.target).parents("TH")[0];var m=f(i).offset();var k=f(i).innerWidth();if(Math.abs(l.pageX-Math.round(m.left+k))<=5){f(i).css({cursor:"col-resize"})}else{f(i).css({cursor:"pointer"})}}})}f(j).bind("mousedown.ColReorder",function(i){h._fnMouseDown.call(h,i,j,g);return false})},_fnMouseDown:function(o,g,m){var n=this,q=this.s.dt.aoColumns;if(f(g).css("cursor")=="col-resize"){this.s.mouse.startX=o.pageX;this.s.mouse.startWidth=f(g).width();this.s.mouse.resizeElem=f(g);var h=f(g).next();this.s.mouse.nextStartWidth=f(h).width();n.dom.resize=true;this.s.dt.aoColumns[m].bSortable=false;this.s.dt.oFeatures.bAutoWidth=false}else{if(this.s.allowReorder){n.dom.resize=null;var p=o.target.nodeName=="TH"?o.target:f(o.target).parents("TH")[0];var l=f(p).offset();this.s.mouse.startX=o.pageX;this.s.mouse.startY=o.pageY;this.s.mouse.offsetX=o.pageX-l.left;this.s.mouse.offsetY=o.pageY-l.top;this.s.mouse.target=g;this.s.mouse.targetIndex=f("th",g.parentNode).index(g);this.s.mouse.fromIndex=this.s.dt.oInstance.oApi._fnVisibleToColumnIndex(this.s.dt,this.s.mouse.targetIndex);this.s.aoTargets.splice(0,this.s.aoTargets.length);this.s.aoTargets.push({x:f(this.s.dt.nTable).offset().left,to:0});var k=0;for(var m=0,j=q.length;m<j;m++){if(m!=this.s.mouse.fromIndex){k++}if(q[m].bVisible){this.s.aoTargets.push({x:f(q[m].nTh).offset().left+f(q[m].nTh).outerWidth(),to:k})}}if(this.s.fixed!==0){this.s.aoTargets.splice(0,this.s.fixed)}}}f(a).bind("mousemove.ColReorder",function(i){n._fnMouseMove.call(n,i,m)});f(a).bind("mouseup.ColReorder",function(i){setTimeout(function(){n._fnMouseUp.call(n,i,m)},10)})},_fnMouseMove:function(r,p){var q=this;var l;l=this.s.dt.oInit.sScrollX===""?false:true;if(this.table_size<0&&l&&f("div.dataTables_scrollHead",this.s.dt.nTableWrapper)!=undefined){if(f("div.dataTables_scrollHead",this.s.dt.nTableWrapper).length>0){this.table_size=f(f("div.dataTables_scrollHead",this.s.dt.nTableWrapper)[0].childNodes[0].childNodes[0]).width()}}if(this.dom.resize){var h=this.s.mouse.resizeElem;var j=f(h).next();var s=r.pageX-this.s.mouse.startX;if(s!=0&&!l){f(j).width(this.s.mouse.nextStartWidth-s)}f(h).width(this.s.mouse.startWidth+s);if(l&&f("div.dataTables_scrollHead",this.s.dt.nTableWrapper)!=undefined){if(f("div.dataTables_scrollHead",this.s.dt.nTableWrapper).length>0){f(f("div.dataTables_scrollHead",this.s.dt.nTableWrapper)[0].childNodes[0].childNodes[0]).width(this.table_size+s)}}var n;if(f("div.dataTables_scrollBody")!=null){if(f("div.dataTables_scrollBody").length>0){var g;n=-1;for(g=-1;g<this.s.dt.aoColumns.length-1&&g!=p;g++){if(this.s.dt.aoColumns[g+1].bVisible){n++}}tableScroller=f("div.dataTables_scrollBody",this.s.dt.nTableWrapper)[0];scrollingTableHead=f(tableScroller)[0].childNodes[0].childNodes[0].childNodes[0];if(s!=0&&!l){f(f(scrollingTableHead)[0].childNodes[n+1]).width(this.s.mouse.nextStartWidth-s)}f(f(scrollingTableHead)[0].childNodes[n]).width(this.s.mouse.startWidth+s);if(l){f(f(tableScroller)[0].childNodes[0]).width(this.table_size+s)}}}return}else{if(this.s.allowReorder){if(this.dom.drag===null){if(Math.pow(Math.pow(r.pageX-this.s.mouse.startX,2)+Math.pow(r.pageY-this.s.mouse.startY,2),0.5)<5){return}this._fnCreateDragNode()}this.dom.drag.style.left=(r.pageX-this.s.mouse.offsetX)+"px";this.dom.drag.style.top=(r.pageY-this.s.mouse.offsetY)+"px";var m=false;for(var o=1,k=this.s.aoTargets.length;o<k;o++){if(r.pageX<this.s.aoTargets[o-1].x+((this.s.aoTargets[o].x-this.s.aoTargets[o-1].x)/2)){this.dom.pointer.style.left=this.s.aoTargets[o-1].x+"px";this.s.mouse.toIndex=this.s.aoTargets[o-1].to;m=true;break}}if(!m){this.dom.pointer.style.left=this.s.aoTargets[this.s.aoTargets.length-1].x+"px";this.s.mouse.toIndex=this.s.aoTargets[this.s.aoTargets.length-1].to}}}},_fnMouseUp:function(o,k){var n=this;f(a).unbind("mousemove.ColReorder");f(a).unbind("mouseup.ColReorder");if(this.dom.drag!==null){a.body.removeChild(this.dom.drag);a.body.removeChild(this.dom.pointer);this.dom.drag=null;this.dom.pointer=null;this.s.dt.oInstance.fnColReorder(this.s.mouse.fromIndex,this.s.mouse.toIndex);if(this.s.dt.oScroll.sX!==""||this.s.dt.oScroll.sY!==""){this.s.dt.oInstance.fnAdjustColumnSizing()}if(this.s.dropCallback!==null){this.s.dropCallback.call(this)}this._fnConstruct();this.s.dt.oInstance.oApi._fnSaveState(this.s.dt)}else{if(this.dom.resize!==null){var l;var h;var p;var m;var q;var g;this.s.dt.aoColumns[k].bSortable=true;this.s.dt.aoColumns[k].sWidth=f(this.s.mouse.resizeElem).innerWidth()+"px";g=this.s.dt.oInit.sScrollX===""?false:true;if(!g){for(m=k+1;m<this.s.dt.aoColumns.length;m++){if(this.s.dt.aoColumns[m].bVisible){break}}for(q=k-1;q>=0;q--){if(this.s.dt.aoColumns[q].bVisible){break}}if(this.s.dt.aoColumns.length>m){this.s.dt.aoColumns[m].sWidth=f(this.s.mouse.resizeElem).next().innerWidth()+"px"}else{p=this.s.mouse.resizeElem;for(l=q;l>0;l--){if(this.s.dt.aoColumns[l].bVisible){p=f(p).prev();this.s.dt.aoColumns[l].sWidth=f(p).innerWidth()+"px"}}}}if(g&&f("div.dataTables_scrollHead",this.s.dt.nTableWrapper)!=undefined){if(f("div.dataTables_scrollHead",this.s.dt.nTableWrapper).length>0){this.table_size=f(f("div.dataTables_scrollHead",this.s.dt.nTableWrapper)[0].childNodes[0].childNodes[0]).width()}}this.s.dt.oInstance.oApi._fnSaveState(this.s.dt)}}this.dom.resize=null},_fnCreateDragNode:function(){var g=this;this.dom.drag=f(this.s.dt.nTHead.parentNode).clone(true)[0];this.dom.drag.className+=" DTCR_clonedTable";while(this.dom.drag.getElementsByTagName("caption").length>0){this.dom.drag.removeChild(this.dom.drag.getElementsByTagName("caption")[0])}while(this.dom.drag.getElementsByTagName("tbody").length>0){this.dom.drag.removeChild(this.dom.drag.getElementsByTagName("tbody")[0])}while(this.dom.drag.getElementsByTagName("tfoot").length>0){this.dom.drag.removeChild(this.dom.drag.getElementsByTagName("tfoot")[0])}f("thead tr:eq(0)",this.dom.drag).each(function(){f("th:not(:eq("+g.s.mouse.targetIndex+"))",this).remove()});f("tr",this.dom.drag).height(f("tr:eq(0)",g.s.dt.nTHead).height());f("thead tr:gt(0)",this.dom.drag).remove();f("thead th:eq(0)",this.dom.drag).each(function(h){this.style.width=f("th:eq("+g.s.mouse.targetIndex+")",g.s.dt.nTHead).width()+"px"});this.dom.drag.style.position="absolute";this.dom.drag.style.zIndex=1200;this.dom.drag.style.top="0px";this.dom.drag.style.left="0px";this.dom.drag.style.width=f("th:eq("+g.s.mouse.targetIndex+")",g.s.dt.nTHead).outerWidth()+"px";this.dom.pointer=a.createElement("div");this.dom.pointer.className="DTCR_pointer";this.dom.pointer.style.position="absolute";if(this.s.dt.oScroll.sX===""&&this.s.dt.oScroll.sY===""){this.dom.pointer.style.top=f(this.s.dt.nTable).offset().top+"px";this.dom.pointer.style.height=f(this.s.dt.nTable).height()+"px"}else{this.dom.pointer.style.top=f("div.dataTables_scroll",this.s.dt.nTableWrapper).offset().top+"px";this.dom.pointer.style.height=f("div.dataTables_scroll",this.s.dt.nTableWrapper).height()+"px"}a.body.appendChild(this.dom.pointer);a.body.appendChild(this.dom.drag)},_fnDestroy:function(){for(var h=0,g=ColReorder.aoInstances.length;h<g;h++){if(ColReorder.aoInstances[h]===this){ColReorder.aoInstances.splice(h,1);break}}f(this.s.dt.nTHead).find("*").unbind(".ColReorder");this.s.dt.oInstance._oPluginColReorder=null;this.s=null}};ColReorder.aoInstances=[];ColReorder.fnReset=function(h){for(var j=0,g=ColReorder.aoInstances.length;j<g;j++){if(ColReorder.aoInstances[j].s.dt.oInstance==h){ColReorder.aoInstances[j].fnReset()}}};ColReorder.prototype.CLASS="ColReorder";ColReorder.VERSION="1.0.7";ColReorder.prototype.VERSION=ColReorder.VERSION;if(typeof f.fn.dataTable=="function"&&typeof f.fn.dataTableExt.fnVersionCheck=="function"&&f.fn.dataTableExt.fnVersionCheck("1.9.3")){f.fn.dataTableExt.aoFeatures.push({fnInit:function(i){var g=i.oInstance;if(typeof g._oPluginColReorder=="undefined"){var h=typeof i.oInit.oColReorder!="undefined"?i.oInit.oColReorder:{};g._oPluginColReorder=new ColReorder(i,h)}else{g.oApi._fnLog(i,1,"ColReorder attempted to initialise twice. Ignoring second")}return null},cFeature:"R",sFeature:"ColReorder"})}else{alert("Warning: ColReorder requires DataTables 1.9.3 or greater - www.datatables.net/download")}})(jQuery,window,document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-colReorderWithResize.min.js
jquery-dataTables-colReorderWithResize.min.js
!function(f){function e(n,m){return this instanceof e?(f.isPlainObject(n)?m=n:(m=m||{},m.alias=n),this.el=void 0,this.opts=f.extend(!0,{},this.defaults,m),this.noMasksCache=m&&void 0!==m.definitions,this.userOptions=m||{},this.events={},void h(this.opts.alias,m,this.opts)):new e(n,m)}function k(m){var p=document.createElement("input"),o="on"+m,n=o in p;return n||(p.setAttribute(o,"return;"),n="function"==typeof p[o]),p=null,n}function i(n,q){var m=n.getAttribute("type"),o="INPUT"===n.tagName&&-1!==f.inArray(m,q.supportsInputType)||n.isContentEditable||"TEXTAREA"===n.tagName;if(!o&&"INPUT"===n.tagName){var p=document.createElement("input");p.setAttribute("type",m),o="text"===p.type,p=null}return o}function h(n,o,p){var m=p.aliases[n];return m?(m.alias&&h(m.alias,void 0,p),f.extend(!0,p,m),f.extend(!0,p,o),!0):(null===p.mask&&(p.mask=n),!1)}function l(v,m,t){function q(p,w){w=void 0!==w?w:v.getAttribute("data-inputmask-"+p),null!==w&&("string"==typeof w&&(0===p.indexOf("on")?w=window[w]:"false"===w?w=!1:"true"===w&&(w=!0)),t[p]=w)}var s,o,r,n,u=v.getAttribute("data-inputmask");if(u&&""!==u&&(u=u.replace(new RegExp("'","g"),'"'),o=JSON.parse("{"+u+"}")),o){r=void 0;for(n in o){if("alias"===n.toLowerCase()){r=o[n];break}}}q("alias",r),t.alias&&h(t.alias,t,m);for(s in m){if(o){r=void 0;for(n in o){if(n.toLowerCase()===s.toLowerCase()){r=o[n];break}}}q(s,r)}return f.extend(!0,m,t),m}function d(s,p){function r(M){function A(V,T,U,S){this.matches=[],this.isGroup=V||!1,this.isOptional=T||!1,this.isQuantifier=U||!1,this.isAlternator=S||!1,this.quantifier={min:1,max:1}}function t(aa,V,X){var T=s.definitions[V];X=void 0!==X?X:aa.matches.length;var U=aa.matches[X-1];if(T&&!B){T.placeholder=f.isFunction(T.placeholder)?T.placeholder(s):T.placeholder;for(var Z=T.prevalidator,ac=Z?Z.length:0,W=1;W<T.cardinality;W++){var ab=ac>=W?Z[W-1]:[],S=ab.validator,Y=ab.cardinality;aa.matches.splice(X++,0,{fn:S?"string"==typeof S?new RegExp(S):new function(){this.test=S}():new RegExp("."),cardinality:Y?Y:1,optionality:aa.isOptional,newBlockMarker:void 0===U||U.def!==(T.definitionSymbol||V),casing:T.casing,def:T.definitionSymbol||V,placeholder:T.placeholder,mask:V}),U=aa.matches[X-1]}aa.matches.splice(X++,0,{fn:T.validator?"string"==typeof T.validator?new RegExp(T.validator):new function(){this.test=T.validator}():new RegExp("."),cardinality:T.cardinality,optionality:aa.isOptional,newBlockMarker:void 0===U||U.def!==(T.definitionSymbol||V),casing:T.casing,def:T.definitionSymbol||V,placeholder:T.placeholder,mask:V})}else{aa.matches.splice(X++,0,{fn:null,cardinality:0,optionality:aa.isOptional,newBlockMarker:void 0===U||U.def!==V,casing:null,def:s.staticDefinitionSymbol||V,placeholder:void 0!==s.staticDefinitionSymbol?V:void 0,mask:V}),B=!1}}function C(T,S){T.isGroup&&(T.isGroup=!1,t(T,s.groupmarker.start,0),S!==!0&&t(T,s.groupmarker.end))}function R(S,U,V,T){U.matches.length>0&&(void 0===T||T)&&(V=U.matches[U.matches.length-1],C(V)),t(U,S)}function E(){if(Q.length>0){if(N=Q[Q.length-1],R(I,N,O,!N.isAlternator),N.isAlternator){P=Q.pop();for(var S=0;S<P.matches.length;S++){P.matches[S].isGroup=!1}Q.length>0?(N=Q[Q.length-1],N.matches.push(P)):v.matches.push(P)}}else{R(I,v,O)}}function y(U){function V(X){return X===s.optionalmarker.start?X=s.optionalmarker.end:X===s.optionalmarker.end?X=s.optionalmarker.start:X===s.groupmarker.start?X=s.groupmarker.end:X===s.groupmarker.end&&(X=s.groupmarker.start),X}U.matches=U.matches.reverse();for(var T in U.matches){var S=parseInt(T);if(U.matches[T].isQuantifier&&U.matches[S+1]&&U.matches[S+1].isGroup){var W=U.matches[T];U.matches.splice(T,1),U.matches.splice(S+1,0,W)}void 0!==U.matches[T].matches?U.matches[T]=y(U.matches[T]):U.matches[T]=V(U.matches[T])}return U}for(var D,I,z,N,P,O,w,G=/(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g,B=!1,v=new A(),Q=[],x=[];D=G.exec(M);){if(I=D[0],B){E()}else{switch(I.charAt(0)){case s.escapeChar:B=!0;break;case s.optionalmarker.end:case s.groupmarker.end:if(z=Q.pop(),void 0!==z){if(Q.length>0){if(N=Q[Q.length-1],N.matches.push(z),N.isAlternator){P=Q.pop();for(var F=0;F<P.matches.length;F++){P.matches[F].isGroup=!1}Q.length>0?(N=Q[Q.length-1],N.matches.push(P)):v.matches.push(P)}}else{v.matches.push(z)}}else{E()}break;case s.optionalmarker.start:Q.push(new A(!1,!0));break;case s.groupmarker.start:Q.push(new A(!0));break;case s.quantifiermarker.start:var H=new A(!1,!1,!0);I=I.replace(/[{}]/g,"");var J=I.split(","),L=isNaN(J[0])?J[0]:parseInt(J[0]),K=1===J.length?L:isNaN(J[1])?J[1]:parseInt(J[1]);if(("*"===K||"+"===K)&&(L="*"===K?0:1),H.quantifier={min:L,max:K},Q.length>0){var u=Q[Q.length-1].matches;D=u.pop(),D.isGroup||(w=new A(!0),w.matches.push(D),D=w),u.push(D),u.push(H)}else{D=v.matches.pop(),D.isGroup||(w=new A(!0),w.matches.push(D),D=w),v.matches.push(D),v.matches.push(H)}break;case s.alternatormarker:Q.length>0?(N=Q[Q.length-1],O=N.matches.pop()):O=v.matches.pop(),O.isAlternator?Q.push(O):(P=new A(!1,!1,!1,!0),P.matches.push(O),Q.push(P));break;default:E()}}}for(;Q.length>0;){z=Q.pop(),C(z,!0),v.matches.push(z)}return v.matches.length>0&&(O=v.matches[v.matches.length-1],C(O),x.push(v)),s.numericInput&&y(x[0]),x}function q(t,u){if(null===t||""===t){return void 0}if(1===t.length&&s.greedy===!1&&0!==s.repeat&&(s.placeholder=""),s.repeat>0||"*"===s.repeat||"+"===s.repeat){var v="*"===s.repeat?0:"+"===s.repeat?1:s.repeat;t=s.groupmarker.start+t+s.groupmarker.end+s.quantifiermarker.start+v+","+s.repeat+s.quantifiermarker.end}var w;return void 0===e.prototype.masksCache[t]||p===!0?(w={mask:t,maskToken:r(t),validPositions:{},_buffer:void 0,buffer:void 0,tests:{},metadata:u},p!==!0&&(e.prototype.masksCache[s.numericInput?t.split("").reverse().join(""):t]=w,w=f.extend(!0,{},e.prototype.masksCache[s.numericInput?t.split("").reverse().join(""):t]))):w=f.extend(!0,{},e.prototype.masksCache[s.numericInput?t.split("").reverse().join(""):t]),w}function n(t){return t=t.toString()}var m;if(f.isFunction(s.mask)&&(s.mask=s.mask(s)),f.isArray(s.mask)){if(s.mask.length>1){s.keepStatic=null===s.keepStatic?!0:s.keepStatic;var o="(";return f.each(s.numericInput?s.mask.reverse():s.mask,function(t,u){o.length>1&&(o+=")|("),o+=n(void 0===u.mask||f.isFunction(u.mask)?u:u.mask)}),o+=")",q(o,s.mask)}s.mask=s.mask.pop()}return s.mask&&(m=void 0===s.mask.mask||f.isFunction(s.mask.mask)?q(n(s.mask),s.mask):q(n(s.mask.mask),s.mask)),m}function g(w,F,T){function aw(aM,aL,aE){aL=aL||0;var aG,aJ,aH,aF=[],aK=0,aI=r();do{if(aM===!0&&K().validPositions[aK]){var aD=K().validPositions[aK];aJ=aD.match,aG=aD.locator.slice(),aF.push(aE===!0?aD.input:aA(aK,aJ))}else{aH=E(aK,aG,aK-1),aJ=aH.match,aG=aH.locator.slice(),(T.jitMasking===!1||aI>aK||isFinite(T.jitMasking)&&T.jitMasking>aK)&&aF.push(aA(aK,aJ))}aK++}while((void 0===y||y>aK-1)&&null!==aJ.fn||null===aJ.fn&&""!==aJ.def||aL>=aK);return""===aF[aF.length-1]&&aF.pop(),aF}function K(){return F}function N(aD){var aE=K();aE.buffer=void 0,aD!==!0&&(aE.tests={},aE._buffer=void 0,aE.validPositions={},aE.p=0)}function r(aE,aF){var aI=-1,aJ=-1,aG=K().validPositions;void 0===aE&&(aE=-1);for(var aD in aG){var aH=parseInt(aD);aG[aH]&&(aF||null!==aG[aH].match.fn)&&(aE>=aH&&(aI=aH),aH>=aE&&(aJ=aH))}return -1!==aI&&aE-aI>1||aE>aJ?aI:aJ}function B(aM,aN,aH,aJ){if(aJ||T.insertMode&&void 0!==K().validPositions[aM]&&void 0===aH){var aG,aO=f.extend(!0,{},K().validPositions),aI=r();for(aG=aM;aI>=aG;aG++){delete K().validPositions[aG]}K().validPositions[aM]=aN;var aF,aD=!0,aL=K().validPositions;for(aG=aF=aM;aI>=aG;aG++){var aP=aO[aG];if(void 0!==aP){for(var aK=aF,aE=-1;aK<ak()&&(null==aP.match.fn&&aL[aG]&&(aL[aG].match.optionalQuantifier===!0||aL[aG].match.optionality===!0)||null!=aP.match.fn);){if(null===aP.match.fn||!T.keepStatic&&aL[aG]&&(void 0!==aL[aG+1]&&C(aG+1,aL[aG].locator.slice(),aG).length>1||void 0!==aL[aG].alternation)?aK++:aK=p(aF),ar(aK,aP.match.def)){var aQ=u(aK,aP.input,!0,!0);if(aD=aQ!==!1,aF=aQ.caret||aQ.insert?r():aK,aD){break}}else{if(aD=null==aP.match.fn,aE===aK){break}aE=aK}}}if(!aD){break}}if(!aD){return K().validPositions=f.extend(!0,{},aO),N(!0),!1}}else{K().validPositions[aM]=aN}return N(!0),!0}function aa(aD,aE,aH,aI){function aJ(aP){var aN=K().validPositions[aP];if(void 0!==aN&&null===aN.match.fn){var aO=K().validPositions[aP-1],aM=K().validPositions[aP+1];return void 0!==aO&&void 0!==aM}return !1}var aF,aG=aD;for(K().p=aD,aF=aE-1;aF>=aG;aF--){void 0!==K().validPositions[aF]&&(aH===!0||!aJ(aF)&&T.canClearPosition(K(),aF,r(),aI,T)!==!1)&&delete K().validPositions[aF]}for(N(!0),aF=aG+1;aF<=r();){for(;void 0!==K().validPositions[aG];){aG++}var aL=K().validPositions[aG];if(aG>aF&&(aF=aG+1),void 0===K().validPositions[aF]&&M(aF)||void 0!==aL){aF++}else{var aK=E(aF);ar(aG,aK.match.def)?u(aG,aK.input||aA(aF),!0)!==!1&&(delete K().validPositions[aF],aF++):M(aF)||(aF++,aG--),aG++}}N(!0)}function E(aJ,aG,aF){var aH=K().validPositions[aJ];if(void 0===aH){for(var aE=C(aJ,aG,aF),aI=r(),aK=K().validPositions[aI]||C(0)[0],aD=void 0!==aK.alternation?aK.locator[aK.alternation].toString().split(","):[],aL=0;aL<aE.length&&(aH=aE[aL],!(aH.match&&(T.greedy&&aH.match.optionalQuantifier!==!0||(aH.match.optionality===!1||aH.match.newBlockMarker===!1)&&aH.match.optionalQuantifier!==!0)&&(void 0===aK.alternation||aK.alternation!==aH.alternation||void 0!==aH.locator[aK.alternation]&&o(aH.locator[aK.alternation].toString().split(","),aD))));aL++){}}return aH}function ag(aD){return K().validPositions[aD]?K().validPositions[aD].match:C(aD)[0].match}function ar(aH,aG){for(var aF=!1,aD=C(aH),aE=0;aE<aD.length;aE++){if(aD[aE].match&&aD[aE].match.def===aG){aF=!0;break}}return aF}function U(aG,aE){var aD,aF;return(K().tests[aG]||K().validPositions[aG])&&f.each(K().tests[aG]||[K().validPositions[aG]],function(aH,aI){var aJ=aI.alternation?aI.locator[aI.alternation].toString().indexOf(aE):-1;(void 0===aF||aF>aJ)&&-1!==aJ&&(aD=aI,aF=aJ)}),aD}function C(aO,aH,aG){function aD(aY,aV,aX,aT){function aZ(bc,bn,bm){function bj(br,bs){var bq=0===f.inArray(br,bs.matches);return bq||f.each(bs.matches,function(bt,bu){return bu.isQuantifier===!0&&(bq=bj(br,bs.matches[bt-1]))?!1:void 0}),bq}function a8(bs,br){var bq=U(bs,br);return bq?bq.locator.slice(bq.alternation+1):[]}if(aK>10000){throw"Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. "+K().mask}if(aK===aO&&void 0===bc.matches){return aJ.push({match:bc,locator:bn.reverse(),cd:aQ}),!0}if(void 0!==bc.matches){if(bc.isGroup&&bm!==bc){if(bc=aZ(aY.matches[f.inArray(bc,aY.matches)+1],bn)){return !0}}else{if(bc.isOptional){var bf=bc;if(bc=aD(bc,aV,bn,bm)){if(aR=aJ[aJ.length-1].match,!bj(aR,bf)){return !0}aP=!0,aK=aO}}else{if(bc.isAlternator){var a2,a3=bc,a0=[],a4=aJ.slice(),a6=bn.length,a7=aV.length>0?aV.shift():-1;if(-1===a7||"string"==typeof a7){var be,bo=aK,bd=aV.slice(),bl=[];if("string"==typeof a7){bl=a7.split(",")}else{for(be=0;be<a3.matches.length;be++){bl.push(be)}}for(var a9=0;a9<bl.length;a9++){if(be=parseInt(bl[a9]),aJ=[],aV=a8(aK,be),bc=aZ(a3.matches[be]||aY.matches[be],[be].concat(bn),bm)||bc,bc!==!0&&void 0!==bc&&bl[bl.length-1]<a3.matches.length){var bh=f.inArray(bc,aY.matches)+1;aY.matches.length>bh&&(bc=aZ(aY.matches[bh],[bh].concat(bn.slice(1,bn.length)),bm),bc&&(bl.push(bh.toString()),f.each(aJ,function(bq,br){br.alternation=bn.length-1})))}a2=aJ.slice(),aK=bo,aJ=[];for(var bk=0;bk<bd.length;bk++){aV[bk]=bd[bk]}for(var bi=0;bi<a2.length;bi++){var bb=a2[bi];bb.alternation=bb.alternation||a6;for(var bg=0;bg<a0.length;bg++){var a1=a0[bg];if(bb.match.def===a1.match.def&&("string"!=typeof a7||-1!==f.inArray(bb.locator[bb.alternation].toString(),bl))){bb.match.mask===a1.match.mask&&(a2.splice(bi,1),bi--),-1===a1.locator[bb.alternation].toString().indexOf(bb.locator[bb.alternation])&&(a1.locator[bb.alternation]=a1.locator[bb.alternation]+","+bb.locator[bb.alternation],a1.alternation=bb.alternation);break}}}a0=a0.concat(a2)}"string"==typeof a7&&(a0=f.map(a0,function(bs,bq){if(isFinite(bq)){var bv,br=bs.alternation,bt=bs.locator[br].toString().split(",");bs.locator[br]=void 0,bs.alternation=void 0;for(var bu=0;bu<bt.length;bu++){bv=-1!==f.inArray(bt[bu],bl),bv&&(void 0!==bs.locator[br]?(bs.locator[br]+=",",bs.locator[br]+=bt[bu]):bs.locator[br]=parseInt(bt[bu]),bs.alternation=br)}if(void 0!==bs.locator[br]){return bs}}})),aJ=a4.concat(a0),aK=aO,aP=aJ.length>0}else{bc=aZ(a3.matches[a7]||aY.matches[a7],[a7].concat(bn),bm)}if(bc){return !0}}else{if(bc.isQuantifier&&bm!==aY.matches[f.inArray(bc,aY.matches)-1]){for(var bp=bc,a5=aV.length>0?aV.shift():0;a5<(isNaN(bp.quantifier.max)?a5+1:bp.quantifier.max)&&aO>=aK;a5++){var ba=aY.matches[f.inArray(bp,aY.matches)-1];if(bc=aZ(ba,[a5].concat(bn),ba)){if(aR=aJ[aJ.length-1].match,aR.optionalQuantifier=a5>bp.quantifier.min-1,bj(aR,ba)){if(a5>bp.quantifier.min-1){aP=!0,aK=aO;break}return !0}return !0}}}else{if(bc=aD(bc,aV,bn,bm)){return !0}}}}}}else{aK++}}for(var aW=aV.length>0?aV.shift():0;aW<aY.matches.length;aW++){if(aY.matches[aW].isQuantifier!==!0){var aU=aZ(aY.matches[aW],[aW].concat(aX),aT);if(aU&&aK===aO){return aU}if(aK>aO){break}}}}function aL(aT){var aU=aT[0]||aT;return aU.locator.slice()}var aR,aE=K().maskToken,aK=aH?aG:0,aS=aH||[0],aJ=[],aP=!1,aQ=aH?aH.join(""):"";if(aO>-1){if(void 0===aH){for(var aN,aM=aO-1;void 0===(aN=K().validPositions[aM]||K().tests[aM])&&aM>-1;){aM--}void 0!==aN&&aM>-1&&(aS=aL(aN),aQ=aS.join(""),aN=aN[0]||aN,aK=aM)}if(K().tests[aO]&&K().tests[aO][0].cd===aQ){return K().tests[aO]}for(var aF=aS.shift();aF<aE.length;aF++){var aI=aD(aE[aF],aS,[aF]);if(aI&&aK===aO||aK>aO){break}}}return(0===aJ.length||aP)&&aJ.push({match:{fn:null,cardinality:0,optionality:!0,casing:null,def:""},locator:[]}),K().tests[aO]=f.extend(!0,[],aJ),K().tests[aO]}function aC(){return void 0===K()._buffer&&(K()._buffer=aw(!1,1)),K()._buffer}function n(aD){if(void 0===K().buffer||aD===!0){if(aD===!0){for(var aE in K().tests){void 0===K().validPositions[aE]&&delete K().tests[aE]}}K().buffer=aw(!0,r(),!0)}return K().buffer}function ab(aG,aE,aD){var aF;if(aD=aD,aG===!0){N(),aG=0,aE=aD.length}else{for(aF=aG;aE>aF;aF++){delete K().validPositions[aF],delete K().tests[aF]}}for(aF=aG;aE>aF;aF++){N(!0),aD[aF]!==T.skipOptionalPartCharacter&&u(aF,aD[aF],!0,!0)}}function Z(aD,aE){switch(aE.casing){case"upper":aD=aD.toUpperCase();break;case"lower":aD=aD.toLowerCase()}return aD}function o(aF,aE){for(var aH=T.greedy?aE:aE.slice(0,1),aD=!1,aG=0;aG<aF.length;aG++){if(-1!==f.inArray(aF[aG],aH)){aD=!0;break}}return aD}function u(aO,aN,aR,aJ){function aK(aU){return ao?aU.begin-aU.end>1||aU.begin-aU.end===1&&T.insertMode:aU.end-aU.begin>1||aU.end-aU.begin===1&&T.insertMode}function aG(aV,aY,aX,aU){var aW=!1;return f.each(C(aV),function(a8,a1){for(var a6=a1.match,a2=aY?1:0,a0="",a4=a6.cardinality;a4>a2;a4--){a0+=S(aV-(a4-1))}if(aY&&(a0+=aY),n(!0),aW=null!=a6.fn?a6.fn.test(a0,K(),aV,aX,T):aY!==a6.def&&aY!==T.skipOptionalPartCharacter||""===a6.def?!1:{c:a6.placeholder||a6.def,pos:aV},aW!==!1){var a3=void 0!==aW.c?aW.c:aY;a3=a3===T.skipOptionalPartCharacter&&null===a6.fn?a6.placeholder||a6.def:a3;var aZ=aV,a7=n();if(void 0!==aW.remove&&(f.isArray(aW.remove)||(aW.remove=[aW.remove]),f.each(aW.remove.sort(function(ba,a9){return a9-ba}),function(a9,ba){aa(ba,ba+1,!0)})),void 0!==aW.insert&&(f.isArray(aW.insert)||(aW.insert=[aW.insert]),f.each(aW.insert.sort(function(ba,a9){return ba-a9}),function(a9,ba){u(ba.pos,ba.c,!1,aU)})),aW.refreshFromBuffer){var a5=aW.refreshFromBuffer;if(aX=!0,ab(a5===!0?a5:a5.start,a5.end,a7),void 0===aW.pos&&void 0===aW.c){return aW.pos=r(),!1}if(aZ=void 0!==aW.pos?aW.pos:aV,aZ!==aV){return aW=f.extend(aW,u(aZ,a3,!0,aU)),!1}}else{if(aW!==!0&&void 0!==aW.pos&&aW.pos!==aV&&(aZ=aW.pos,ab(aV,aZ,n().slice()),aZ!==aV)){return aW=f.extend(aW,u(aZ,a3,!0)),!1}}return aW!==!0&&void 0===aW.pos&&void 0===aW.c?!1:(a8>0&&N(!0),B(aZ,f.extend({},a1,{input:Z(a3,a6)}),aU,aK(aO))||(aW=!1),!1)}}),aW}function aI(a0,bf,bj,bd){for(var a3,bh,aZ,a1,be,aW,aV=f.extend(!0,{},K().validPositions),aX=f.extend(!0,{},K().tests),a2=r();a2>=0&&(a1=K().validPositions[a2],!a1||void 0===a1.alternation||(a3=a2,bh=K().validPositions[a3].alternation,E(a3).locator[a1.alternation]===a1.locator[a1.alternation]));a2--){}if(void 0!==bh){a3=parseInt(a3);for(var a7 in K().validPositions){if(a7=parseInt(a7),a1=K().validPositions[a7],a7>=a3&&void 0!==a1.alternation){var bg;0===a3?(bg=[],f.each(K().tests[a3],function(bk,bl){void 0!==bl.locator[bh]&&(bg=bg.concat(bl.locator[bh].toString().split(",")))})):bg=K().validPositions[a3].locator[bh].toString().split(",");var a9=void 0!==a1.locator[bh]?a1.locator[bh]:bg[0];a9.length>0&&(a9=a9.split(",")[0]);for(var a6=0;a6<bg.length;a6++){var bc=[],bb=0,ba=0;if(a9<bg[a6]){for(var aY,bi,a8=a7;a8>=0;a8--){if(aY=K().validPositions[a8],void 0!==aY){var aU=U(a8,bg[a6]);K().validPositions[a8].match.def!==aU.match.def&&(bc.push(K().validPositions[a8].input),K().validPositions[a8]=aU,K().validPositions[a8].input=aA(a8),null===K().validPositions[a8].match.fn&&ba++,aY=aU),bi=aY.locator[bh],aY.locator[bh]=parseInt(bg[a6]);break}}if(a9!==aY.locator[bh]){for(be=a7+1;be<r(void 0,!0)+1;be++){aW=K().validPositions[be],aW&&null!=aW.match.fn?bc.push(aW.input):a0>be&&bb++,delete K().validPositions[be],delete K().tests[be]}for(N(!0),T.keepStatic=!T.keepStatic,aZ=!0;bc.length>0;){var a5=bc.shift();if(a5!==T.skipOptionalPartCharacter&&!(aZ=u(r(void 0,!0)+1,a5,!1,bd))){break}}if(aY.alternation=bh,aY.locator[bh]=bi,aZ){var a4=r(a0)+1;for(be=a7+1;be<r()+1;be++){aW=K().validPositions[be],(void 0===aW||null==aW.match.fn)&&a0>be&&ba++}a0+=ba-bb,aZ=u(a0>a4?a4:a0,bf,bj,bd)}if(T.keepStatic=!T.keepStatic,aZ){return aZ}N(),K().validPositions=f.extend(!0,{},aV),K().tests=f.extend(!0,{},aX)}}}break}}}return !1}function aL(aY,a0){for(var aV=K().validPositions[a0],aZ=aV.locator,a2=aZ.length,aU=aY;a0>aU;aU++){if(void 0===K().validPositions[aU]&&!M(aU,!0)){var aW=C(aU),aX=aW[0],a1=-1;f.each(aW,function(a4,a3){for(var a5=0;a2>a5&&(void 0!==a3.locator[a5]&&o(a3.locator[a5].toString().split(","),aZ[a5].toString().split(",")));a5++){a5>a1&&(a1=a5,aX=a3)}}),B(aU,f.extend({},aX,{input:aX.match.placeholder||aX.match.def}),!0)}}}aR=aR===!0;var aQ=aO;void 0!==aO.begin&&(aQ=ao&&!aK(aO)?aO.end:aO.begin);for(var aT=!1,aP=f.extend(!0,{},K().validPositions),aM=aQ-1;aM>-1&&!K().validPositions[aM];aM--){}aM++;for(var aH;aQ>aM;aM++){n(),void 0===K().validPositions[aM]&&((aH=E(aM)).match.def===T.radixPointDefinitionSymbol||!M(aM,!0)||f.inArray(T.radixPoint,n())<aM&&aH.match.fn&&aH.match.fn.test(aA(aM),K(),aM,!1,T))&&aG(aM,aH.match.placeholder||(null==aH.match.fn?aH.match.def:aA(aM)),!0,aJ)}if(aK(aO)&&(V(void 0,e.keyCode.DELETE,aO),aQ=K().p),aQ<ak()&&(aT=aG(aQ,aN,aR,aJ),(!aR||aJ===!0)&&aT===!1)){var aD=K().validPositions[aQ];if(!aD||null!==aD.match.fn||aD.match.def!==aN&&aN!==T.skipOptionalPartCharacter){if((T.insertMode||void 0===K().validPositions[p(aQ)])&&!M(aQ,!0)){var aS=E(aQ).match;aS=aS.placeholder||aS.def,aG(aQ,aS,aR,aJ);for(var aF=aQ+1,aE=p(aQ);aE>=aF;aF++){if(aT=aG(aF,aN,aR,aJ),aT!==!1){aL(aQ,aF),aQ=aF;break}}}}else{aT={caret:p(aQ)}}}return aT===!1&&T.keepStatic&&(aT=aI(aQ,aN,aR,aJ)),aT===!0&&(aT={pos:aQ}),f.isFunction(T.postValidation)&&aT!==!1&&!aR&&aJ!==!0&&(aT=T.postValidation(n(!0),aT,T)?aT:!1),void 0===aT.pos&&(aT.pos=aQ),aT===!1&&(N(!0),K().validPositions=f.extend(!0,{},aP)),aT}function M(aG,aD){var aF;if(aD?(aF=E(aG).match,""===aF.def&&(aF=ag(aG))):aF=ag(aG),null!=aF.fn){return aF.fn}if(aD!==!0&&aG>-1&&!T.keepStatic&&void 0===K().validPositions[aG]){var aE=C(aG);return aE.length>2}return !1}function ak(){var aI;y=void 0!==ax?ax.maxLength:void 0,-1===y&&(y=void 0);var aH,aG=r(),aD=K().validPositions[aG],aF=void 0!==aD?aD.locator.slice():void 0;for(aH=aG+1;void 0===aD||null!==aD.match.fn||null===aD.match.fn&&""!==aD.match.def;aH++){aD=E(aH,aF,aH-1),aF=aD.locator.slice()}var aE=ag(aH-1);return aI=""!==aE.def?aH:aH-1,void 0===y||y>aI?aI:y}function p(aG,aF){var aE=ak();if(aG>=aE){return aE}for(var aD=aG;++aD<aE&&(aF===!0&&(ag(aD).newBlockMarker!==!0||!M(aD))||aF!==!0&&!M(aD)&&(T.nojumps!==!0||T.nojumpsThreshold>aD));){}return aD}function au(aF,aE){var aD=aF;if(0>=aD){return 0}for(;--aD>0&&(aE===!0&&ag(aD).newBlockMarker!==!0||aE!==!0&&!M(aD));){}return aD}function S(aD){return void 0===K().validPositions[aD]?aA(aD):K().validPositions[aD].input}function ac(aF,aE,aG,aJ,aI){if(aJ&&f.isFunction(T.onBeforeWrite)){var aD=T.onBeforeWrite(aJ,aE,aG,T);if(aD){if(aD.refreshFromBuffer){var aH=aD.refreshFromBuffer;ab(aH===!0?aH:aH.start,aH.end,aD.buffer||aE),aE=n(!0)}void 0!==aG&&(aG=void 0!==aD.caret?aD.caret:aG)}}aF.inputmask._valueSet(aE.join("")),void 0===aG||void 0!==aJ&&"blur"===aJ.type||I(aF,aG),aI===!0&&(s=!0,f(aF).trigger("input"))}function aA(aI,aH){if(aH=aH||ag(aI),void 0!==aH.placeholder){return aH.placeholder}if(null===aH.fn){if(aI>-1&&!T.keepStatic&&void 0===K().validPositions[aI]){var aF,aE=C(aI),aG=0;if(aE.length>2){for(var aD=0;aD<aE.length;aD++){if(aE[aD].match.optionality!==!0&&aE[aD].match.optionalQuantifier!==!0&&(null===aE[aD].match.fn||void 0===aF||aE[aD].match.fn.test(aF.match.def,K(),aI,!0,T)!==!1)&&(aG++,null===aE[aD].match.fn&&(aF=aE[aD]),aG>1)){return T.placeholder.charAt(aI%T.placeholder.length)}}}}return aH.def}return T.placeholder.charAt(aI%T.placeholder.length)}function z(aK,aJ,aL,aI){function aM(){var aP=!1,aQ=aC().slice(aE,p(aE)).join("").indexOf(aG);if(-1!==aQ&&!M(aE)){aP=!0;for(var aO=aC().slice(aE,aE+aQ),aN=0;aN<aO.length;aN++){if(" "!==aO[aN]){aP=!1;break}}}return aP}var aD=aI.slice(),aG="",aE=0;if(N(),K().p=p(-1),!aL){if(T.autoUnmask!==!0){var aH=aC().slice(0,p(-1)).join(""),aF=aD.join("").match(new RegExp("^"+e.escapeRegex(aH),"g"));aF&&aF.length>0&&(aD.splice(0,aF.length*aH.length),aE=p(aE))}else{aE=p(aE)}}f.each(aD,function(aP,aN){if(void 0!==aN){var aO=new f.Event("keypress");aO.which=aN.charCodeAt(0),aG+=aN;var aT=r(void 0,!0),aR=K().validPositions[aT],aQ=E(aT+1,aR?aR.locator.slice():void 0,aT);if(!aM()||aL||T.autoUnmask){var aS=aL?aP:null==aQ.match.fn&&aQ.match.optionality&&aT+1<K().p?aT+1:K().p;J.call(aK,aO,!0,!1,aL,aS),aE=aS+1,aG=""}else{J.call(aK,aO,!0,!1,!0,aT+1)}}}),aJ&&ac(aK,n(),document.activeElement===aK?p(r(0)):void 0,new f.Event("checkval"))}function m(aD){if(aD&&void 0===aD.inputmask){return aD.value}var aG=[],aI=K().validPositions;for(var aH in aI){aI[aH].match&&null!=aI[aH].match.fn&&aG.push(aI[aH].input)}var aE=0===aG.length?null:(ao?aG.reverse():aG).join("");if(null!==aE){var aF=(ao?n().slice().reverse():n()).join("");f.isFunction(T.onUnMask)&&(aE=T.onUnMask(aF,aE,T)||aE)}return aE}function I(aL,aF,aH,aD){function aI(aN){if(aD!==!0&&ao&&"number"==typeof aN&&(!T.greedy||""!==T.placeholder)){var aM=n().join("").length;aN=aM-aN}return aN}var aK;if("number"!=typeof aF){return aL.setSelectionRange?(aF=aL.selectionStart,aH=aL.selectionEnd):window.getSelection?(aK=window.getSelection().getRangeAt(0),(aK.commonAncestorContainer.parentNode===aL||aK.commonAncestorContainer===aL)&&(aF=aK.startOffset,aH=aK.endOffset)):document.selection&&document.selection.createRange&&(aK=document.selection.createRange(),aF=0-aK.duplicate().moveStart("character",-aL.inputmask._valueGet().length),aH=aF+aK.text.length),{begin:aI(aF),end:aI(aH)}}aF=aI(aF),aH=aI(aH),aH="number"==typeof aH?aH:aF;var aJ=parseInt(((aL.ownerDocument.defaultView||window).getComputedStyle?(aL.ownerDocument.defaultView||window).getComputedStyle(aL,null):aL.currentStyle).fontSize)*aH;if(aL.scrollLeft=aJ>aL.scrollWidth?aJ:0,b||T.insertMode!==!1||aF!==aH||aH++,aL.setSelectionRange){aL.selectionStart=aF,aL.selectionEnd=aH}else{if(window.getSelection){if(aK=document.createRange(),void 0===aL.firstChild||null===aL.firstChild){var aG=document.createTextNode("");aL.appendChild(aG)}aK.setStart(aL.firstChild,aF<aL.inputmask._valueGet().length?aF:aL.inputmask._valueGet().length),aK.setEnd(aL.firstChild,aH<aL.inputmask._valueGet().length?aH:aL.inputmask._valueGet().length),aK.collapse(!0);var aE=window.getSelection();aE.removeAllRanges(),aE.addRange(aK)}else{aL.createTextRange&&(aK=aL.createTextRange(),aK.collapse(!0),aK.moveEnd("character",aH),aK.moveStart("character",aF),aK.select())}}}function D(aH){var aL,aJ,aF=n(),aE=aF.length,aK=r(),aI={},aM=K().validPositions[aK],aG=void 0!==aM?aM.locator.slice():void 0;for(aL=aK+1;aL<aF.length;aL++){aJ=E(aL,aG,aL-1),aG=aJ.locator.slice(),aI[aL]=f.extend(!0,{},aJ)}var aD=aM&&void 0!==aM.alternation?aM.locator[aM.alternation]:void 0;for(aL=aE-1;aL>aK&&(aJ=aI[aL],(aJ.match.optionality||aJ.match.optionalQuantifier||aD&&(aD!==aI[aL].locator[aM.alternation]&&null!=aJ.match.fn||null===aJ.match.fn&&aJ.locator[aM.alternation]&&o(aJ.locator[aM.alternation].toString().split(","),aD.toString().split(","))&&""!==C(aL)[0].def))&&aF[aL]===aA(aL,aJ.match));aL--){aE--}return aH?{l:aE,def:aI[aE]?aI[aE].match:void 0}:aE}function av(aE){for(var aF=D(),aD=aE.length-1;aD>aF&&!M(aD);aD--){}return aE.splice(aF,aD+1-aF),aE}function ad(aE){if(f.isFunction(T.isComplete)){return T.isComplete(aE,T)}if("*"===T.repeat){return void 0}var aD=!1,aF=D(!0),aH=au(aF.l);if(void 0===aF.def||aF.def.newBlockMarker||aF.def.optionality||aF.def.optionalQuantifier){aD=!0;for(var aG=0;aH>=aG;aG++){var aI=E(aG).match;if(null!==aI.fn&&void 0===K().validPositions[aG]&&aI.optionality!==!0&&aI.optionalQuantifier!==!0||null===aI.fn&&aE[aG]!==aA(aG,aI)){aD=!1;break}}}return aD}function an(aJ){function aF(aM){if(f.valHooks&&(void 0===f.valHooks[aM]||f.valHooks[aM].inputmaskpatch!==!0)){var aL=f.valHooks[aM]&&f.valHooks[aM].get?f.valHooks[aM].get:function(aO){return aO.value},aN=f.valHooks[aM]&&f.valHooks[aM].set?f.valHooks[aM].set:function(aO,aP){return aO.value=aP,aO};f.valHooks[aM]={get:function(aQ){if(aQ.inputmask){if(aQ.inputmask.opts.autoUnmask){return aQ.inputmask.unmaskedvalue()}var aO=aL(aQ),aR=aQ.inputmask.maskset,aP=aR._buffer;return aP=aP?aP.join(""):"",aO!==aP?aO:""}return aL(aQ)},set:function(aQ,aR){var aO,aP=f(aQ);return aO=aN(aQ,aR),aQ.inputmask&&aP.trigger("setvalue"),aO},inputmaskpatch:!0}}}function aD(){return this.inputmask?this.inputmask.opts.autoUnmask?this.inputmask.unmaskedvalue():aI.call(this)!==aC().join("")?document.activeElement===this&&T.clearMaskOnLostFocus?(ao?av(n().slice()).reverse():av(n().slice())).join(""):aI.call(this):"":aI.call(this)}function aK(aL){aE.call(this,aL),this.inputmask&&f(this).trigger("setvalue")}function aG(aL){W.on(aL,"mouseenter",function(aN){var aP=f(this),aM=this,aO=aM.inputmask._valueGet();aO!==n().join("")&&aP.trigger("setvalue")})}var aI,aE;if(!aJ.inputmask.__valueGet){if(Object.getOwnPropertyDescriptor){var aH=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(aJ),"value");aH&&aH.get&&aH.set?(aI=aH.get,aE=aH.set,Object.defineProperty(aJ,"value",{get:aD,set:aK,configurable:!0})):"INPUT"!==aJ.tagName&&(aI=function(){return this.textContent},aE=function(aL){this.textContent=aL},Object.defineProperty(aJ,"value",{get:aD,set:aK,configurable:!0}))}else{document.__lookupGetter__&&aJ.__lookupGetter__("value")&&(aI=aJ.__lookupGetter__("value"),aE=aJ.__lookupSetter__("value"),aJ.__defineGetter__("value",aD),aJ.__defineSetter__("value",aK))}void 0===aI&&(aI=function(){return aJ.value},aE=function(aL){aJ.value=aL},aF(aJ.type),aG(aJ)),aJ.inputmask.__valueGet=aI,aJ.inputmask._valueGet=function(aL){return ao&&aL!==!0?aI.call(this.el).split("").reverse().join(""):aI.call(this.el)},aJ.inputmask.__valueSet=aE,aJ.inputmask._valueSet=function(aL,aM){aE.call(this.el,null===aL||void 0===aL?"":aM!==!0&&ao?aL.split("").reverse().join(""):aL)}}}function V(aF,aE,aJ,aD){function aH(){if(T.keepStatic){N(!0);var aM,aL=[],aN=f.extend(!0,{},K().validPositions);for(aM=r();aM>=0;aM--){var aO=K().validPositions[aM];if(aO&&(null!=aO.match.fn&&aL.push(aO.input),delete K().validPositions[aM],void 0!==aO.alternation&&aO.locator[aO.alternation]===E(aM).locator[aO.alternation])){break}}if(aM>-1){for(;aL.length>0;){K().p=p(r());var aK=new f.Event("keypress");aK.which=aL.pop().charCodeAt(0),J.call(aF,aK,!0,!1,!1,K().p)}}else{K().validPositions=f.extend(!0,{},aN)}}}if((T.numericInput||ao)&&(aE===e.keyCode.BACKSPACE?aE=e.keyCode.DELETE:aE===e.keyCode.DELETE&&(aE=e.keyCode.BACKSPACE),ao)){var aG=aJ.end;aJ.end=aJ.begin,aJ.begin=aG}aE===e.keyCode.BACKSPACE&&(aJ.end-aJ.begin<1||T.insertMode===!1)?(aJ.begin=au(aJ.begin),void 0===K().validPositions[aJ.begin]||K().validPositions[aJ.begin].input!==T.groupSeparator&&K().validPositions[aJ.begin].input!==T.radixPoint||aJ.begin--):aE===e.keyCode.DELETE&&aJ.begin===aJ.end&&(aJ.end=M(aJ.end)?aJ.end+1:p(aJ.end)+1,void 0===K().validPositions[aJ.begin]||K().validPositions[aJ.begin].input!==T.groupSeparator&&K().validPositions[aJ.begin].input!==T.radixPoint||aJ.end++),aa(aJ.begin,aJ.end,!1,aD),aD!==!0&&aH();var aI=r(aJ.begin);aI<aJ.begin?(-1===aI&&N(),K().p=p(aI)):aD!==!0&&(K().p=aJ.begin)}function az(aG){var aE=this,aI=f(aE),aD=aG.keyCode,aH=I(aE);if(aD===e.keyCode.BACKSPACE||aD===e.keyCode.DELETE||j&&aD===e.keyCode.BACKSPACE_SAFARI||aG.ctrlKey&&aD===e.keyCode.X&&!k("cut")){aG.preventDefault(),V(aE,aD,aH),ac(aE,n(),K().p,aG,R!==n().join("")),aE.inputmask._valueGet()===aC().join("")?aI.trigger("cleared"):ad(n())===!0&&aI.trigger("complete"),T.showTooltip&&(aE.title=T.tooltip||K().mask)}else{if(aD===e.keyCode.END||aD===e.keyCode.PAGE_DOWN){aG.preventDefault();var aF=p(r());T.insertMode||aF!==ak()||aG.shiftKey||aF--,I(aE,aG.shiftKey?aH.begin:aF,aF,!0)}else{aD===e.keyCode.HOME&&!aG.shiftKey||aD===e.keyCode.PAGE_UP?(aG.preventDefault(),I(aE,0,aG.shiftKey?aH.begin:0,!0)):(T.undoOnEscape&&aD===e.keyCode.ESCAPE||90===aD&&aG.ctrlKey)&&aG.altKey!==!0?(z(aE,!0,!1,R.split("")),aI.trigger("click")):aD!==e.keyCode.INSERT||aG.shiftKey||aG.ctrlKey?T.tabThrough===!0&&aD===e.keyCode.TAB?(aG.shiftKey===!0?(null===ag(aH.begin).fn&&(aH.begin=p(aH.begin)),aH.end=au(aH.begin,!0),aH.begin=au(aH.end,!0)):(aH.begin=p(aH.begin,!0),aH.end=p(aH.begin,!0),aH.end<ak()&&aH.end--),aH.begin<ak()&&(aG.preventDefault(),I(aE,aH.begin,aH.end))):T.insertMode!==!1||aG.shiftKey||(aD===e.keyCode.RIGHT?setTimeout(function(){var aJ=I(aE);I(aE,aJ.begin)},0):aD===e.keyCode.LEFT&&setTimeout(function(){var aJ=I(aE);I(aE,ao?aJ.begin+1:aJ.begin-1)},0)):(T.insertMode=!T.insertMode,I(aE,T.insertMode||aH.begin!==ak()?aH.begin:aH.begin-1))}}T.onKeyDown.call(this,aG,n(),I(aE).begin,T),G=-1!==f.inArray(aD,T.ignorables)}function J(aR,aG,aD,aU,aK){var aM=this,aE=f(aM),aQ=aR.which||aR.charCode||aR.keyCode;if(!(aG===!0||aR.ctrlKey&&aR.altKey)&&(aR.ctrlKey||aR.metaKey||G)){return aQ===e.keyCode.ENTER&&R!==n().join("")&&(R=n().join(""),setTimeout(function(){aE.trigger("change")},0)),!0}if(aQ){46===aQ&&aR.shiftKey===!1&&","===T.radixPoint&&(aQ=44);var aI,aJ=aG?{begin:aK,end:aK}:I(aM),aS=String.fromCharCode(aQ);K().writeOutBuffer=!0;var aF=u(aJ,aS,aU);if(aF!==!1){var aO=aF.pos;if(N(!0),void 0!==aF.caret){aI=aF.caret}else{var aT=K().validPositions;aI=!T.keepStatic&&(void 0!==aT[aO+1]&&C(aO+1,aT[aO].locator.slice(),aO).length>1||void 0!==aT[aO].alternation)?aO+1:p(aO)}K().p=aI}if(aD!==!1){var aN=this;if(setTimeout(function(){T.onKeyValidation.call(aN,aQ,aF,T)},0),K().writeOutBuffer&&aF!==!1){var aP=n();ac(aM,aP,T.numericInput&&void 0===aF.caret?au(aI):aI,aR,aG!==!0),aG!==!0&&setTimeout(function(){ad(aP)===!0&&aE.trigger("complete")},0)}}if(T.showTooltip&&(aM.title=T.tooltip||K().mask),aG&&f.isFunction(T.onBeforeWrite)){var aL=T.onBeforeWrite(aR,n(),aI,T);if(aL&&aL.refreshFromBuffer){var aH=aL.refreshFromBuffer;ab(aH===!0?aH:aH.start,aH.end,aL.buffer),N(!0),aL.caret&&(K().p=aL.caret)}}if(aR.preventDefault(),aG){return aF}}}function am(aI){var aD,aM=this,aK=aI.originalEvent||aI,aJ=f(aM),aE=aM.inputmask._valueGet(!0),aH=I(aM);ao&&(aD=aH.end,aH.end=aH.begin,aH.begin=aD);var aG=aE.substr(0,aH.begin),aF=aE.substr(aH.end,aE.length);aG===(ao?aC().reverse():aC()).slice(0,aH.begin).join("")&&(aG=""),aF===(ao?aC().reverse():aC()).slice(aH.end).join("")&&(aF=""),ao&&(aD=aG,aG=aF,aF=aD),window.clipboardData&&window.clipboardData.getData?aE=aG+window.clipboardData.getData("Text")+aF:aK.clipboardData&&aK.clipboardData.getData&&(aE=aG+aK.clipboardData.getData("text/plain")+aF);var aL=aE;if(f.isFunction(T.onBeforePaste)){if(aL=T.onBeforePaste(aE,T),aL===!1){return aI.preventDefault()}aL||(aL=aE)}return z(aM,!1,!1,ao?aL.split("").reverse():aL.toString().split("")),ac(aM,n(),p(r()),aI,!0),ad(n())===!0&&aJ.trigger("complete"),aI.preventDefault()}function H(aJ){var aF=this,aD=aF.inputmask._valueGet();if(n().join("")!==aD){var aH=I(aF);if(aD=aD.replace(new RegExp("("+e.escapeRegex(aC().join(""))+")*"),""),a){var aI=aD.replace(n().join(""),"");if(1===aI.length){var aE=new f.Event("keypress");return aE.which=aI.charCodeAt(0),J.call(aF,aE,!0,!0,!1,K().validPositions[aH.begin-1]?aH.begin:aH.begin-1),!1}}if(aH.begin>aD.length&&(I(aF,aD.length),aH=I(aF)),n().length-aD.length!==1||aD.charAt(aH.begin)===n()[aH.begin]||aD.charAt(aH.begin+1)===n()[aH.begin]||M(aH.begin)){for(var aK=r()+1,aG=n().slice(aK).join("");null===aD.match(e.escapeRegex(aG)+"$");){aG=aG.slice(1)}aD=aD.replace(aG,""),aD=aD.split(""),z(aF,!0,!1,aD),ad(n())===!0&&f(aF).trigger("complete")}else{aJ.keyCode=e.keyCode.BACKSPACE,az.call(aF,aJ)}aJ.preventDefault()}}function Q(aF){var aD=this,aE=aD.inputmask._valueGet();z(aD,!0,!1,(f.isFunction(T.onBeforeMask)?T.onBeforeMask(aE,T)||aE:aE).split("")),R=n().join(""),(T.clearMaskOnLostFocus||T.clearIncomplete)&&aD.inputmask._valueGet()===aC().join("")&&aD.inputmask._valueSet("")}function Y(aE){var aD=this,aF=aD.inputmask._valueGet();T.showMaskOnFocus&&(!T.showMaskOnHover||T.showMaskOnHover&&""===aF)?aD.inputmask._valueGet()!==n().join("")&&ac(aD,n(),p(r())):x===!1&&I(aD,p(r())),T.positionCaretOnTab===!0&&setTimeout(function(){I(aD,p(r()))},0),R=n().join("")}function ay(aF){var aE=this;if(x=!1,T.clearMaskOnLostFocus&&document.activeElement!==aE){var aD=n().slice(),aG=aE.inputmask._valueGet();aG!==aE.getAttribute("placeholder")&&""!==aG&&(-1===r()&&aG===aC().join("")?aD=[]:av(aD),ac(aE,aD))}}function aB(aJ){function aI(aM){if(T.radixFocus&&""!==T.radixPoint){var aN=K().validPositions;if(void 0===aN[aM]||aN[aM].input===aA(aM)){if(aM<p(-1)){return !0}var aK=f.inArray(T.radixPoint,n());if(-1!==aK){for(var aL in aN){if(aL>aK&&aN[aL].input!==aA(aL)){return !1}}return !0}}}return !1}var aF=this;if(document.activeElement===aF){var aH=I(aF);if(aH.begin===aH.end){if(aI(aH.begin)){I(aF,T.numericInput?p(f.inArray(T.radixPoint,n())):f.inArray(T.radixPoint,n()))}else{var aG=aH.begin,aE=r(aG,!0),aD=p(aE);aD>aG?I(aF,M(aG)||M(aG-1)?aG:p(aG)):((n()[aD]!==aA(aD)||!M(aD,!0)&&ag(aD).def===aA(aD))&&(aD=p(aD)),I(aF,aD))}}}}function t(aE){var aD=this;setTimeout(function(){I(aD,0,p(r()))},0)}function af(aG){var aD=this,aJ=f(aD),aI=I(aD),aF=aG.originalEvent||aG,aH=window.clipboardData||aF.clipboardData,aE=ao?n().slice(aI.end,aI.begin):n().slice(aI.begin,aI.end);aH.setData("text",ao?aE.reverse().join(""):aE.join("")),document.execCommand&&document.execCommand("copy"),V(aD,e.keyCode.DELETE,aI),ac(aD,n(),K().p,aG,R!==n().join("")),aD.inputmask._valueGet()===aC().join("")&&aJ.trigger("cleared"),T.showTooltip&&(aD.title=T.tooltip||K().mask)}function v(aF){var aH=f(this),aE=this;if(aE.inputmask){var aG=aE.inputmask._valueGet(),aD=n().slice();R!==aD.join("")&&setTimeout(function(){aH.trigger("change"),R=aD.join("")},0),""!==aG&&(T.clearMaskOnLostFocus&&(-1===r()&&aG===aC().join("")?aD=[]:av(aD)),ad(aD)===!1&&(setTimeout(function(){aH.trigger("incomplete")},0),T.clearIncomplete&&(N(),aD=T.clearMaskOnLostFocus?[]:aC().slice())),ac(aE,aD,void 0,aF))}}function P(aE){var aD=this;x=!0,document.activeElement!==aD&&T.showMaskOnHover&&aD.inputmask._valueGet()!==n().join("")&&ac(aD,n())}function aj(aD){R!==n().join("")&&al.trigger("change"),T.clearMaskOnLostFocus&&-1===r()&&ax.inputmask._valueGet&&ax.inputmask._valueGet()===aC().join("")&&ax.inputmask._valueSet(""),T.removeMaskOnSubmit&&(ax.inputmask._valueSet(ax.inputmask.unmaskedvalue(),!0),setTimeout(function(){ac(ax,n())},0))}function X(aD){setTimeout(function(){al.trigger("setvalue")},0)}function at(aF){if(ax=aF,al=f(ax),T.showTooltip&&(ax.title=T.tooltip||K().mask),("rtl"===ax.dir||T.rightAlign)&&(ax.style.textAlign="right"),("rtl"===ax.dir||T.numericInput)&&(ax.dir="ltr",ax.removeAttribute("dir"),ax.inputmask.isRTL=!0,ao=!0),W.off(ax),an(ax),i(ax,T)&&(W.on(ax,"submit",aj),W.on(ax,"reset",X),W.on(ax,"mouseenter",P),W.on(ax,"blur",v),W.on(ax,"focus",Y),W.on(ax,"mouseleave",ay),W.on(ax,"click",aB),W.on(ax,"dblclick",t),W.on(ax,"paste",am),W.on(ax,"dragdrop",am),W.on(ax,"drop",am),W.on(ax,"cut",af),W.on(ax,"complete",T.oncomplete),W.on(ax,"incomplete",T.onincomplete),W.on(ax,"cleared",T.oncleared),W.on(ax,"keydown",az),W.on(ax,"keypress",J),W.on(ax,"input",H)),W.on(ax,"setvalue",Q),""!==ax.inputmask._valueGet()||T.clearMaskOnLostFocus===!1||document.activeElement===ax){var aD=f.isFunction(T.onBeforeMask)?T.onBeforeMask(ax.inputmask._valueGet(),T)||ax.inputmask._valueGet():ax.inputmask._valueGet();z(ax,!0,!1,aD.split(""));var aE=n().slice();R=aE.join(""),ad(aE)===!1&&T.clearIncomplete&&N(),T.clearMaskOnLostFocus&&document.activeElement!==ax&&(aE.join("")===aC().join("")?aE=[]:av(aE)),ac(ax,aE),document.activeElement===ax&&I(ax,p(r()))}}var R,ax,al,y,q,ao=!1,ah=!1,s=!1,G=!1,x=!0,W={on:function(aE,aD,aF){var aG=function(aK){if(void 0===this.inputmask&&"FORM"!==this.nodeName){var aH=f.data(this,"_inputmask_opts");aH?new e(aH).mask(this):W.off(this)}else{if("setvalue"===aK.type||!(this.disabled||this.readOnly&&!("keydown"===aK.type&&aK.ctrlKey&&67===aK.keyCode||T.tabThrough===!1&&aK.keyCode===e.keyCode.TAB))){switch(aK.type){case"input":if(s===!0){return s=!1,aK.preventDefault()}break;case"keydown":ah=!1,s=!1;break;case"keypress":if(ah===!0){return aK.preventDefault()}ah=!0;break;case"click":if(a){var aJ=this;return setTimeout(function(){aF.apply(aJ,arguments)},0),!1}}var aI=aF.apply(this,arguments);return aI===!1&&(aK.preventDefault(),aK.stopPropagation()),aI}aK.preventDefault()}};aE.inputmask.events[aD]=aE.inputmask.events[aD]||[],aE.inputmask.events[aD].push(aG),-1!==f.inArray(aD,["submit","reset"])?null!=aE.form&&f(aE.form).on(aD,aG):f(aE).on(aD,aG)},off:function(aD,aF){if(aD.inputmask&&aD.inputmask.events){var aE;aF?(aE=[],aE[aF]=aD.inputmask.events[aF]):aE=aD.inputmask.events,f.each(aE,function(aG,aI){for(;aI.length>0;){var aH=aI.pop();-1!==f.inArray(aG,["submit","reset"])?null!=aD.form&&f(aD.form).off(aG,aH):f(aD).off(aG,aH)}delete aD.inputmask.events[aG]})}}};if(void 0!==w){switch(w.action){case"isComplete":return ax=w.el,ad(n());case"unmaskedvalue":return ax=w.el,void 0!==ax&&void 0!==ax.inputmask?(F=ax.inputmask.maskset,T=ax.inputmask.opts,ao=ax.inputmask.isRTL):(q=w.value,T.numericInput&&(ao=!0),q=(f.isFunction(T.onBeforeMask)?T.onBeforeMask(q,T)||q:q).split(""),z(void 0,!1,!1,ao?q.reverse():q),f.isFunction(T.onBeforeWrite)&&T.onBeforeWrite(void 0,n(),0,T)),m(ax);case"mask":ax=w.el,F=ax.inputmask.maskset,T=ax.inputmask.opts,ao=ax.inputmask.isRTL,R=n().join(""),at(ax);break;case"format":return T.numericInput&&(ao=!0),q=(f.isFunction(T.onBeforeMask)?T.onBeforeMask(w.value,T)||w.value:w.value).split(""),z(void 0,!1,!1,ao?q.reverse():q),f.isFunction(T.onBeforeWrite)&&T.onBeforeWrite(void 0,n(),0,T),w.metadata?{value:ao?n().slice().reverse().join(""):n().join(""),metadata:g({action:"getmetadata"},F,T)}:ao?n().slice().reverse().join(""):n().join("");case"isValid":T.numericInput&&(ao=!0),w.value?(q=w.value.split(""),z(void 0,!1,!0,ao?q.reverse():q)):w.value=n().join("");for(var O=n(),ae=D(),L=O.length-1;L>ae&&!M(L);L--){}return O.splice(ae,L+1-ae),ad(O)&&w.value===n().join("");case"getemptymask":return aC().join("");case"remove":ax=w.el,al=f(ax),F=ax.inputmask.maskset,T=ax.inputmask.opts,ax.inputmask._valueSet(m(ax)),W.off(ax);var ap;Object.getOwnPropertyDescriptor?(ap=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(ax),"value"),ap&&ax.inputmask.__valueGet&&Object.defineProperty(ax,"value",{get:ax.inputmask.__valueGet,set:ax.inputmask.__valueSet,configurable:!0})):document.__lookupGetter__&&ax.__lookupGetter__("value")&&ax.inputmask.__valueGet&&(ax.__defineGetter__("value",ax.inputmask.__valueGet),ax.__defineSetter__("value",ax.inputmask.__valueSet)),ax.inputmask=void 0;break;case"getmetadata":if(f.isArray(F.metadata)){for(var ai,aq=r(void 0,!0),A=aq;A>=0;A--){if(K().validPositions[A]&&void 0!==K().validPositions[A].alternation){ai=K().validPositions[A].alternation;break}}return void 0!==ai?F.metadata[K().validPositions[A].locator[ai]]:[]}return F.metadata}}}e.prototype={defaults:{placeholder:"_",optionalmarker:{start:"[",end:"]"},quantifiermarker:{start:"{",end:"}"},groupmarker:{start:"(",end:")"},alternatormarker:"|",escapeChar:"\\",mask:null,oncomplete:f.noop,onincomplete:f.noop,oncleared:f.noop,repeat:0,greedy:!0,autoUnmask:!1,removeMaskOnSubmit:!1,clearMaskOnLostFocus:!0,insertMode:!0,clearIncomplete:!1,aliases:{},alias:null,onKeyDown:f.noop,onBeforeMask:null,onBeforePaste:function(m,n){return f.isFunction(n.onBeforeMask)?n.onBeforeMask(m,n):m},onBeforeWrite:null,onUnMask:null,showMaskOnFocus:!0,showMaskOnHover:!0,onKeyValidation:f.noop,skipOptionalPartCharacter:" ",showTooltip:!1,tooltip:void 0,numericInput:!1,rightAlign:!1,undoOnEscape:!0,radixPoint:"",radixPointDefinitionSymbol:void 0,groupSeparator:"",radixFocus:!1,nojumps:!1,nojumpsThreshold:0,keepStatic:null,positionCaretOnTab:!1,tabThrough:!1,supportsInputType:["text","tel","password"],definitions:{"9":{validator:"[0-9]",cardinality:1,definitionSymbol:"*"},a:{validator:"[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",cardinality:1,definitionSymbol:"*"},"*":{validator:"[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",cardinality:1}},ignorables:[8,9,13,19,27,33,34,35,36,37,38,39,40,45,46,93,112,113,114,115,116,117,118,119,120,121,122,123],isComplete:null,canClearPosition:f.noop,postValidation:null,staticDefinitionSymbol:void 0,jitMasking:!1},masksCache:{},mask:function(m){var n=this;return"string"==typeof m&&(m=document.getElementById(m)||document.querySelectorAll(m)),m=m.nodeName?[m]:m,f.each(m,function(p,q){var o=f.extend(!0,{},n.opts);l(q,o,f.extend(!0,{},n.userOptions));var r=d(o,n.noMasksCache);void 0!==r&&(void 0!==q.inputmask&&q.inputmask.remove(),q.inputmask=new e(),q.inputmask.opts=o,q.inputmask.noMasksCache=n.noMasksCache,q.inputmask.userOptions=f.extend(!0,{},n.userOptions),q.inputmask.el=q,q.inputmask.maskset=r,q.inputmask.isRTL=!1,f.data(q,"_inputmask_opts",o),g({action:"mask",el:q}))}),m&&m[0]?m[0].inputmask||this:this},option:function(m){return"string"==typeof m?this.opts[m]:"object"==typeof m?(f.extend(this.opts,m),f.extend(this.userOptions,m),this.el&&(void 0!==m.mask||void 0!==m.alias?this.mask(this.el):(f.data(this.el,"_inputmask_opts",this.opts),g({action:"mask",el:this.el}))),this):void 0},unmaskedvalue:function(m){return g({action:"unmaskedvalue",el:this.el,value:m},this.el&&this.el.inputmask?this.el.inputmask.maskset:d(this.opts,this.noMasksCache),this.opts)},remove:function(){return this.el?(g({action:"remove",el:this.el}),this.el.inputmask=void 0,this.el):void 0},getemptymask:function(){return g({action:"getemptymask"},this.maskset||d(this.opts,this.noMasksCache),this.opts)},hasMaskedValue:function(){return !this.opts.autoUnmask},isComplete:function(){return g({action:"isComplete",el:this.el},this.maskset||d(this.opts,this.noMasksCache),this.opts)},getmetadata:function(){return g({action:"getmetadata"},this.maskset||d(this.opts,this.noMasksCache),this.opts)},isValid:function(m){return g({action:"isValid",value:m},this.maskset||d(this.opts,this.noMasksCache),this.opts)},format:function(n,m){return g({action:"format",value:n,metadata:m},this.maskset||d(this.opts,this.noMasksCache),this.opts)}},e.extendDefaults=function(m){f.extend(!0,e.prototype.defaults,m)},e.extendDefinitions=function(m){f.extend(!0,e.prototype.defaults.definitions,m)},e.extendAliases=function(m){f.extend(!0,e.prototype.defaults.aliases,m)},e.format=function(o,m,n){return e(m).format(o,n)},e.unmask=function(n,m){return e(m).unmaskedvalue(n)},e.isValid=function(n,m){return e(m).isValid(n)},e.remove=function(m){f.each(m,function(n,o){o.inputmask&&o.inputmask.remove()})},e.escapeRegex=function(n){var m=["/",".","*","+","?","|","(",")","[","]","{","}","\\","$","^"];return n.replace(new RegExp("(\\"+m.join("|\\")+")","gim"),"\\$1")},e.keyCode={ALT:18,BACKSPACE:8,BACKSPACE_SAFARI:127,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91,X:88};var c=navigator.userAgent,b=/mobile/i.test(c),a=/iemobile/i.test(c),j=/iphone/i.test(c)&&!a;/android.*safari.*/i.test(c)&&!a;return window.Inputmask=e,e}(jQuery),function(b,a){return void 0===b.fn.inputmask&&(b.fn.inputmask=function(e,d){var f,c=this[0];if(void 0===d&&(d={}),"string"==typeof e){switch(e){case"unmaskedvalue":return c&&c.inputmask?c.inputmask.unmaskedvalue():b(c).val();case"remove":return this.each(function(){this.inputmask&&this.inputmask.remove()});case"getemptymask":return c&&c.inputmask?c.inputmask.getemptymask():"";case"hasMaskedValue":return c&&c.inputmask?c.inputmask.hasMaskedValue():!1;case"isComplete":return c&&c.inputmask?c.inputmask.isComplete():!0;case"getmetadata":return c&&c.inputmask?c.inputmask.getmetadata():void 0;case"setvalue":b(c).val(d),c&&void 0!==c.inputmask&&b(c).triggerHandler("setvalue");break;case"option":if("string"!=typeof d){return this.each(function(){return void 0!==this.inputmask?this.inputmask.option(d):void 0})}if(c&&void 0!==c.inputmask){return c.inputmask.option(d)}break;default:return d.alias=e,f=new a(d),this.each(function(){f.mask(this)})}}else{if("object"==typeof e){return f=new a(e),void 0===e.mask&&void 0===e.alias?this.each(function(){return void 0!==this.inputmask?this.inputmask.option(e):void f.mask(this)}):this.each(function(){f.mask(this)})}if(void 0===e){return this.each(function(){f=new a(d),f.mask(this)})}}}),b.fn.inputmask}(jQuery,Inputmask),function(b,a){return a.extendDefinitions({h:{validator:"[01][0-9]|2[0-3]",cardinality:2,prevalidator:[{validator:"[0-2]",cardinality:1}]},s:{validator:"[0-5][0-9]",cardinality:2,prevalidator:[{validator:"[0-5]",cardinality:1}]},d:{validator:"0[1-9]|[12][0-9]|3[01]",cardinality:2,prevalidator:[{validator:"[0-3]",cardinality:1}]},m:{validator:"0[1-9]|1[012]",cardinality:2,prevalidator:[{validator:"[01]",cardinality:1}]},y:{validator:"(19|20)\\d{2}",cardinality:4,prevalidator:[{validator:"[12]",cardinality:1},{validator:"(19|20)",cardinality:2},{validator:"(19|20)\\d",cardinality:3}]}}),a.extendAliases({"dd/mm/yyyy":{mask:"1/2/y",placeholder:"dd/mm/yyyy",regex:{val1pre:new RegExp("[0-3]"),val1:new RegExp("0[1-9]|[12][0-9]|3[01]"),val2pre:function(d){var c=a.escapeRegex.call(this,d);return new RegExp("((0[1-9]|[12][0-9]|3[01])"+c+"[01])")},val2:function(d){var c=a.escapeRegex.call(this,d);return new RegExp("((0[1-9]|[12][0-9])"+c+"(0[1-9]|1[012]))|(30"+c+"(0[13-9]|1[012]))|(31"+c+"(0[13578]|1[02]))")}},leapday:"29/02/",separator:"/",yearrange:{minyear:1900,maxyear:2099},isInYearRange:function(f,c,d){if(isNaN(f)){return !1}var e=parseInt(f.concat(c.toString().slice(f.length))),g=parseInt(f.concat(d.toString().slice(f.length)));return(isNaN(e)?!1:e>=c&&d>=e)||(isNaN(g)?!1:g>=c&&d>=g)},determinebaseyear:function(i,e,h){var g=new Date().getFullYear();if(i>g){return i}if(g>e){for(var d=e.toString().slice(0,2),f=e.toString().slice(2,4);d+h>e;){d--}var j=d+f;return i>j?i:j}if(g>=i&&e>=g){for(var c=g.toString().slice(0,2);c+h>e;){c--}var k=c+h;return i>k?i:k}return g},onKeyDown:function(h,c,f,g){var i=b(this);if(h.ctrlKey&&h.keyCode===a.keyCode.RIGHT){var d=new Date();i.val(d.getDate().toString()+(d.getMonth()+1).toString()+d.getFullYear().toString()),i.trigger("setvalue")}},getFrontValue:function(d,c,h){for(var j=0,g=0,f=0;f<d.length&&"2"!==d.charAt(f);f++){var e=h.definitions[d.charAt(f)];e?(j+=g,g=e.cardinality):g++}return c.join("").substr(j,g)},definitions:{"1":{validator:function(d,g,h,c,e){var f=e.regex.val1.test(d);return c||f||d.charAt(1)!==e.separator&&-1==="-./".indexOf(d.charAt(1))||!(f=e.regex.val1.test("0"+d.charAt(0)))?f:(g.buffer[h-1]="0",{refreshFromBuffer:{start:h-1,end:h},pos:h,c:d.charAt(0)})},cardinality:2,prevalidator:[{validator:function(d,h,i,c,f){var e=d;isNaN(h.buffer[i+1])||(e+=h.buffer[i+1]);var g=1===e.length?f.regex.val1pre.test(e):f.regex.val1.test(e);if(!c&&!g){if(g=f.regex.val1.test(d+"0")){return h.buffer[i]=d,h.buffer[++i]="0",{pos:i,c:"0"}}if(g=f.regex.val1.test("0"+d)){return h.buffer[i]="0",i++,{pos:i}}}return g},cardinality:1}]},"2":{validator:function(e,i,g,h,c){var d=c.getFrontValue(i.mask,i.buffer,c);-1!==d.indexOf(c.placeholder[0])&&(d="01"+c.separator);var k=c.regex.val2(c.separator).test(d+e);if(!h&&!k&&(e.charAt(1)===c.separator||-1!=="-./".indexOf(e.charAt(1)))&&(k=c.regex.val2(c.separator).test(d+"0"+e.charAt(0)))){return i.buffer[g-1]="0",{refreshFromBuffer:{start:g-1,end:g},pos:g,c:e.charAt(0)}}if(c.mask.indexOf("2")===c.mask.length-1&&k){var j=i.buffer.join("").substr(4,4)+e;if(j!==c.leapday){return !0}var f=parseInt(i.buffer.join("").substr(0,4),10);return f%4===0?f%100===0?f%400===0?!0:!1:!0:!1}return k},cardinality:2,prevalidator:[{validator:function(d,h,i,c,e){isNaN(h.buffer[i+1])||(d+=h.buffer[i+1]);var g=e.getFrontValue(h.mask,h.buffer,e);-1!==g.indexOf(e.placeholder[0])&&(g="01"+e.separator);var f=1===d.length?e.regex.val2pre(e.separator).test(g+d):e.regex.val2(e.separator).test(g+d);return c||f||!(f=e.regex.val2(e.separator).test(g+"0"+d))?f:(h.buffer[i]="0",i++,{pos:i})},cardinality:1}]},y:{validator:function(d,g,i,c,f){if(f.isInYearRange(d,f.yearrange.minyear,f.yearrange.maxyear)){var h=g.buffer.join("").substr(0,6);if(h!==f.leapday){return !0}var e=parseInt(d,10);return e%4===0?e%100===0?e%400===0?!0:!1:!0:!1}return !1},cardinality:4,prevalidator:[{validator:function(e,h,i,d,f){var g=f.isInYearRange(e,f.yearrange.minyear,f.yearrange.maxyear);if(!d&&!g){var c=f.determinebaseyear(f.yearrange.minyear,f.yearrange.maxyear,e+"0").toString().slice(0,1);if(g=f.isInYearRange(c+e,f.yearrange.minyear,f.yearrange.maxyear)){return h.buffer[i++]=c.charAt(0),{pos:i}}if(c=f.determinebaseyear(f.yearrange.minyear,f.yearrange.maxyear,e+"0").toString().slice(0,2),g=f.isInYearRange(c+e,f.yearrange.minyear,f.yearrange.maxyear)){return h.buffer[i++]=c.charAt(0),h.buffer[i++]=c.charAt(1),{pos:i}}}return g},cardinality:1},{validator:function(d,i,g,h,c){var k=c.isInYearRange(d,c.yearrange.minyear,c.yearrange.maxyear);if(!h&&!k){var e=c.determinebaseyear(c.yearrange.minyear,c.yearrange.maxyear,d).toString().slice(0,2);if(k=c.isInYearRange(d[0]+e[1]+d[1],c.yearrange.minyear,c.yearrange.maxyear)){return i.buffer[g++]=e.charAt(1),{pos:g}}if(e=c.determinebaseyear(c.yearrange.minyear,c.yearrange.maxyear,d).toString().slice(0,2),c.isInYearRange(e+d,c.yearrange.minyear,c.yearrange.maxyear)){var j=i.buffer.join("").substr(0,6);if(j!==c.leapday){k=!0}else{var f=parseInt(d,10);k=f%4===0?f%100===0?f%400===0?!0:!1:!0:!1}}else{k=!1}if(k){return i.buffer[g-1]=e.charAt(0),i.buffer[g++]=e.charAt(1),i.buffer[g++]=d.charAt(0),{refreshFromBuffer:{start:g-3,end:g},pos:g}}}return k},cardinality:2},{validator:function(d,f,g,c,e){return e.isInYearRange(d,e.yearrange.minyear,e.yearrange.maxyear)},cardinality:3}]}},insertMode:!1,autoUnmask:!1},"mm/dd/yyyy":{placeholder:"mm/dd/yyyy",alias:"dd/mm/yyyy",regex:{val2pre:function(d){var c=a.escapeRegex.call(this,d);return new RegExp("((0[13-9]|1[012])"+c+"[0-3])|(02"+c+"[0-2])")},val2:function(d){var c=a.escapeRegex.call(this,d);return new RegExp("((0[1-9]|1[012])"+c+"(0[1-9]|[12][0-9]))|((0[13-9]|1[012])"+c+"30)|((0[13578]|1[02])"+c+"31)")},val1pre:new RegExp("[01]"),val1:new RegExp("0[1-9]|1[012]")},leapday:"02/29/",onKeyDown:function(h,c,f,g){var i=b(this);if(h.ctrlKey&&h.keyCode===a.keyCode.RIGHT){var d=new Date();i.val((d.getMonth()+1).toString()+d.getDate().toString()+d.getFullYear().toString()),i.trigger("setvalue")}}},"yyyy/mm/dd":{mask:"y/1/2",placeholder:"yyyy/mm/dd",alias:"mm/dd/yyyy",leapday:"/02/29",onKeyDown:function(h,c,f,g){var i=b(this);if(h.ctrlKey&&h.keyCode===a.keyCode.RIGHT){var d=new Date();i.val(d.getFullYear().toString()+(d.getMonth()+1).toString()+d.getDate().toString()),i.trigger("setvalue")}}},"dd.mm.yyyy":{mask:"1.2.y",placeholder:"dd.mm.yyyy",leapday:"29.02.",separator:".",alias:"dd/mm/yyyy"},"dd-mm-yyyy":{mask:"1-2-y",placeholder:"dd-mm-yyyy",leapday:"29-02-",separator:"-",alias:"dd/mm/yyyy"},"mm.dd.yyyy":{mask:"1.2.y",placeholder:"mm.dd.yyyy",leapday:"02.29.",separator:".",alias:"mm/dd/yyyy"},"mm-dd-yyyy":{mask:"1-2-y",placeholder:"mm-dd-yyyy",leapday:"02-29-",separator:"-",alias:"mm/dd/yyyy"},"yyyy.mm.dd":{mask:"y.1.2",placeholder:"yyyy.mm.dd",leapday:".02.29",separator:".",alias:"yyyy/mm/dd"},"yyyy-mm-dd":{mask:"y-1-2",placeholder:"yyyy-mm-dd",leapday:"-02-29",separator:"-",alias:"yyyy/mm/dd"},datetime:{mask:"1/2/y h:s",placeholder:"dd/mm/yyyy hh:mm",alias:"dd/mm/yyyy",regex:{hrspre:new RegExp("[012]"),hrs24:new RegExp("2[0-4]|1[3-9]"),hrs:new RegExp("[01][0-9]|2[0-4]"),ampm:new RegExp("^[a|p|A|P][m|M]"),mspre:new RegExp("[0-5]"),ms:new RegExp("[0-5][0-9]")},timeseparator:":",hourFormat:"24",definitions:{h:{validator:function(e,h,i,c,f){if("24"===f.hourFormat&&24===parseInt(e,10)){return h.buffer[i-1]="0",h.buffer[i]="0",{refreshFromBuffer:{start:i-1,end:i},c:"0"}}var g=f.regex.hrs.test(e);if(!c&&!g&&(e.charAt(1)===f.timeseparator||-1!=="-.:".indexOf(e.charAt(1)))&&(g=f.regex.hrs.test("0"+e.charAt(0)))){return h.buffer[i-1]="0",h.buffer[i]=e.charAt(0),i++,{refreshFromBuffer:{start:i-2,end:i},pos:i,c:f.timeseparator}}if(g&&"24"!==f.hourFormat&&f.regex.hrs24.test(e)){var d=parseInt(e,10);return 24===d?(h.buffer[i+5]="a",h.buffer[i+6]="m"):(h.buffer[i+5]="p",h.buffer[i+6]="m"),d-=12,10>d?(h.buffer[i]=d.toString(),h.buffer[i-1]="0"):(h.buffer[i]=d.toString().charAt(1),h.buffer[i-1]=d.toString().charAt(0)),{refreshFromBuffer:{start:i-1,end:i+6},c:h.buffer[i]}}return g},cardinality:2,prevalidator:[{validator:function(d,g,h,c,e){var f=e.regex.hrspre.test(d);return c||f||!(f=e.regex.hrs.test("0"+d))?f:(g.buffer[h]="0",h++,{pos:h})},cardinality:1}]},s:{validator:"[0-5][0-9]",cardinality:2,prevalidator:[{validator:function(d,g,h,c,e){var f=e.regex.mspre.test(d);return c||f||!(f=e.regex.ms.test("0"+d))?f:(g.buffer[h]="0",h++,{pos:h})},cardinality:1}]},t:{validator:function(d,f,g,c,e){return e.regex.ampm.test(d+"m")},casing:"lower",cardinality:1}},insertMode:!1,autoUnmask:!1},datetime12:{mask:"1/2/y h:s t\\m",placeholder:"dd/mm/yyyy hh:mm xm",alias:"datetime",hourFormat:"12"},"mm/dd/yyyy hh:mm xm":{mask:"1/2/y h:s t\\m",placeholder:"mm/dd/yyyy hh:mm xm",alias:"datetime12",regex:{val2pre:function(d){var c=a.escapeRegex.call(this,d);return new RegExp("((0[13-9]|1[012])"+c+"[0-3])|(02"+c+"[0-2])")},val2:function(d){var c=a.escapeRegex.call(this,d);return new RegExp("((0[1-9]|1[012])"+c+"(0[1-9]|[12][0-9]))|((0[13-9]|1[012])"+c+"30)|((0[13578]|1[02])"+c+"31)")},val1pre:new RegExp("[01]"),val1:new RegExp("0[1-9]|1[012]")},leapday:"02/29/",onKeyDown:function(h,c,f,g){var i=b(this);if(h.ctrlKey&&h.keyCode===a.keyCode.RIGHT){var d=new Date();i.val((d.getMonth()+1).toString()+d.getDate().toString()+d.getFullYear().toString()),i.trigger("setvalue")}}},"hh:mm t":{mask:"h:s t\\m",placeholder:"hh:mm xm",alias:"datetime",hourFormat:"12"},"h:s t":{mask:"h:s t\\m",placeholder:"hh:mm xm",alias:"datetime",hourFormat:"12"},"hh:mm:ss":{mask:"h:s:s",placeholder:"hh:mm:ss",alias:"datetime",autoUnmask:!1},"hh:mm":{mask:"h:s",placeholder:"hh:mm",alias:"datetime",autoUnmask:!1},date:{alias:"dd/mm/yyyy"},"mm/yyyy":{mask:"1/y",placeholder:"mm/yyyy",leapday:"donotuse",separator:"/",alias:"mm/dd/yyyy"},shamsi:{regex:{val2pre:function(d){var c=a.escapeRegex.call(this,d);return new RegExp("((0[1-9]|1[012])"+c+"[0-3])")},val2:function(d){var c=a.escapeRegex.call(this,d);return new RegExp("((0[1-9]|1[012])"+c+"(0[1-9]|[12][0-9]))|((0[1-9]|1[012])"+c+"30)|((0[1-6])"+c+"31)")},val1pre:new RegExp("[01]"),val1:new RegExp("0[1-9]|1[012]")},yearrange:{minyear:1300,maxyear:1499},mask:"y/1/2",leapday:"/12/30",placeholder:"yyyy/mm/dd",alias:"mm/dd/yyyy",clearIncomplete:!0}}),a}(jQuery,Inputmask),function(b,a){return a.extendDefinitions({A:{validator:"[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",cardinality:1,casing:"upper"},"&":{validator:"[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",cardinality:1,casing:"upper"},"#":{validator:"[0-9A-Fa-f]",cardinality:1,casing:"upper"}}),a.extendAliases({url:{definitions:{i:{validator:".",cardinality:1}},mask:"(\\http://)|(\\http\\s://)|(ftp://)|(ftp\\s://)i{+}",insertMode:!1,autoUnmask:!1},ip:{mask:"i[i[i]].i[i[i]].i[i[i]].i[i[i]]",definitions:{i:{validator:function(d,f,g,c,e){return g-1>-1&&"."!==f.buffer[g-1]?(d=f.buffer[g-1]+d,d=g-2>-1&&"."!==f.buffer[g-2]?f.buffer[g-2]+d:"0"+d):d="00"+d,new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]").test(d)},cardinality:1}},onUnMask:function(e,c,d){return e}},email:{mask:"*{1,64}[.*{1,64}][.*{1,64}][.*{1,63}]@-{1,63}[.-{1,63}][.-{1,63}][.-{1,63}]",greedy:!1,onBeforePaste:function(c,d){return c=c.toLowerCase(),c.replace("mailto:","")},definitions:{"*":{validator:"[0-9A-Za-z!#$%&'*+/=?^_`{|}~-]",cardinality:1,casing:"lower"},"-":{validator:"[0-9A-Za-z-]",cardinality:1,casing:"lower"}},onUnMask:function(e,c,d){return e}},mac:{mask:"##:##:##:##:##:##"},vin:{mask:"V{8}vV{4}9{4}",definitions:{V:{validator:"[A-HJ-NPR-Za-hj-npr-z\\d]",cardinality:1,casing:"upper"},v:{validator:"[Xx\\d]",cardinality:1,casing:"upper"}},clearIncomplete:!0,autoUnmask:!0}}),a}(jQuery,Inputmask),function(b,a){return a.extendAliases({numeric:{mask:function(e){function g(h){for(var j="",k=0;k<h.length;k++){j+=e.definitions[h.charAt(k)]?"\\"+h.charAt(k):h.charAt(k)}return j}if(0!==e.repeat&&isNaN(e.integerDigits)&&(e.integerDigits=e.repeat),e.repeat=0,e.groupSeparator===e.radixPoint&&("."===e.radixPoint?e.groupSeparator=",":","===e.radixPoint?e.groupSeparator=".":e.groupSeparator="")," "===e.groupSeparator&&(e.skipOptionalPartCharacter=void 0),e.autoGroup=e.autoGroup&&""!==e.groupSeparator,e.autoGroup&&("string"==typeof e.groupSize&&isFinite(e.groupSize)&&(e.groupSize=parseInt(e.groupSize)),isFinite(e.integerDigits))){var f=Math.floor(e.integerDigits/e.groupSize),d=e.integerDigits%e.groupSize;e.integerDigits=parseInt(e.integerDigits)+(0===d?f-1:f),e.integerDigits<1&&(e.integerDigits="*")}e.placeholder.length>1&&(e.placeholder=e.placeholder.charAt(0)),e.radixFocus=e.radixFocus&&""!==e.placeholder&&e.integerOptional===!0,e.definitions[";"]=e.definitions["~"],e.definitions[";"].definitionSymbol="~",1==e.numericInput&&(e.radixFocus=!1,e.digitsOptional=!1,isNaN(e.digits)&&(e.digits=2),e.decimalProtect=!1);var c=g(e.prefix);return c+="[+]",c+=e.integerOptional===!0?"~{1,"+e.integerDigits+"}":"~{"+e.integerDigits+"}",void 0!==e.digits&&(isNaN(e.digits)||parseInt(e.digits)>0)&&(e.decimalProtect&&(e.radixPointDefinitionSymbol=":"),c+=e.digitsOptional?"["+(e.decimalProtect?":":e.radixPoint)+";{1,"+e.digits+"}]":(e.decimalProtect?":":e.radixPoint)+";{"+e.digits+"}"),""!==e.negationSymbol.back&&(c+="[-]"),c+=g(e.suffix),e.greedy=!1,c},placeholder:"",greedy:!1,digits:"*",digitsOptional:!0,radixPoint:".",radixFocus:!0,groupSize:3,groupSeparator:"",autoGroup:!1,allowPlus:!0,allowMinus:!0,negationSymbol:{front:"-",back:""},integerDigits:"+",integerOptional:!0,prefix:"",suffix:"",rightAlign:!0,decimalProtect:!0,min:null,max:null,step:1,insertMode:!0,autoUnmask:!1,unmaskAsNumber:!1,postFormat:function(m,r,c){c.numericInput===!0&&(m=m.reverse(),isFinite(r)&&(r=m.join("").length-r-1));var n,f,s=!1;m.length>=c.suffix.length&&m.join("").indexOf(c.suffix)===m.length-c.suffix.length&&(m.length=m.length-c.suffix.length,s=!0),r=r>=m.length?m.length-1:r<c.prefix.length?c.prefix.length:r;var k=!1,p=m[r],h=m.slice();p===c.groupSeparator&&(h.splice(r--,1),p=h[r]),p!==c.radixPoint&&p!==c.negationSymbol.front&&p!==c.negationSymbol.back&&(h[r]="?");var o=h.join(""),g=o;if(o.length>0&&c.autoGroup||-1!==o.indexOf(c.groupSeparator)){var j=a.escapeRegex(c.groupSeparator);k=0===o.indexOf(c.groupSeparator),o=o.replace(new RegExp(j,"g"),"");var e=o.split(c.radixPoint);if(o=""===c.radixPoint?o:e[0],o!==c.prefix+"?0"&&o.length>=c.groupSize+c.prefix.length){for(var d=new RegExp("([-+]?[\\d?]+)([\\d?]{"+c.groupSize+"})");d.test(o)&&""!==c.groupSeparator;){o=o.replace(d,"$1"+c.groupSeparator+"$2"),o=o.replace(c.groupSeparator+c.groupSeparator,c.groupSeparator)}}""!==c.radixPoint&&e.length>1&&(o+=c.radixPoint+e[1])}for(k=g!==o,m.length=o.length,n=0,f=o.length;f>n;n++){m[n]=o.charAt(n)}var q=b.inArray("?",m);if(-1===q&&(q=b.inArray(p,m)),m[q]=p,!k&&s){for(n=0,f=c.suffix.length;f>n;n++){m.push(c.suffix.charAt(n))}}return q=c.numericInput&&isFinite(r)?m.join("").length-q-1:q,c.numericInput&&(m=m.reverse(),b.inArray(c.radixPoint,m)<q&&m.join("").length-c.suffix.length!==q&&(q-=1)),{pos:q,refreshFromBuffer:k,buffer:m}},onBeforeWrite:function(n,g,k,d){var o;if(n&&("blur"===n.type||"checkval"===n.type||"keydown"===n.type)){var c=d.numericInput?g.slice().reverse().join(""):g.join(""),p=c.replace(d.prefix,""),r=!1;p=p.replace(d.suffix,""),p=p.replace(new RegExp(a.escapeRegex(d.groupSeparator),"g"),""),","===d.radixPoint&&(p=p.replace(d.radixPoint,"."));var f=p.match(new RegExp("[-"+a.escapeRegex(d.negationSymbol.front)+"]","g"));if(f=null!==f&&1===f.length,p=p.replace(new RegExp("[-"+a.escapeRegex(d.negationSymbol.front)+"]","g"),""),p=p.replace(new RegExp(a.escapeRegex(d.negationSymbol.back)+"$"),""),p=p===d.negationSymbol.front?p+"0":p,isFinite(p)){var l=parseFloat(p),q=f?-1*l:l;if(null!==d.min&&isFinite(d.min)&&q<parseFloat(d.min)&&(l=Math.abs(d.min),f=d.min<0,r=!0),!r&&null!==d.max&&isFinite(d.max)&&q>parseFloat(d.max)&&(l=Math.abs(d.max),f=d.max<0,r=!0),p=l.toString().replace(".",d.radixPoint).split(""),isFinite(d.digits)){var j=b.inArray(d.radixPoint,p),m=b.inArray(d.radixPoint,c);-1===j&&(p.push(d.radixPoint),j=p.length-1);for(var h=1;h<=d.digits;h++){d.digitsOptional||void 0!==p[j+h]&&p[j+h]!==d.placeholder.charAt(0)?-1!==m&&void 0!==c[m+h]&&(p[j+h]=p[j+h]||c[m+h]):p[j+h]="0"}p[p.length-1]===d.radixPoint&&delete p[p.length-1]}if(l.toString()!==p&&l.toString()+"."!==p||f){return !f||0===l&&"blur"===n.type||(p.unshift(d.negationSymbol.front),p.push(d.negationSymbol.back)),p=(d.prefix+p.join("")).split(""),d.numericInput&&(p=p.reverse()),o=d.postFormat(p,d.numericInput?k:k-1,d),o.buffer&&(o.refreshFromBuffer=o.buffer.join("")!==g.join("")),o}}}return d.autoGroup?(o=d.postFormat(g,d.numericInput?k:k-1,d),o.caret=k<=d.prefix.length?o.pos:o.pos+1,o):void 0},regex:{integerPart:function(c){return new RegExp("["+a.escapeRegex(c.negationSymbol.front)+"+]?\\d+")},integerNPart:function(c){return new RegExp("[\\d"+a.escapeRegex(c.groupSeparator)+a.escapeRegex(c.placeholder.charAt(0))+"]+")}},signHandler:function(d,g,h,c,f){if(!c&&f.allowMinus&&"-"===d||f.allowPlus&&"+"===d){var e=g.buffer.join("").match(f.regex.integerPart(f));if(e&&e[0].length>0){return g.buffer[e.index]===("-"===d?"+":f.negationSymbol.front)?"-"===d?""!==f.negationSymbol.back?{pos:e.index,c:f.negationSymbol.front,remove:e.index,caret:h,insert:{pos:g.buffer.length-f.suffix.length-1,c:f.negationSymbol.back}}:{pos:e.index,c:f.negationSymbol.front,remove:e.index,caret:h}:""!==f.negationSymbol.back?{pos:e.index,c:"+",remove:[e.index,g.buffer.length-f.suffix.length-1],caret:h}:{pos:e.index,c:"+",remove:e.index,caret:h}:g.buffer[e.index]===("-"===d?f.negationSymbol.front:"+")?"-"===d&&""!==f.negationSymbol.back?{remove:[e.index,g.buffer.length-f.suffix.length-1],caret:h-1}:{remove:e.index,caret:h-1}:"-"===d?""!==f.negationSymbol.back?{pos:e.index,c:f.negationSymbol.front,caret:h+1,insert:{pos:g.buffer.length-f.suffix.length,c:f.negationSymbol.back}}:{pos:e.index,c:f.negationSymbol.front,caret:h+1}:{pos:e.index,c:d,caret:h+1}}}return !1},radixHandler:function(f,h,i,d,g){if(!d&&(-1!==b.inArray(f,[",","."])&&(f=g.radixPoint),f===g.radixPoint&&void 0!==g.digits&&(isNaN(g.digits)||parseInt(g.digits)>0))){var c=b.inArray(g.radixPoint,h.buffer),e=h.buffer.join("").match(g.regex.integerPart(g));if(-1!==c&&h.validPositions[c]){return h.validPositions[c-1]?{caret:c+1}:{pos:e.index,c:e[0],caret:c+1}}if(!e||"0"===e[0]&&e.index+1!==i){return h.buffer[e?e.index:i]="0",{pos:(e?e.index:i)+1,c:g.radixPoint}}}return !1},leadingZeroHandler:function(d,h,i,c,f){if(f.numericInput===!0){if("0"===h.buffer[h.buffer.length-f.prefix.length-1]){return{pos:i,remove:h.buffer.length-f.prefix.length-1}}}else{var g=b.inArray(f.radixPoint,h.buffer),e=h.buffer.slice(0,-1!==g?g:void 0).join("").match(f.regex.integerNPart(f));if(e&&!c&&(-1===g||g>=i)){if(0===e[0].indexOf(""!==f.placeholder?f.placeholder.charAt(0):"0")&&e.index+1===i){return h.buffer.splice(e.index,1),i=e.index,{pos:i,remove:e.index}}if("0"===d&&i<=e.index&&e[0]!==f.groupSeparator){return !1}}}return !0},definitions:{"~":{validator:function(d,h,i,c,e){var g=e.signHandler(d,h,i,c,e);if(!g&&(g=e.radixHandler(d,h,i,c,e),!g&&(g=c?new RegExp("[0-9"+a.escapeRegex(e.groupSeparator)+"]").test(d):new RegExp("[0-9]").test(d),g===!0&&(g=e.leadingZeroHandler(d,h,i,c,e),g===!0)))){var f=b.inArray(e.radixPoint,h.buffer);g=-1!==f&&(e.digitsOptional===!1||h.validPositions[i])&&e.numericInput!==!0&&i>f&&!c?{pos:i,remove:i}:{pos:i}}return g},cardinality:1,prevalidator:null},"+":{validator:function(d,g,h,c,e){var f=e.signHandler(d,g,h,c,e);return !f&&(c&&e.allowMinus&&d===e.negationSymbol.front||e.allowMinus&&"-"===d||e.allowPlus&&"+"===d)&&(f="-"===d?""!==e.negationSymbol.back?{pos:h,c:"-"===d?e.negationSymbol.front:"+",caret:h+1,insert:{pos:g.buffer.length,c:e.negationSymbol.back}}:{pos:h,c:"-"===d?e.negationSymbol.front:"+",caret:h+1}:!0),f},cardinality:1,prevalidator:null,placeholder:""},"-":{validator:function(d,g,h,c,e){var f=e.signHandler(d,g,h,c,e);return !f&&c&&e.allowMinus&&d===e.negationSymbol.back&&(f=!0),f},cardinality:1,prevalidator:null,placeholder:""},":":{validator:function(d,h,i,c,f){var g=f.signHandler(d,h,i,c,f);if(!g){var e="["+a.escapeRegex(f.radixPoint)+",\\.]";g=new RegExp(e).test(d),g&&h.validPositions[i]&&h.validPositions[i].match.placeholder===f.radixPoint&&(g={caret:i+1})}return g?{c:f.radixPoint}:g},cardinality:1,prevalidator:null,placeholder:function(c){return c.radixPoint}}},onUnMask:function(f,c,e){var d=f.replace(e.prefix,"");return d=d.replace(e.suffix,""),d=d.replace(new RegExp(a.escapeRegex(e.groupSeparator),"g"),""),e.unmaskAsNumber?(""!==e.radixPoint&&-1!==d.indexOf(e.radixPoint)&&(d=d.replace(a.escapeRegex.call(this,e.radixPoint),".")),Number(d)):d},isComplete:function(d,f){var g=d.join(""),c=d.slice();if(f.postFormat(c,0,f),c.join("")!==g){return !1}var e=g.replace(f.prefix,"");return e=e.replace(f.suffix,""),e=e.replace(new RegExp(a.escapeRegex(f.groupSeparator),"g"),""),","===f.radixPoint&&(e=e.replace(a.escapeRegex(f.radixPoint),".")),isFinite(e)},onBeforeMask:function(e,g){if(""!==g.radixPoint&&isFinite(e)){e=e.toString().replace(".",g.radixPoint)}else{var d=e.match(/,/g),i=e.match(/\./g);i&&d?i.length>d.length?(e=e.replace(/\./g,""),e=e.replace(",",g.radixPoint)):d.length>i.length?(e=e.replace(/,/g,""),e=e.replace(".",g.radixPoint)):e=e.indexOf(".")<e.indexOf(",")?e.replace(/\./g,""):e=e.replace(/,/g,""):e=e.replace(new RegExp(a.escapeRegex(g.groupSeparator),"g"),"")}if(0===g.digits&&(-1!==e.indexOf(".")?e=e.substring(0,e.indexOf(".")):-1!==e.indexOf(",")&&(e=e.substring(0,e.indexOf(",")))),""!==g.radixPoint&&isFinite(g.digits)&&-1!==e.indexOf(g.radixPoint)){var f=e.split(g.radixPoint),h=f[1].match(new RegExp("\\d*"))[0];if(parseInt(g.digits)<h.toString().length){var c=Math.pow(10,parseInt(g.digits));e=e.replace(a.escapeRegex(g.radixPoint),"."),e=Math.round(parseFloat(e)*c)/c,e=e.toString().replace(".",g.radixPoint)}}return e.toString()},canClearPosition:function(h,c,i,d,g){var f=h.validPositions[c].input,e=f!==g.radixPoint||null!==h.validPositions[c].match.fn&&g.decimalProtect===!1||isFinite(f)||c===i||f===g.groupSeparator||f===g.negationSymbol.front||f===g.negationSymbol.back;return e},onKeyDown:function(g,c,d,f){var h=b(this);if(g.ctrlKey){switch(g.keyCode){case a.keyCode.UP:h.val(parseFloat(this.inputmask.unmaskedvalue())+parseInt(f.step)),h.trigger("setvalue");break;case a.keyCode.DOWN:h.val(parseFloat(this.inputmask.unmaskedvalue())-parseInt(f.step)),h.trigger("setvalue")}}}},currency:{prefix:"$ ",groupSeparator:",",alias:"numeric",placeholder:"0",autoGroup:!0,digits:2,digitsOptional:!1,clearMaskOnLostFocus:!1},decimal:{alias:"numeric"},integer:{alias:"numeric",digits:0,radixPoint:""},percentage:{alias:"numeric",digits:2,radixPoint:".",placeholder:"0",autoGroup:!1,min:0,max:100,suffix:" %",allowPlus:!1,allowMinus:!1}}),a}(jQuery,Inputmask),function(b,a){return a.extendAliases({phone:{url:"phone-codes/phone-codes.js",countrycode:"",phoneCodeCache:{},mask:function(c){if(void 0===c.phoneCodeCache[c.url]){var d=[];c.definitions["#"]=c.definitions[9],b.ajax({url:c.url,async:!1,type:"get",dataType:"json",success:function(e){d=e},error:function(g,e,f){alert(f+" - "+c.url)}}),c.phoneCodeCache[c.url]=d.sort(function(f,e){return(f.mask||f)<(e.mask||e)?-1:1})}return c.phoneCodeCache[c.url]},keepStatic:!1,nojumps:!0,nojumpsThreshold:1,onBeforeMask:function(e,d){var c=e.replace(/^0{1,2}/,"").replace(/[\s]/g,"");return(c.indexOf(d.countrycode)>1||-1===c.indexOf(d.countrycode))&&(c="+"+d.countrycode+c),c}},phonebe:{alias:"phone",url:"phone-codes/phone-be.js",countrycode:"32",nojumpsThreshold:4}}),a}(jQuery,Inputmask),function(b,a){return a.extendAliases({Regex:{mask:"r",greedy:!1,repeat:"*",regex:null,regexTokens:null,tokenizer:/\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g,quantifierFilter:/[0-9]+[^,]/,isComplete:function(c,d){return new RegExp(d.regex).test(c.join(""))},definitions:{r:{validator:function(f,o,m,n,c){function k(t,i){this.matches=[],this.isGroup=t||!1,this.isQuantifier=i||!1,this.quantifier={min:1,max:1},this.repeaterPart=void 0}function r(){var z,v,x=new k(),A=[];for(c.regexTokens=[];z=c.tokenizer.exec(c.regex);){switch(v=z[0],v.charAt(0)){case"(":A.push(new k(!0));break;case")":j=A.pop(),A.length>0?A[A.length-1].matches.push(j):x.matches.push(j);break;case"{":case"+":case"*":var i=new k(!1,!0);v=v.replace(/[{}]/g,"");var t=v.split(","),w=isNaN(t[0])?t[0]:parseInt(t[0]),u=1===t.length?w:isNaN(t[1])?t[1]:parseInt(t[1]);if(i.quantifier={min:w,max:u},A.length>0){var y=A[A.length-1].matches;z=y.pop(),z.isGroup||(j=new k(!0),j.matches.push(z),z=j),y.push(z),y.push(i)}else{z=x.matches.pop(),z.isGroup||(j=new k(!0),j.matches.push(z),z=j),x.matches.push(z),x.matches.push(i)}break;default:A.length>0?A[A.length-1].matches.push(v):x.matches.push(v)}}x.matches.length>0&&c.regexTokens.push(x)}function p(z,u){var w=!1;u&&(s+="(",d++);for(var E=0;E<z.matches.length;E++){var F=z.matches[E];if(F.isGroup===!0){w=p(F,!0)}else{if(F.isQuantifier===!0){var x=b.inArray(F,z.matches),v=z.matches[x-1],G=s;if(isNaN(F.quantifier.max)){for(;F.repeaterPart&&F.repeaterPart!==s&&F.repeaterPart.length>s.length&&!(w=p(v,!0));){}w=w||p(v,!0),w&&(F.repeaterPart=s),s=G+F.quantifier.max}else{for(var D=0,I=F.quantifier.max-1;I>D&&!(w=p(v,!0));D++){}s=G+"{"+F.quantifier.min+","+F.quantifier.max+"}"}}else{if(void 0!==F.matches){for(var B=0;B<F.length&&!(w=p(F[B],u));B++){}}else{var t;if("["==F.charAt(0)){t=s,t+=F;for(var C=0;d>C;C++){t+=")"}var A=new RegExp("^("+t+")$");w=A.test(g)}else{for(var y=0,H=F.length;H>y;y++){if("\\"!==F.charAt(y)){t=s,t+=F.substr(0,y+1),t=t.replace(/\|$/,"");for(var C=0;d>C;C++){t+=")"}var A=new RegExp("^("+t+")$");if(w=A.test(g)){break}}}}s+=F}}}if(w){break}}return u&&(s+=")",d--),w}var g,j,e=o.buffer.slice(),s="",q=!1,d=0;null===c.regexTokens&&r(),e.splice(m,0,f),g=e.join("");for(var h=0;h<c.regexTokens.length;h++){var l=c.regexTokens[h];if(q=p(l,l.isGroup)){break}}return q},cardinality:1}}}}),a}(jQuery,Inputmask);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-inputmask-bundle-3.2.8.min.js
jquery-inputmask-bundle-3.2.8.min.js
(function(c){var b=function(e,d){this.$element=c(e);this.options=c.extend({},b.defaults,d)};b.defaults={transition_delay:300,refresh_speed:50,display_text:"none",use_percentage:true,percent_format:function(d){return d+"%"},amount_format:function(e,d){return e+" / "+d},update:c.noop,done:c.noop,fail:c.noop};b.prototype.transition=function(){var j=this.$element;var h=j.parent();var p=this.$back_text;var l=this.$front_text;var q=this.options;var i=j.attr("aria-valuetransitiongoal");var m=j.attr("aria-valuemin")||0;var d=j.attr("aria-valuemax")||100;var o=h.hasClass("vertical");var g=q.update&&typeof q.update==="function"?q.update:b.defaults.update;var f=q.done&&typeof q.done==="function"?q.done:b.defaults.done;var e=q.fail&&typeof q.fail==="function"?q.fail:b.defaults.fail;if(!i){e("aria-valuetransitiongoal not set");return}var n=Math.round(100*(i-m)/(d-m));if(q.display_text==="center"&&!p&&!l){this.$back_text=p=c("<span>").addClass("progressbar-back-text").prependTo(h);this.$front_text=l=c("<span>").addClass("progressbar-front-text").prependTo(j);var k;if(o){k=h.css("height");p.css({height:k,"line-height":k});l.css({height:k,"line-height":k});c(window).resize(function(){k=h.css("height");p.css({height:k,"line-height":k});l.css({height:k,"line-height":k})})}else{k=h.css("width");l.css({width:k});c(window).resize(function(){k=h.css("width");l.css({width:k})})}}setTimeout(function(){var v;var t;var r;var u;var w;if(o){j.css("height",n+"%")}else{j.css("width",n+"%")}var s=setInterval(function(){if(o){r=j.height();u=h.height()}else{r=j.width();u=h.width()}v=Math.round(100*r/u);t=Math.round(r/u*(d-m));if(v>=n){v=n;t=i;f();clearInterval(s)}if(q.display_text!=="none"){w=q.use_percentage?q.percent_format(v):q.amount_format(t,d);if(q.display_text==="fill"){j.text(w)}else{if(q.display_text==="center"){p.text(w);l.text(w)}}}j.attr("aria-valuenow",t);g(v)},q.refresh_speed)},q.transition_delay)};var a=c.fn.progressbar;c.fn.progressbar=function(d){return this.each(function(){var g=c(this);var f=g.data("bs.progressbar");var e=typeof d==="object"&&d;if(!f){g.data("bs.progressbar",(f=new b(this,e)))}f.transition()})};c.fn.progressbar.Constructor=b;c.fn.progressbar.noConflict=function(){c.fn.progressbar=a;return this}})(window.jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/bootstrap-progressbar-0.6.0.min.js
bootstrap-progressbar-0.6.0.min.js
var FixedHeader;(function(c,a,d){var b=function(f,e){FixedHeader=function(h,g){if(!this instanceof FixedHeader){alert("FixedHeader warning: FixedHeader must be initialised with the 'new' keyword.");return}var j=this;var k={aoCache:[],oSides:{top:true,bottom:false,left:0,right:0},oZIndexes:{top:104,bottom:103,left:102,right:101},oCloneOnDraw:{top:false,bottom:false,left:true,right:true},oMes:{iTableWidth:0,iTableHeight:0,iTableLeft:0,iTableRight:0,iTableTop:0,iTableBottom:0},oOffset:{top:0},nTable:null,bFooter:false,bInitComplete:false};this.fnGetSettings=function(){return k};this.fnUpdate=function(){this._fnUpdateClones();this._fnUpdatePositions()};this.fnPosition=function(){this._fnUpdatePositions()};var i=f.fn.dataTable.Api?new f.fn.dataTable.Api(h).settings()[0]:h.fnSettings();i._oPluginFixedHeader=this;this.fnInit(i,g)};FixedHeader.prototype={fnInit:function(j,g){var h=this.fnGetSettings();var i=this;this.fnInitSettings(h,g);if(j.oScroll.sX!==""||j.oScroll.sY!==""){alert("FixedHeader 2 is not supported with DataTables' scrolling mode at this time");return}h.nTable=j.nTable;j.aoDrawCallback.unshift({fn:function(){FixedHeader.fnMeasure();i._fnUpdateClones.call(i);i._fnUpdatePositions.call(i)},sName:"FixedHeader"});h.bFooter=(f(">tfoot",h.nTable).length>0)?true:false;if(h.oSides.top){h.aoCache.push(i._fnCloneTable("fixedHeader","FixedHeader_Header",i._fnCloneThead))}if(h.oSides.bottom){h.aoCache.push(i._fnCloneTable("fixedFooter","FixedHeader_Footer",i._fnCloneTfoot))}if(h.oSides.left){h.aoCache.push(i._fnCloneTable("fixedLeft","FixedHeader_Left",i._fnCloneTLeft,h.oSides.left))}if(h.oSides.right){h.aoCache.push(i._fnCloneTable("fixedRight","FixedHeader_Right",i._fnCloneTRight,h.oSides.right))}FixedHeader.afnScroll.push(function(){i._fnUpdatePositions.call(i)});f(c).resize(function(){FixedHeader.fnMeasure();i._fnUpdateClones.call(i);i._fnUpdatePositions.call(i)});f(h.nTable).on("column-reorder",function(){FixedHeader.fnMeasure();i._fnUpdateClones(true);i._fnUpdatePositions()}).on("column-visibility",function(){FixedHeader.fnMeasure();i._fnUpdateClones(true);i._fnUpdatePositions()});FixedHeader.fnMeasure();i._fnUpdateClones();i._fnUpdatePositions();h.bInitComplete=true},fnInitSettings:function(h,g){if(g!==d){if(g.top!==d){h.oSides.top=g.top}if(g.bottom!==d){h.oSides.bottom=g.bottom}if(typeof g.left=="boolean"){h.oSides.left=g.left?1:0}else{if(g.left!==d){h.oSides.left=g.left}}if(typeof g.right=="boolean"){h.oSides.right=g.right?1:0}else{if(g.right!==d){h.oSides.right=g.right}}if(g.zTop!==d){h.oZIndexes.top=g.zTop}if(g.zBottom!==d){h.oZIndexes.bottom=g.zBottom}if(g.zLeft!==d){h.oZIndexes.left=g.zLeft}if(g.zRight!==d){h.oZIndexes.right=g.zRight}if(g.offsetTop!==d){h.oOffset.top=g.offsetTop}if(g.alwaysCloneTop!==d){h.oCloneOnDraw.top=g.alwaysCloneTop}if(g.alwaysCloneBottom!==d){h.oCloneOnDraw.bottom=g.alwaysCloneBottom}if(g.alwaysCloneLeft!==d){h.oCloneOnDraw.left=g.alwaysCloneLeft}if(g.alwaysCloneRight!==d){h.oCloneOnDraw.right=g.alwaysCloneRight}}},_fnCloneTable:function(m,l,k,i){var h=this.fnGetSettings();var g;if(f(h.nTable.parentNode).css("position")!="absolute"){h.nTable.parentNode.style.position="relative"}g=h.nTable.cloneNode(false);g.removeAttribute("id");var j=a.createElement("div");j.style.position="absolute";j.style.top="0px";j.style.left="0px";j.className+=" FixedHeader_Cloned "+m+" "+l;if(m=="fixedHeader"){j.style.zIndex=h.oZIndexes.top}if(m=="fixedFooter"){j.style.zIndex=h.oZIndexes.bottom}if(m=="fixedLeft"){j.style.zIndex=h.oZIndexes.left}else{if(m=="fixedRight"){j.style.zIndex=h.oZIndexes.right}}g.style.margin="0";j.appendChild(g);a.body.appendChild(j);return{nNode:g,nWrapper:j,sType:m,sPosition:"",sTop:"",sLeft:"",fnClone:k,iCells:i}},_fnMeasure:function(){var j=this.fnGetSettings(),g=j.oMes,i=f(j.nTable),h=i.offset(),l=this._fnSumScroll(j.nTable.parentNode,"scrollTop"),k=this._fnSumScroll(j.nTable.parentNode,"scrollLeft");g.iTableWidth=i.outerWidth();g.iTableHeight=i.outerHeight();g.iTableLeft=h.left+j.nTable.parentNode.scrollLeft;g.iTableTop=h.top+l;g.iTableRight=g.iTableLeft+g.iTableWidth;g.iTableRight=FixedHeader.oDoc.iWidth-g.iTableLeft-g.iTableWidth;g.iTableBottom=FixedHeader.oDoc.iHeight-g.iTableTop-g.iTableHeight},_fnSumScroll:function(j,h){var g=j[h];while(j=j.parentNode){if(j.nodeName=="HTML"||j.nodeName=="BODY"){break}g=j[h]}return g},_fnUpdatePositions:function(){var j=this.fnGetSettings();this._fnMeasure();for(var h=0,g=j.aoCache.length;h<g;h++){if(j.aoCache[h].sType=="fixedHeader"){this._fnScrollFixedHeader(j.aoCache[h])}else{if(j.aoCache[h].sType=="fixedFooter"){this._fnScrollFixedFooter(j.aoCache[h])}else{if(j.aoCache[h].sType=="fixedLeft"){this._fnScrollHorizontalLeft(j.aoCache[h])}else{this._fnScrollHorizontalRight(j.aoCache[h])}}}}},_fnUpdateClones:function(j){var k=this.fnGetSettings();if(j){k.bInitComplete=false}for(var h=0,g=k.aoCache.length;h<g;h++){k.aoCache[h].fnClone.call(this,k.aoCache[h])}if(j){k.bInitComplete=true}},_fnScrollHorizontalRight:function(m){var k=this.fnGetSettings(),l=k.oMes,h=FixedHeader.oWin,g=FixedHeader.oDoc,j=m.nWrapper,i=f(j).outerWidth();if(h.iScrollRight<l.iTableRight){this._fnUpdateCache(m,"sPosition","absolute","position",j.style);this._fnUpdateCache(m,"sTop",l.iTableTop+"px","top",j.style);this._fnUpdateCache(m,"sLeft",(l.iTableLeft+l.iTableWidth-i)+"px","left",j.style)}else{if(l.iTableLeft<g.iWidth-h.iScrollRight-i){this._fnUpdateCache(m,"sPosition","fixed","position",j.style);this._fnUpdateCache(m,"sTop",(l.iTableTop-h.iScrollTop)+"px","top",j.style);this._fnUpdateCache(m,"sLeft",(h.iWidth-i)+"px","left",j.style)}else{this._fnUpdateCache(m,"sPosition","absolute","position",j.style);this._fnUpdateCache(m,"sTop",l.iTableTop+"px","top",j.style);this._fnUpdateCache(m,"sLeft",l.iTableLeft+"px","left",j.style)}}},_fnScrollHorizontalLeft:function(m){var k=this.fnGetSettings(),l=k.oMes,h=FixedHeader.oWin,g=FixedHeader.oDoc,i=m.nWrapper,j=f(i).outerWidth();if(h.iScrollLeft<l.iTableLeft){this._fnUpdateCache(m,"sPosition","absolute","position",i.style);this._fnUpdateCache(m,"sTop",l.iTableTop+"px","top",i.style);this._fnUpdateCache(m,"sLeft",l.iTableLeft+"px","left",i.style)}else{if(h.iScrollLeft<l.iTableLeft+l.iTableWidth-j){this._fnUpdateCache(m,"sPosition","fixed","position",i.style);this._fnUpdateCache(m,"sTop",(l.iTableTop-h.iScrollTop)+"px","top",i.style);this._fnUpdateCache(m,"sLeft","0px","left",i.style)}else{this._fnUpdateCache(m,"sPosition","absolute","position",i.style);this._fnUpdateCache(m,"sTop",l.iTableTop+"px","top",i.style);this._fnUpdateCache(m,"sLeft",(l.iTableLeft+l.iTableWidth-j)+"px","left",i.style)}}},_fnScrollFixedFooter:function(n){var l=this.fnGetSettings(),m=l.oMes,h=FixedHeader.oWin,g=FixedHeader.oDoc,i=n.nWrapper,k=f("thead",l.nTable).outerHeight(),j=f(i).outerHeight();if(h.iScrollBottom<m.iTableBottom){this._fnUpdateCache(n,"sPosition","absolute","position",i.style);this._fnUpdateCache(n,"sTop",(m.iTableTop+m.iTableHeight-j)+"px","top",i.style);this._fnUpdateCache(n,"sLeft",m.iTableLeft+"px","left",i.style)}else{if(h.iScrollBottom<m.iTableBottom+m.iTableHeight-j-k){this._fnUpdateCache(n,"sPosition","fixed","position",i.style);this._fnUpdateCache(n,"sTop",(h.iHeight-j)+"px","top",i.style);this._fnUpdateCache(n,"sLeft",(m.iTableLeft-h.iScrollLeft)+"px","left",i.style)}else{this._fnUpdateCache(n,"sPosition","absolute","position",i.style);this._fnUpdateCache(n,"sTop",(m.iTableTop+j)+"px","top",i.style);this._fnUpdateCache(n,"sLeft",m.iTableLeft+"px","left",i.style)}}},_fnScrollFixedHeader:function(m){var p=this.fnGetSettings(),j=p.oMes,k=FixedHeader.oWin,o=FixedHeader.oDoc,h=m.nWrapper,n=0,l=p.nTable.getElementsByTagName("tbody");for(var g=0;g<l.length;++g){n+=l[g].offsetHeight}if(j.iTableTop>k.iScrollTop+p.oOffset.top){this._fnUpdateCache(m,"sPosition","absolute","position",h.style);this._fnUpdateCache(m,"sTop",j.iTableTop+"px","top",h.style);this._fnUpdateCache(m,"sLeft",j.iTableLeft+"px","left",h.style)}else{if(k.iScrollTop+p.oOffset.top>j.iTableTop+n){this._fnUpdateCache(m,"sPosition","absolute","position",h.style);this._fnUpdateCache(m,"sTop",(j.iTableTop+n)+"px","top",h.style);this._fnUpdateCache(m,"sLeft",j.iTableLeft+"px","left",h.style)}else{this._fnUpdateCache(m,"sPosition","fixed","position",h.style);this._fnUpdateCache(m,"sTop",p.oOffset.top+"px","top",h.style);this._fnUpdateCache(m,"sLeft",(j.iTableLeft-k.iScrollLeft)+"px","left",h.style)}}},_fnUpdateCache:function(k,i,h,j,g){if(k[i]!=h){g[j]=h;k[i]=h}},_fnClassUpdate:function(i,g){var h=this;if(i.nodeName.toUpperCase()==="TR"||i.nodeName.toUpperCase()==="TH"||i.nodeName.toUpperCase()==="TD"||i.nodeName.toUpperCase()==="SPAN"){g.className=i.className}f(i).children().each(function(j){h._fnClassUpdate(f(i).children()[j],f(g).children()[j])})},_fnCloneThead:function(m){var l=this.fnGetSettings();var i=m.nNode;if(l.bInitComplete&&!l.oCloneOnDraw.top){this._fnClassUpdate(f("thead",l.nTable)[0],f("thead",i)[0]);return}var k=f(l.nTable).outerWidth();m.nWrapper.style.width=k+"px";i.style.width=k+"px";while(i.childNodes.length>0){f("thead th",i).unbind("click");i.removeChild(i.childNodes[0])}var j=f("thead",l.nTable).clone(true)[0];i.appendChild(j);var h=[];var g=[];f("thead>tr th",l.nTable).each(function(n){h.push(f(this).width())});f("thead>tr td",l.nTable).each(function(n){g.push(f(this).width())});f("thead>tr th",l.nTable).each(function(n){f("thead>tr th:eq("+n+")",i).width(h[n]);f(this).width(h[n])});f("thead>tr td",l.nTable).each(function(n){f("thead>tr td:eq("+n+")",i).width(g[n]);f(this).width(g[n])});f("th.sorting, th.sorting_desc, th.sorting_asc",i).bind("click",function(){this.blur()})},_fnCloneTfoot:function(j){var i=this.fnGetSettings();var g=j.nNode;j.nWrapper.style.width=f(i.nTable).outerWidth()+"px";while(g.childNodes.length>0){g.removeChild(g.childNodes[0])}var h=f("tfoot",i.nTable).clone(true)[0];g.appendChild(h);f("tfoot:eq(0)>tr th",i.nTable).each(function(k){f("tfoot:eq(0)>tr th:eq("+k+")",g).width(f(this).width())});f("tfoot:eq(0)>tr td",i.nTable).each(function(k){f("tfoot:eq(0)>tr td:eq("+k+")",g).width(f(this).width())})},_fnCloneTLeft:function(m){var j=this.fnGetSettings();var g=m.nNode;var l=f("tbody",j.nTable)[0];while(g.childNodes.length>0){g.removeChild(g.childNodes[0])}g.appendChild(f("thead",j.nTable).clone(true)[0]);g.appendChild(f("tbody",j.nTable).clone(true)[0]);if(j.bFooter){g.appendChild(f("tfoot",j.nTable).clone(true)[0])}var n="gt("+(m.iCells-1)+")";f("thead tr",g).each(function(i){f("th:"+n,this).remove()});f("tfoot tr",g).each(function(i){f("th:"+n,this).remove()});f("tbody tr",g).each(function(i){f("td:"+n,this).remove()});this.fnEqualiseHeights("thead",l.parentNode,g);this.fnEqualiseHeights("tbody",l.parentNode,g);this.fnEqualiseHeights("tfoot",l.parentNode,g);var k=0;for(var h=0;h<m.iCells;h++){k+=f("thead tr th:eq("+h+")",j.nTable).outerWidth()}g.style.width=k+"px";m.nWrapper.style.width=k+"px"},_fnCloneTRight:function(n){var j=this.fnGetSettings();var m=f("tbody",j.nTable)[0];var g=n.nNode;var l=f("tbody tr:eq(0) td",j.nTable).length;while(g.childNodes.length>0){g.removeChild(g.childNodes[0])}g.appendChild(f("thead",j.nTable).clone(true)[0]);g.appendChild(f("tbody",j.nTable).clone(true)[0]);if(j.bFooter){g.appendChild(f("tfoot",j.nTable).clone(true)[0])}f("thead tr th:lt("+(l-n.iCells)+")",g).remove();f("tfoot tr th:lt("+(l-n.iCells)+")",g).remove();f("tbody tr",g).each(function(i){f("td:lt("+(l-n.iCells)+")",this).remove()});this.fnEqualiseHeights("thead",m.parentNode,g);this.fnEqualiseHeights("tbody",m.parentNode,g);this.fnEqualiseHeights("tfoot",m.parentNode,g);var k=0;for(var h=0;h<n.iCells;h++){k+=f("thead tr th:eq("+(l-1-h)+")",j.nTable).outerWidth()}g.style.width=k+"px";n.nWrapper.style.width=k+"px"},fnEqualiseHeights:function(j,i,l){var k=this;var h=f(j+" tr",i);var g;f(j+" tr",l).each(function(m){g=h.eq(m).css("height");if(navigator.appName=="Microsoft Internet Explorer"){g=parseInt(g,10)+1}f(this).css("height",g);h.eq(m).css("height",g)})}};FixedHeader.oWin={iScrollTop:0,iScrollRight:0,iScrollBottom:0,iScrollLeft:0,iHeight:0,iWidth:0};FixedHeader.oDoc={iHeight:0,iWidth:0};FixedHeader.afnScroll=[];FixedHeader.fnMeasure=function(){var j=f(c),i=f(a),h=FixedHeader.oWin,g=FixedHeader.oDoc;g.iHeight=i.height();g.iWidth=i.width();h.iHeight=j.height();h.iWidth=j.width();h.iScrollTop=j.scrollTop();h.iScrollLeft=j.scrollLeft();h.iScrollRight=g.iWidth-h.iScrollLeft-h.iWidth;h.iScrollBottom=g.iHeight-h.iScrollTop-h.iHeight};FixedHeader.version="2.1.0";f(c).scroll(function(){FixedHeader.fnMeasure();for(var h=0,g=FixedHeader.afnScroll.length;h<g;h++){FixedHeader.afnScroll[h]()}});f.fn.dataTable.FixedHeader=FixedHeader;f.fn.DataTable.FixedHeader=FixedHeader;return FixedHeader};b(jQuery,jQuery.fn.dataTable)})(window,document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-fixedHeader.min.js
jquery-dataTables-fixedHeader.min.js
(function(c,a,d){var b=function(g,f){var e=function(i,h){if(!this.CLASS||this.CLASS!="ColVis"){alert("Warning: ColVis must be initialised with the keyword 'new'")}if(typeof h=="undefined"){h={}}if(g.fn.dataTable.camelToHungarian){g.fn.dataTable.camelToHungarian(e.defaults,h)}this.s={dt:null,oInit:h,hidden:true,abOriginal:[]};this.dom={wrapper:null,button:null,collection:null,background:null,catcher:null,buttons:[],groupButtons:[],restore:null};e.aInstances.push(this);this.s.dt=g.fn.dataTable.Api?new g.fn.dataTable.Api(i).settings()[0]:i;this._fnConstruct(h);return this};e.prototype={button:function(){return this.dom.wrapper},fnRebuild:function(){this.rebuild()},rebuild:function(){for(var h=this.dom.buttons.length-1;h>=0;h--){this.dom.collection.removeChild(this.dom.buttons[h])}this.dom.buttons.splice(0,this.dom.buttons.length);if(this.dom.restore){this.dom.restore.parentNode(this.dom.restore)}this._fnAddGroups();this._fnAddButtons();this._fnDrawCallback()},_fnConstruct:function(l){this._fnApplyCustomisation(l);var k=this;var j,h;this.dom.wrapper=a.createElement("div");this.dom.wrapper.className="ColVis";this.dom.button=g("<button />",{"class":!this.s.dt.bJUI?"ColVis_Button ColVis_MasterButton":"ColVis_Button ColVis_MasterButton ui-button ui-state-default"}).append("<span>"+this.s.buttonText+"</span>").bind(this.s.activate=="mouseover"?"mouseover":"click",function(i){i.preventDefault();k._fnCollectionShow()}).appendTo(this.dom.wrapper)[0];this.dom.catcher=this._fnDomCatcher();this.dom.collection=this._fnDomCollection();this.dom.background=this._fnDomBackground();this._fnAddGroups();this._fnAddButtons();for(j=0,h=this.s.dt.aoColumns.length;j<h;j++){this.s.abOriginal.push(this.s.dt.aoColumns[j].bVisible)}this.s.dt.aoDrawCallback.push({fn:function(){k._fnDrawCallback.call(k)},sName:"ColVis"});g(this.s.dt.oInstance).bind("column-reorder",function(o,n,m){for(j=0,h=k.s.aiExclude.length;j<h;j++){k.s.aiExclude[j]=m.aiInvertMapping[k.s.aiExclude[j]]}var i=k.s.abOriginal.splice(m.iFrom,1)[0];k.s.abOriginal.splice(m.iTo,0,i);k.fnRebuild()});this._fnDrawCallback()},_fnApplyCustomisation:function(m){g.extend(true,this.s,e.defaults,m);if(!this.s.showAll&&this.s.bShowAll){this.s.showAll=this.s.sShowAll}if(!this.s.restore&&this.s.bRestore){this.s.restore=this.s.sRestore}var h=this.s.groups;var l=this.s.aoGroups;if(h){for(var k=0,j=h.length;k<j;k++){if(h[k].title){l[k].sTitle=h[k].title}if(h[k].columns){l[k].aiColumns=h[k].columns}}}},_fnDrawCallback:function(){var k=this.s.dt.aoColumns;var o=this.dom.buttons;var h=this.s.aoGroups;var n;for(var m=0,r=o.length;m<r;m++){n=o[m];if(n.__columnIdx!==d){g("input",n).prop("checked",k[n.__columnIdx].bVisible)}}var q=function(t){for(var i=0,j=t.length;i<j;i++){if(k[t[i]].bVisible===false){return false}}return true};var p=function(j){for(var i=0,t=j.length;i<t;i++){if(k[j[i]].bVisible===true){return false}}return true};for(var l=0,s=h.length;l<s;l++){if(q(h[l].aiColumns)){g("input",this.dom.groupButtons[l]).prop("checked",true);g("input",this.dom.groupButtons[l]).prop("indeterminate",false)}else{if(p(h[l].aiColumns)){g("input",this.dom.groupButtons[l]).prop("checked",false);g("input",this.dom.groupButtons[l]).prop("indeterminate",false)}else{g("input",this.dom.groupButtons[l]).prop("indeterminate",true)}}}},_fnAddGroups:function(){var k;if(typeof this.s.aoGroups!="undefined"){for(var j=0,h=this.s.aoGroups.length;j<h;j++){k=this._fnDomGroupButton(j);this.dom.groupButtons.push(k);this.dom.buttons.push(k);this.dom.collection.appendChild(k)}}},_fnAddButtons:function(){var l,k=this.s.dt.aoColumns;if(g.inArray("all",this.s.aiExclude)===-1){for(var j=0,h=k.length;j<h;j++){if(g.inArray(j,this.s.aiExclude)===-1){l=this._fnDomColumnButton(j);l.__columnIdx=j;this.dom.buttons.push(l)}}}if(this.s.order==="alpha"){this.dom.buttons.sort(function(m,i){var o=k[m.__columnIdx].sTitle;var n=k[i.__columnIdx].sTitle;return o===n?0:o<n?-1:1})}if(this.s.restore){l=this._fnDomRestoreButton();l.className+=" ColVis_Restore";this.dom.buttons.push(l)}if(this.s.showAll){l=this._fnDomShowAllButton();l.className+=" ColVis_ShowAll";this.dom.buttons.push(l)}g(this.dom.collection).append(this.dom.buttons)},_fnDomRestoreButton:function(){var i=this,h=this.s.dt;return g('<li class="ColVis_Special '+(h.bJUI?"ui-button ui-state-default":"")+'">'+this.s.restore+"</li>").click(function(l){for(var k=0,j=i.s.abOriginal.length;k<j;k++){i.s.dt.oInstance.fnSetColumnVis(k,i.s.abOriginal[k],false)}i._fnAdjustOpenRows();i.s.dt.oInstance.fnAdjustColumnSizing(false);i.s.dt.oInstance.fnDraw(false)})[0]},_fnDomShowAllButton:function(){var i=this,h=this.s.dt;return g('<li class="ColVis_Special '+(h.bJUI?"ui-button ui-state-default":"")+'">'+this.s.showAll+"</li>").click(function(l){for(var k=0,j=i.s.abOriginal.length;k<j;k++){if(i.s.aiExclude.indexOf(k)===-1){i.s.dt.oInstance.fnSetColumnVis(k,true,false)}}i._fnAdjustOpenRows();i.s.dt.oInstance.fnAdjustColumnSizing(false);i.s.dt.oInstance.fnDraw(false)})[0]},_fnDomGroupButton:function(j){var l=this,k=this.s.dt,h=this.s.aoGroups[j];return g('<li class="ColVis_Special '+(k.bJUI?"ui-button ui-state-default":"")+'"><label><input type="checkbox" /><span>'+h.sTitle+"</span></label></li>").click(function(m){var n=!g("input",this).is(":checked");if(m.target.nodeName.toLowerCase()!=="li"){n=!n}for(var i=0;i<h.aiColumns.length;i++){l.s.dt.oInstance.fnSetColumnVis(h.aiColumns[i],n)}})[0]},_fnDomColumnButton:function(h){var l=this,j=this.s.dt.aoColumns[h],k=this.s.dt;var m=this.s.fnLabel===null?j.sTitle:this.s.fnLabel(h,j.sTitle,j.nTh);return g("<li "+(k.bJUI?'class="ui-button ui-state-default"':"")+'><label><input type="checkbox" /><span>'+m+"</span></label></li>").click(function(i){var n=!g("input",this).is(":checked");if(i.target.nodeName.toLowerCase()!=="li"){n=!n}var o=g.fn.dataTableExt.iApiIndex;g.fn.dataTableExt.iApiIndex=l._fnDataTablesApiIndex.call(l);if(k.oFeatures.bServerSide){l.s.dt.oInstance.fnSetColumnVis(h,n,false);l.s.dt.oInstance.fnAdjustColumnSizing(false);if(k.oScroll.sX!==""||k.oScroll.sY!==""){l.s.dt.oInstance.oApi._fnScrollDraw(l.s.dt)}l._fnDrawCallback()}else{l.s.dt.oInstance.fnSetColumnVis(h,n)}g.fn.dataTableExt.iApiIndex=o;if(l.s.fnStateChange!==null){l.s.fnStateChange.call(l,h,n)}})[0]},_fnDataTablesApiIndex:function(){for(var j=0,h=this.s.dt.oInstance.length;j<h;j++){if(this.s.dt.oInstance[j]==this.s.dt.nTable){return j}}return 0},_fnDomCollection:function(){var h=this;return g("<ul />",{"class":!h.s.dt.bJUI?"ColVis_collection":"ColVis_collection ui-buttonset ui-buttonset-multi"}).css({display:"none",opacity:0,position:!h.s.bCssPosition?"absolute":""})[0]},_fnDomCatcher:function(){var i=this,h=a.createElement("div");h.className="ColVis_catcher";g(h).click(function(){i._fnCollectionHide.call(i,null,null)});return h},_fnDomBackground:function(){var i=this;var h=g("<div></div>").addClass("ColVis_collectionBackground").css("opacity",0).click(function(){i._fnCollectionHide.call(i,null,null)});if(this.s.activate=="mouseover"){h.mouseover(function(){i.s.overcollection=false;i._fnCollectionHide.call(i,null,null)})}return h[0]},_fnCollectionShow:function(){var q=this,o,m,p;var s=g(this.dom.button).offset();var n=this.dom.collection;var k=this.dom.background;var j=parseInt(s.left,10);var h=parseInt(s.top+g(this.dom.button).outerHeight(),10);if(!this.s.bCssPosition){n.style.top=h+"px";n.style.left=j+"px"}g(n).css({display:"block",opacity:0});a.body.appendChild(k);a.body.appendChild(n);a.body.appendChild(this.dom.catcher);g(n).animate({opacity:1},q.s.iOverlayFade);g(k).animate({opacity:0.1},q.s.iOverlayFade,"linear",function(){if(g.browser&&g.browser.msie&&g.browser.version=="6.0"){q._fnDrawCallback()}});if(!this.s.bCssPosition){p=(this.s.sAlign=="left")?j:j-g(n).outerWidth()+g(this.dom.button).outerWidth();n.style.left=p+"px";var l=g(n).outerWidth();var t=g(n).outerHeight();var r=g(a).width();if(p+l>r){n.style.left=(r-l)+"px"}}this.s.hidden=false},_fnCollectionHide:function(){var h=this;if(!this.s.hidden&&this.dom.collection!==null){this.s.hidden=true;g(this.dom.collection).animate({opacity:0},h.s.iOverlayFade,function(i){this.style.display="none"});g(this.dom.background).animate({opacity:0},h.s.iOverlayFade,function(i){a.body.removeChild(h.dom.background);a.body.removeChild(h.dom.catcher)})}},_fnAdjustOpenRows:function(){var l=this.s.dt.aoOpenRows;var j=this.s.dt.oApi._fnVisbleColumns(this.s.dt);for(var k=0,h=l.length;k<h;k++){l[k].nTr.getElementsByTagName("td")[0].colSpan=j}}};e.fnRebuild=function(j){var k=null;if(typeof j!="undefined"){k=j.fnSettings().nTable}for(var l=0,h=e.aInstances.length;l<h;l++){if(typeof j=="undefined"||k==e.aInstances[l].s.dt.nTable){e.aInstances[l].fnRebuild()}}};e.defaults={active:"click",buttonText:"Show / hide columns",aiExclude:[],bRestore:false,sRestore:"Restore original",bShowAll:false,sShowAll:"Show All",sAlign:"left",fnStateChange:null,iOverlayFade:500,fnLabel:null,bCssPosition:false,aoGroups:[],order:"column"};e.aInstances=[];e.prototype.CLASS="ColVis";e.VERSION="1.1.0";e.prototype.VERSION=e.VERSION;if(typeof g.fn.dataTable=="function"&&typeof g.fn.dataTableExt.fnVersionCheck=="function"&&g.fn.dataTableExt.fnVersionCheck("1.7.0")){g.fn.dataTableExt.aoFeatures.push({fnInit:function(j){var h=j.oInit;var i=new e(j,h.colVis||h.oColVis||{});return i.button()},cFeature:"C",sFeature:"ColVis"})}else{alert("Warning: ColVis requires DataTables 1.7 or greater - www.datatables.net/download")}g.fn.dataTable.ColVis=e;g.fn.DataTable.ColVis=e;return e};b(jQuery,jQuery.fn.dataTable)})(window,document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-colVis.min.js
jquery-dataTables-colVis.min.js
(function(a){a.fn.columnFilter=function(d){var b,w,m,h;var z="From {from} to {to}";var c=new Array();var g=new Array();var x=null;var v=function(){};function A(B,E,H,K,I){if(typeof E=="undefined"){return new Array()}if(typeof H=="undefined"){H=true}if(typeof K=="undefined"){K=true}if(typeof I=="undefined"){I=true}var M;if(K==true){M=B.aiDisplay}else{M=B.aiDisplayMaster}var L=new Array();for(var D=0,G=M.length;D<G;D++){var F=M[D];var C=t.fnGetData(F);var J=C[E];if(I==true&&J.length==0){continue}else{if(H==true&&jQuery.inArray(J,L)>-1){continue}else{L.push(J)}}}return L.sort()}function u(i){if(l.bUseColVis){return i}else{return t.fnSettings().oApi._fnVisibleToColumnIndex(t.fnSettings(),i)}}function o(J,I,K,B,F,L){var C="text_filter";if(B){C="number_filter"}m=m.replace(/(^\s*)|(\s*$)/g,"");var D=J.fnSettings().aoPreSearchCols[w].sSearch;var i="search_init ";var E=m;if(D!=""&&D!="^"){if(B&&D.charAt(0)=="^"){E=D.substr(1)}else{E=D}i=""}var H=a('<input type="text" class="'+i+C+'" value="'+E+'" rel="'+w+'"/>');if(L!=undefined&&L!=-1){H.attr("maxlength",L)}h.html(H);if(B){h.wrapInner('<span class="filter_column filter_number" />')}else{h.wrapInner('<span class="filter_column filter_text" />')}b[w]=m;var G=w;if(B&&!J.fnSettings().oFeatures.bServerSide){H.keyup(function(){J.fnFilter("^"+this.value,u(G),true,false);v()})}else{H.keyup(function(){if(J.fnSettings().oFeatures.bServerSide&&F!=0){var M=J.fnSettings().aoPreSearchCols[G].sSearch;var N=a(this).data("dt-iLastFilterLength");if(typeof N=="undefined"){N=0}var O=this.value.length;if(Math.abs(O-N)<F){return}else{a(this).data("dt-iLastFilterLength",O)}}J.fnFilter(this.value,u(G),I,K);v()})}H.focus(function(){if(a(this).hasClass("search_init")){a(this).removeClass("search_init");this.value=""}});H.blur(function(){if(this.value==""){a(this).addClass("search_init");this.value=b[G]}})}function f(i){h.html(p(0));var D=i.attr("id")+"_range_from_"+w;var F=a('<input type="text" class="number_range_filter" id="'+D+'" rel="'+w+'"/>');h.append(F);h.append(p(1));var C=i.attr("id")+"_range_to_"+w;var E=a('<input type="text" class="number_range_filter" id="'+C+'" rel="'+w+'"/>');h.append(E);h.append(p(2));h.wrapInner('<span class="filter_column filter_number_range" />');var B=w;g.push(w);i.dataTableExt.afnFiltering.push(function(K,I,H){if(i.attr("id")!=K.sTableId){return true}if(document.getElementById(D)==null){return true}var J=document.getElementById(D).value*1;var G=document.getElementById(C).value*1;var L=I[u(B)]=="-"?0:I[u(B)]*1;if(J==""&&G==""){return true}else{if(J==""&&L<=G){return true}else{if(J<=L&&""==G){return true}else{if(J<=L&&L<=G){return true}}}}return false});a("#"+D+",#"+C,h).keyup(function(){var H=document.getElementById(D).value*1;var G=document.getElementById(C).value*1;if(H!=0&&G!=0&&H>G){return}i.fnDraw();v()})}function q(i){var C=z.split(/[}{]/);h.html("");var E=i.attr("id")+"_range_from_"+w;var G=a('<input type="text" class="date_range_filter" id="'+E+'" rel="'+w+'"/>');G.datepicker();var D=i.attr("id")+"_range_to_"+w;var F=a('<input type="text" class="date_range_filter" id="'+D+'" rel="'+w+'"/>');for(ti=0;ti<C.length;ti++){if(C[ti]==l.sDateFromToken){h.append(G)}else{if(C[ti]==l.sDateToToken){h.append(F)}else{h.append(C[ti])}}}h.wrapInner('<span class="filter_column filter_date_range" />');F.datepicker();var B=w;g.push(w);i.dataTableExt.afnFiltering.push(function(N,K,J){if(i.attr("id")!=N.sTableId){return true}var I=G.datepicker("getDate");var H=F.datepicker("getDate");if(I==null&&H==null){return true}var M=null;try{if(K[u(B)]==null||K[u(B)]==""){return false}M=a.datepicker.parseDate(a.datepicker.regional[""].dateFormat,K[u(B)])}catch(L){return false}if(M==null){return false}if(I==null&&M<=H){return true}else{if(I<=M&&H==null){return true}else{if(I<=M&&M<=H){return true}}}return false});a("#"+E+",#"+D,h).change(function(){i.fnDraw();v()})}function r(M,E,I,B,N,K,D){if(E==null){E=A(M.fnSettings(),I,true,false,true)}var J=I;var H=M.fnSettings().aoPreSearchCols[w].sSearch;if(H==null||H==""){H=D}var i='<select class="search_init select_filter" rel="'+w+'"><option value="" class="search_init">'+N+"</option>";var G=0;var C=E.length;for(G=0;G<C;G++){if(typeof(E[G])!="object"){var F="";if(escape(E[G])==H||escape(E[G])==escape(H)){F="selected "}i+="<option "+F+' value="'+escape(E[G])+'">'+E[G]+"</option>"}else{var F="";if(K){if(E[G].value==H){F="selected "}i+="<option "+F+'value="'+E[G].value+'">'+E[G].label+"</option>"}else{if(escape(E[G].value)==H){F="selected "}i+="<option "+F+'value="'+escape(E[G].value)+'">'+E[G].label+"</option>"}}}var L=a(i+"</select>");B.html(L);B.wrapInner('<span class="filter_column filter_select" />');L.change(function(){if(a(this).val()!=""){a(this).removeClass("search_init")}else{a(this).addClass("search_init")}if(K){M.fnFilter(a(this).val(),I,K)}else{M.fnFilter(unescape(a(this).val()),I)}v()});if(H!=null&&H!=""){M.fnFilter(unescape(H),I)}}function e(i,B,C,E){var D=i.fnSettings();if(B==null&&D.sAjaxSource!=""&&!D.oFeatures.bServerSide){D.aoDrawCallback.push({fn:(function(F,H,G){return function(){if(D.iDraw==2&&D.sAjaxSource!=null&&D.sAjaxSource!=""&&!D.oFeatures.bServerSide){return r(i,null,u(F),H,G,C,E)}}})(w,h,m),sName:"column_filter_"+w})}r(i,B,u(w),h,m,C,E)}function y(E){var D=w;var F='<div class="dropdown select_filter"><a class="dropdown-toggle" data-toggle="dropdown" href="#">'+m+'<b class="caret"></b></a><ul class="dropdown-menu" role="menu"><li data-value=""><a>Show All</a></li>',C,B=E.length;for(C=0;C<B;C++){F+='<li data-value="'+E[C]+'"><a>'+E[C]+"</a></li>"}var i=a(F+"</ul></div>");h.html(i);h.wrapInner('<span class="filterColumn filter_select" />');i.find("li").click(function(){t.fnFilter(a(this).data("value"),D)})}function s(P,B){if(B==null){B=A(P.fnSettings(),w,true,true,true)}var G=w;var M="",R,Q=B.length;var D=m.replace("%","Perc").replace("&","AND").replace("$","DOL").replace("£","STERL").replace("@","AT").replace(/\s/g,"_");D=D.replace(/[^a-zA-Z 0-9]+/g,"");var N=m;if(l.sFilterButtonText!=null||l.sFilterButtonText!=undefined){N=l.sFilterButtonText}var T=10;var K=12;var J=Math.floor(Q/K);if(Q%K>0){J=J+1}var C=100/J-2;var H=T*J;if(J==1){C=20}var U='<div style="float:left; min-width: '+C+'%; " >';var V="</div>";var I=P.attr("id")+D;var F="chkBtnOpen"+I;var E=I+"-flt-toggle";M+='<button id="'+F+'" class="checkbox_filter" > '+N+"</button>";M+='<div id="'+E+'" title="'+m+'" rel="'+w+'" class="toggle-check ui-widget-content ui-corner-all" style="width: '+(H)+'%; " >';M+=U;for(R=0;R<Q;R++){if(R%K==0&&R!=0){M+=V+U}var S=B[R];var i=B[R];if(typeof(B[R])=="object"){S=B[R].label;i=B[R].value}M+='<input class="search_init checkbox_filter" type="checkbox" id= "'+I+"_cb_"+i+'" name= "'+D+'" value="'+i+'" >'+S+"<br/>";var L=a(M);h.html(L);h.wrapInner('<span class="filter_column filter_checkbox" />');L.change(function(){var X="";var Y="|";var W=a('input:checkbox[name="'+D+'"]:checked').size();a('input:checkbox[name="'+D+'"]:checked').each(function(Z){if((Z==0&&W==1)||(Z!=0&&Z==W-1)){Y=""}X=X.replace(/^\s+|\s+$/g,"");X=X+a(this).val()+Y;Y="|"});if(X!=""){a('input:checkbox[name="'+D+'"]').removeClass("search_init")}else{a('input:checkbox[name="'+D+'"]').addClass("search_init")}P.fnFilter(X,G,true,false);v()})}a("#"+F).button();a("#"+E).dialog({autoOpen:false,hide:"blind",buttons:[{text:"Reset",click:function(){a('input:checkbox[name="'+D+'"]:checked').each(function(W){a(this).attr("checked",false);a(this).addClass("search_init")});P.fnFilter("",G,true,false);v();return false}},{text:"Close",click:function(){a(this).dialog("close")}}]});a("#"+F).click(function(){a("#"+E).dialog("open");var W=a(this);a("#"+E).dialog("widget").position({my:"top",at:"bottom",of:W});return false});var O=v;v=function(){var W=a("#"+F);a("#"+E).dialog("widget").position({my:"top",at:"bottom",of:W});O()}}function p(i){switch(i){case 0:return z.substring(0,z.indexOf("{from}"));case 1:return z.substring(z.indexOf("{from}")+6,z.indexOf("{to}"));default:return z.substring(z.indexOf("{to}")+4)}}var t=this;var n={sPlaceHolder:"foot",sRangeSeparator:"~",iFilteringDelay:500,aoColumns:null,sRangeFormat:"From {from} to {to}",sDateFromToken:"from",sDateToToken:"to"};var l=a.extend(n,d);return this.each(function(){if(!t.fnSettings().oFeatures.bFilter){return}b=new Array();var E=t.fnSettings().aoFooter[0];var F=t.fnSettings().nTFoot;var C="tr";if(l.sPlaceHolder=="head:after"){var D=a("tr:first",t.fnSettings().nTHead).detach();if(t.fnSettings().bSortCellsTop){D.prependTo(a(t.fnSettings().nTHead));E=t.fnSettings().aoHeader[1]}else{D.appendTo(a(t.fnSettings().nTHead));E=t.fnSettings().aoHeader[0]}C="tr:last";F=t.fnSettings().nTHead}else{if(l.sPlaceHolder=="head:before"){if(t.fnSettings().bSortCellsTop){var D=a("tr:first",t.fnSettings().nTHead).detach();D.appendTo(a(t.fnSettings().nTHead));E=t.fnSettings().aoHeader[1]}else{E=t.fnSettings().aoHeader[0]}C="tr:first";F=t.fnSettings().nTHead}}a(E).each(function(G){w=G;var H={type:"text",bRegex:false,bSmart:true,iMaxLenght:-1,iFilterLength:0};if(l.aoColumns!=null){if(l.aoColumns.length<w||l.aoColumns[w]==null){return}H=l.aoColumns[w]}m=a(a(this)[0].cell).text();if(H.sSelector==null){h=a(a(this)[0].cell)}else{h=a(H.sSelector);if(h.length==0){h=a(a(this)[0].cell)}}if(H!=null){if(H.sRangeFormat!=null){z=H.sRangeFormat}else{z=l.sRangeFormat}switch(H.type){case"null":break;case"number":o(t,true,false,true,H.iFilterLength,H.iMaxLenght);break;case"select":if(H.bRegex!=true){H.bRegex=false}e(t,H.values,H.bRegex,H.selected);break;case"number-range":f(t);break;case"date-range":q(t);break;case"checkbox":s(t,H.values);break;case"twitter-dropdown":case"dropdown":y(H.values);break;case"text":default:bRegex=(H.bRegex==null?false:H.bRegex);bSmart=(H.bSmart==null?false:H.bSmart);o(t,bRegex,bSmart,false,H.iFilterLength,H.iMaxLenght);break}}});for(j=0;j<g.length;j++){var B=function(){var G=t.attr("id");return a("#"+G+"_range_from_"+g[j]).val()+l.sRangeSeparator+a("#"+G+"_range_to_"+g[j]).val()};c.push(B)}if(t.fnSettings().oFeatures.bServerSide){var i=t.fnSettings().fnServerData;t.fnSettings().fnServerData=function(G,I,K){for(j=0;j<g.length;j++){var H=g[j];for(k=0;k<I.length;k++){if(I[k].name=="sSearch_"+H){I[k].value=c[j]()}}}I.push({name:"sRangeSeparator",value:l.sRangeSeparator});if(i!=null){try{i(G,I,K,t.fnSettings())}catch(J){i(G,I,K)}}else{a.getJSON(G,I,function(L){K(L)})}}}})}})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-columnFilter.min.js
jquery-dataTables-columnFilter.min.js
(function(c){var a=c.scrollTo=function(e,d,f){return c(window).scrollTo(e,d,f)};a.defaults={axis:"xy",duration:parseFloat(c.fn.jquery)>=1.3?0:1,limit:true};a.window=function(d){return c(window)._scrollable()};c.fn._scrollable=function(){return this.map(function(){var e=this,f=!e.nodeName||c.inArray(e.nodeName.toLowerCase(),["iframe","#document","html","body"])!=-1;if(!f){return e}var d=(e.contentWindow||e).document||e.ownerDocument||e;return/webkit/i.test(navigator.userAgent)||d.compatMode=="BackCompat"?d.body:d.documentElement})};c.fn.scrollTo=function(i,e,d){if(typeof e=="object"){d=e;e=0}if(typeof d=="function"){d={onAfter:d}}if(i=="max"){i=9000000000}d=c.extend({},a.defaults,d);e=e||d.duration;d.queue=d.queue&&d.axis.length>1;if(d.queue){e/=2}d.offset=b(d.offset);d.over=b(d.over);return this._scrollable().each(function(){if(i==null){return}var n=this,j=c(n),k=i,h,f={},m=j.is("html,body");switch(typeof k){case"number":case"string":if(/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(k)){k=b(k);break}k=c(k,this);if(!k.length){return}case"object":if(k.is||k.style){h=(k=c(k)).offset()}}var l=c.isFunction(d.offset)&&d.offset(n,k)||d.offset;c.each(d.axis.split(""),function(t,r){var p=r=="x"?"Left":"Top",v=p.toLowerCase(),s="scroll"+p,q=n[s],o=a.max(n,r);if(h){f[s]=h[v]+(m?0:q-j.offset()[v]);if(d.margin){f[s]-=parseInt(k.css("margin"+p))||0;f[s]-=parseInt(k.css("border"+p+"Width"))||0}f[s]+=l[v]||0;if(d.over[v]){f[s]+=k[r=="x"?"width":"height"]()*d.over[v]}}else{var u=k[v];f[s]=u.slice&&u.slice(-1)=="%"?parseFloat(u)/100*o:u}if(d.limit&&/^\d+$/.test(f[s])){f[s]=f[s]<=0?0:Math.min(f[s],o)}if(!t&&d.queue){if(q!=f[s]){g(d.onAfterFirst)}delete f[s]}});g(d.onAfter);function g(o){j.animate(f,e,d.easing,o&&function(){o.call(this,k,d)})}}).end()};a.max=function(h,g){var k=g=="x"?"Width":"Height",f="scroll"+k;if(!c(h).is("html,body")){return h[f]-c(h)[k.toLowerCase()]()}var j="client"+k,i=h.ownerDocument.documentElement,e=h.ownerDocument.body;return Math.max(i[f],e[f])-Math.min(i[j],e[j])};function b(d){return c.isFunction(d)||typeof d=="object"?d:{top:d,left:d}}return a})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-scrollTo.min.js
jquery-scrollTo.min.js
!function(e,t,i,n){"use strict";var o=i("html"),a=i(e),r=i(t),s=i.fancybox=function(){s.open.apply(this,arguments)},l=navigator.userAgent.match(/msie/i),c=null,d=void 0!==t.createTouch,p=function(e){return e&&e.hasOwnProperty&&e instanceof i},h=function(e){return e&&"string"===i.type(e)},f=function(e){return h(e)&&e.indexOf("%")>0},u=function(e){return e&&!(e.style.overflow&&"hidden"===e.style.overflow)&&(e.clientWidth&&e.scrollWidth>e.clientWidth||e.clientHeight&&e.scrollHeight>e.clientHeight)},g=function(e,t){var i=parseInt(e,10)||0;return t&&f(e)&&(i=s.getViewport()[t]/100*i),Math.ceil(i)},m=function(e,t){return g(e,t)+"px"};i.extend(s,{version:"2.1.5",defaults:{padding:15,margin:20,width:800,height:600,minWidth:100,minHeight:100,maxWidth:9999,maxHeight:9999,pixelRatio:1,autoSize:!0,autoHeight:!1,autoWidth:!1,autoResize:!0,autoCenter:!d,fitToView:!0,aspectRatio:!1,topRatio:.5,leftRatio:.5,scrolling:"auto",wrapCSS:"",arrows:!0,closeBtn:!0,closeClick:!1,nextClick:!1,mouseWheel:!0,autoPlay:!1,playSpeed:3e3,preload:3,modal:!1,loop:!0,ajax:{dataType:"html",headers:{"X-fancyBox":!0}},iframe:{scrolling:"auto",preload:!0},swf:{wmode:"transparent",allowfullscreen:"true",allowscriptaccess:"always"},keys:{next:{13:"left",34:"up",39:"left",40:"up"},prev:{8:"right",33:"down",37:"right",38:"down"},close:[27],play:[32],toggle:[70]},direction:{next:"left",prev:"right"},scrollOutside:!0,index:0,type:null,href:null,content:null,title:null,tpl:{wrap:'<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>',image:'<img class="fancybox-image" src="{href}" alt="" />',iframe:'<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen'+(l?' allowtransparency="true"':"")+"></iframe>",error:'<p class="fancybox-error">'+(MyAMS.plugins.i18n.fancybox.ERROR||"The requested content cannot be loaded.")+"<br/>"+(MyAMS.plugins.i18n.fancybox.RETRY||"Please try again later.")+"</p>",closeBtn:'<a title="'+(MyAMS.plugins.i18n.fancybox.CLOSE||"Close")+'" class="fancybox-item fancybox-close" href="javascript:;"></a>',next:'<a title="'+(MyAMS.plugins.i18n.fancybox.NEXT||"Next")+'" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>',prev:'<a title="'+(MyAMS.plugins.i18n.fancybox.PREVIOUS||"Previous")+'" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>'},openEffect:"fade",openSpeed:250,openEasing:"swing",openOpacity:!0,openMethod:"zoomIn",closeEffect:"fade",closeSpeed:250,closeEasing:"swing",closeOpacity:!0,closeMethod:"zoomOut",nextEffect:"elastic",nextSpeed:250,nextEasing:"swing",nextMethod:"changeIn",prevEffect:"elastic",prevSpeed:250,prevEasing:"swing",prevMethod:"changeOut",helpers:{overlay:!0,title:!0},onCancel:i.noop,beforeLoad:i.noop,afterLoad:i.noop,beforeShow:i.noop,afterShow:i.noop,beforeChange:i.noop,beforeClose:i.noop,afterClose:i.noop},group:{},opts:{},previous:null,coming:null,current:null,isActive:!1,isOpen:!1,isOpened:!1,wrap:null,skin:null,outer:null,inner:null,player:{timer:null,isActive:!1},ajaxLoad:null,imgPreload:null,transitions:{},helpers:{},open:function(e,t){if(e&&(i.isPlainObject(t)||(t={}),!1!==s.close(!0)))return i.isArray(e)||(e=p(e)?i(e).get():[e]),i.each(e,function(n,o){var a,r,l,c,d,f,u,g={};"object"===i.type(o)&&(o.nodeType&&(o=i(o)),p(o)?(g={href:o.data("fancybox-href")||o.attr("href"),title:o.data("fancybox-title")||o.attr("title"),isDom:!0,element:o},i.metadata&&i.extend(!0,g,o.metadata())):g=o),a=t.href||g.href||(h(o)?o:null),r=void 0!==t.title?t.title:g.title||"",!(c=(l=t.content||g.content)?"html":t.type||g.type)&&g.isDom&&((c=o.data("fancybox-type"))||(c=(d=o.prop("class").match(/fancybox\.(\w+)/))?d[1]:null)),h(a)&&(c||(s.isImage(a)?c="image":s.isSWF(a)?c="swf":"#"===a.charAt(0)?c="inline":h(o)&&(c="html",l=o)),"ajax"===c&&(a=(f=a.split(/\s+/,2)).shift(),u=f.shift())),l||("inline"===c?a?l=i(h(a)?a.replace(/.*(?=#[^\s]+$)/,""):a):g.isDom&&(l=o):"html"===c?l=a:c||a||!g.isDom||(c="inline",l=o)),i.extend(g,{href:a,type:c,content:l,title:r,selector:u}),e[n]=g}),s.opts=i.extend(!0,{},s.defaults,t),void 0!==t.keys&&(s.opts.keys=!!t.keys&&i.extend({},s.defaults.keys,t.keys)),s.group=e,s._start(s.opts.index)},cancel:function(){var e=s.coming;e&&!1!==s.trigger("onCancel")&&(s.hideLoading(),s.ajaxLoad&&s.ajaxLoad.abort(),s.ajaxLoad=null,s.imgPreload&&(s.imgPreload.onload=s.imgPreload.onerror=null),e.wrap&&e.wrap.stop(!0,!0).trigger("onReset").remove(),s.coming=null,s.current||s._afterZoomOut(e))},close:function(e){s.cancel(),!1!==s.trigger("beforeClose")&&(s.unbindEvents(),s.isActive&&(s.isOpen&&!0!==e?(s.isOpen=s.isOpened=!1,s.isClosing=!0,i(".fancybox-item, .fancybox-nav").remove(),s.wrap.stop(!0,!0).removeClass("fancybox-opened"),s.transitions[s.current.closeMethod]()):(i(".fancybox-wrap").stop(!0).trigger("onReset").remove(),s._afterZoomOut())))},play:function(e){var t=function(){clearTimeout(s.player.timer)},i=function(){t(),s.current&&s.player.isActive&&(s.player.timer=setTimeout(s.next,s.current.playSpeed))},n=function(){t(),r.unbind(".player"),s.player.isActive=!1,s.trigger("onPlayEnd")};!0===e||!s.player.isActive&&!1!==e?s.current&&(s.current.loop||s.current.index<s.group.length-1)&&(s.player.isActive=!0,r.bind({"onCancel.player beforeClose.player":n,"onUpdate.player":i,"beforeLoad.player":t}),i(),s.trigger("onPlayStart")):n()},next:function(e){var t=s.current;t&&(h(e)||(e=t.direction.next),s.jumpto(t.index+1,e,"next"))},prev:function(e){var t=s.current;t&&(h(e)||(e=t.direction.prev),s.jumpto(t.index-1,e,"prev"))},jumpto:function(e,t,i){var n=s.current;n&&(e=g(e),s.direction=t||n.direction[e>=n.index?"next":"prev"],s.router=i||"jumpto",n.loop&&(e<0&&(e=n.group.length+e%n.group.length),e%=n.group.length),void 0!==n.group[e]&&(s.cancel(),s._start(e)))},reposition:function(e,t){var n,o=s.current,a=o?o.wrap:null;a&&(n=s._getPosition(t),e&&"scroll"===e.type?(delete n.position,a.stop(!0,!0).animate(n,200)):(a.css(n),o.pos=i.extend({},o.dim,n)))},update:function(e){var t=e&&e.type,i=!t||"orientationchange"===t;i&&(clearTimeout(c),c=null),s.isOpen&&!c&&(c=setTimeout(function(){var n=s.current;n&&!s.isClosing&&(s.wrap.removeClass("fancybox-tmp"),(i||"load"===t||"resize"===t&&n.autoResize)&&s._setDimension(),"scroll"===t&&n.canShrink||s.reposition(e),s.trigger("onUpdate"),c=null)},i&&!d?0:300))},toggle:function(e){s.isOpen&&(s.current.fitToView="boolean"===i.type(e)?e:!s.current.fitToView,d&&(s.wrap.removeAttr("style").addClass("fancybox-tmp"),s.trigger("onUpdate")),s.update())},hideLoading:function(){r.unbind(".loading"),i("#fancybox-loading").remove()},showLoading:function(){var e,t;s.hideLoading(),e=i('<div id="fancybox-loading"><div></div></div>').click(s.cancel).appendTo("body"),r.bind("keydown.loading",function(e){27===(e.which||e.keyCode)&&(e.preventDefault(),s.cancel())}),s.defaults.fixed||(t=s.getViewport(),e.css({position:"absolute",top:.5*t.h+t.y,left:.5*t.w+t.x}))},getViewport:function(){var t=s.current&&s.current.locked||!1,i={x:a.scrollLeft(),y:a.scrollTop()};return t?(i.w=t[0].clientWidth,i.h=t[0].clientHeight):(i.w=d&&e.innerWidth?e.innerWidth:a.width(),i.h=d&&e.innerHeight?e.innerHeight:a.height()),i},unbindEvents:function(){s.wrap&&p(s.wrap)&&s.wrap.unbind(".fb"),r.unbind(".fb"),a.unbind(".fb")},bindEvents:function(){var e,t=s.current;t&&(a.bind("orientationchange.fb"+(d?"":" resize.fb")+(t.autoCenter&&!t.locked?" scroll.fb":""),s.update),(e=t.keys)&&r.bind("keydown.fb",function(n){var o=n.which||n.keyCode,a=n.target||n.srcElement;if(27===o&&s.coming)return!1;n.ctrlKey||n.altKey||n.shiftKey||n.metaKey||a&&(a.type||i(a).is("[contenteditable]"))||i.each(e,function(e,a){return t.group.length>1&&void 0!==a[o]?(s[e](a[o]),n.preventDefault(),!1):i.inArray(o,a)>-1?(s[e](),n.preventDefault(),!1):void 0})}),i.fn.mousewheel&&t.mouseWheel&&s.wrap.bind("mousewheel.fb",function(e,n,o,a){for(var r=e.target||null,l=i(r),c=!1;l.length&&!(c||l.is(".fancybox-skin")||l.is(".fancybox-wrap"));)c=u(l[0]),l=i(l).parent();0===n||c||s.group.length>1&&!t.canShrink&&(a>0||o>0?s.prev(a>0?"down":"left"):(a<0||o<0)&&s.next(a<0?"up":"right"),e.preventDefault())}))},trigger:function(e,t){var n,o=t||s.coming||s.current;if(o){if(i.isFunction(o[e])&&(n=o[e].apply(o,Array.prototype.slice.call(arguments,1))),!1===n)return!1;o.helpers&&i.each(o.helpers,function(t,n){n&&s.helpers[t]&&i.isFunction(s.helpers[t][e])&&s.helpers[t][e](i.extend(!0,{},s.helpers[t].defaults,n),o)}),r.trigger(e)}},isImage:function(e){return h(e)&&e.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i)},isSWF:function(e){return h(e)&&e.match(/\.(swf)((\?|#).*)?$/i)},_start:function(e){var t,n,o,a,r,l={};if(e=g(e),!(t=s.group[e]||null))return!1;if(l=i.extend(!0,{},s.opts,t),a=l.margin,r=l.padding,"number"===i.type(a)&&(l.margin=[a,a,a,a]),"number"===i.type(r)&&(l.padding=[r,r,r,r]),l.modal&&i.extend(!0,l,{closeBtn:!1,closeClick:!1,nextClick:!1,arrows:!1,mouseWheel:!1,keys:null,helpers:{overlay:{closeClick:!1}}}),l.autoSize&&(l.autoWidth=l.autoHeight=!0),"auto"===l.width&&(l.autoWidth=!0),"auto"===l.height&&(l.autoHeight=!0),l.group=s.group,l.index=e,s.coming=l,!1!==s.trigger("beforeLoad")){if(o=l.type,n=l.href,!o)return s.coming=null,!(!s.current||!s.router||"jumpto"===s.router)&&(s.current.index=e,s[s.router](s.direction));if(s.isActive=!0,"image"!==o&&"swf"!==o||(l.autoHeight=l.autoWidth=!1,l.scrolling="visible"),"image"===o&&(l.aspectRatio=!0),"iframe"===o&&d&&(l.scrolling="scroll"),l.wrap=i(l.tpl.wrap).addClass("fancybox-"+(d?"mobile":"desktop")+" fancybox-type-"+o+" fancybox-tmp "+l.wrapCSS).appendTo(l.parent||"body"),i.extend(l,{skin:i(".fancybox-skin",l.wrap),outer:i(".fancybox-outer",l.wrap),inner:i(".fancybox-inner",l.wrap)}),i.each(["Top","Right","Bottom","Left"],function(e,t){l.skin.css("padding"+t,m(l.padding[e]))}),s.trigger("onReady"),"inline"===o||"html"===o){if(!l.content||!l.content.length)return s._error("content")}else if(!n)return s._error("href");"image"===o?s._loadImage():"ajax"===o?s._loadAjax():"iframe"===o?s._loadIframe():s._afterLoad()}else s.coming=null},_error:function(e){i.extend(s.coming,{type:"html",autoWidth:!0,autoHeight:!0,minWidth:0,minHeight:0,scrolling:"no",hasError:e,content:s.coming.tpl.error}),s._afterLoad()},_loadImage:function(){var e=s.imgPreload=new Image;e.onload=function(){this.onload=this.onerror=null,s.coming.width=this.width/s.opts.pixelRatio,s.coming.height=this.height/s.opts.pixelRatio,s._afterLoad()},e.onerror=function(){this.onload=this.onerror=null,s._error("image")},e.src=s.coming.href,!0!==e.complete&&s.showLoading()},_loadAjax:function(){var e=s.coming;s.showLoading(),s.ajaxLoad=i.ajax(i.extend({},e.ajax,{url:e.href,error:function(e,t){s.coming&&"abort"!==t?s._error("ajax",e):s.hideLoading()},success:function(t,i){"success"===i&&(e.content=t,s._afterLoad())}}))},_loadIframe:function(){var e=s.coming,t=i(e.tpl.iframe.replace(/\{rnd\}/g,(new Date).getTime())).attr("scrolling",d?"auto":e.iframe.scrolling).attr("src",e.href);i(e.wrap).bind("onReset",function(){try{i(this).find("iframe").hide().attr("src","//about:blank").end().empty()}catch(e){}}),e.iframe.preload&&(s.showLoading(),t.one("load",function(){i(this).data("ready",1),d||i(this).bind("load.fb",s.update),i(this).parents(".fancybox-wrap").width("100%").removeClass("fancybox-tmp").show(),s._afterLoad()})),e.content=t.appendTo(e.inner),e.iframe.preload||s._afterLoad()},_preloadImages:function(){var e,t,i=s.group,n=s.current,o=i.length,a=n.preload?Math.min(n.preload,o-1):0;for(t=1;t<=a;t+=1)"image"===(e=i[(n.index+t)%o]).type&&e.href&&((new Image).src=e.href)},_afterLoad:function(){var e,t,n,o,a,r,l=s.coming,c=s.current,d="fancybox-placeholder";if(s.hideLoading(),l&&!1!==s.isActive){if(!1===s.trigger("afterLoad",l,c))return l.wrap.stop(!0).trigger("onReset").remove(),void(s.coming=null);switch(c&&(s.trigger("beforeChange",c),c.wrap.stop(!0).removeClass("fancybox-opened").find(".fancybox-item, .fancybox-nav").remove()),s.unbindEvents(),e=l,t=l.content,n=l.type,o=l.scrolling,i.extend(s,{wrap:e.wrap,skin:e.skin,outer:e.outer,inner:e.inner,current:e,previous:c}),a=e.href,n){case"inline":case"ajax":case"html":e.selector?t=i("<div>").html(t).find(e.selector):p(t)&&(t.data(d)||t.data(d,i('<div class="'+d+'"></div>').insertAfter(t).hide()),t=t.show().detach(),e.wrap.bind("onReset",function(){i(this).find(t).length&&t.hide().replaceAll(t.data(d)).data(d,!1)}));break;case"image":t=e.tpl.image.replace("{href}",a);break;case"swf":t='<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="'+a+'"></param>',r="",i.each(e.swf,function(e,i){t+='<param name="'+e+'" value="'+i+'"></param>',r+=" "+e+'="'+i+'"'}),t+='<embed src="'+a+'" type="application/x-shockwave-flash" width="100%" height="100%"'+r+"></embed></object>"}p(t)&&t.parent().is(e.inner)||e.inner.append(t),s.trigger("beforeShow"),e.inner.css("overflow","yes"===o?"scroll":"no"===o?"hidden":o),s._setDimension(),s.reposition(),s.isOpen=!1,s.coming=null,s.bindEvents(),s.isOpened?c.prevMethod&&s.transitions[c.prevMethod]():i(".fancybox-wrap").not(e.wrap).stop(!0).trigger("onReset").remove(),s.transitions[s.isOpened?e.nextMethod:e.openMethod](),s._preloadImages()}},_setDimension:function(){var e,t,n,o,a,r,l,c,d,p,h,u,y,x,v,w=s.getViewport(),b=0,k=!1,C=!1,S=s.wrap,O=s.skin,M=s.inner,T=s.current,W=T.width,_=T.height,E=T.minWidth,R=T.minHeight,L=T.maxWidth,A=T.maxHeight,P=T.scrolling,j=T.scrollOutside?T.scrollbarWidth:0,H=T.margin,I=g(H[1]+H[3]),D=g(H[0]+H[2]);if(S.add(O).add(M).width("auto").height("auto").removeClass("fancybox-tmp"),e=g(O.outerWidth(!0)-O.width()),t=g(O.outerHeight(!0)-O.height()),n=I+e,o=D+t,a=f(W)?(w.w-n)*g(W)/100:W,r=f(_)?(w.h-o)*g(_)/100:_,"iframe"===T.type){if(x=T.content,T.autoHeight&&1===x.data("ready"))try{x[0].contentWindow.document.location&&(M.width(a).height(9999),v=x.contents().find("body"),j&&v.css("overflow-x","hidden"),r=v.outerHeight(!0))}catch(e){}}else(T.autoWidth||T.autoHeight)&&(M.addClass("fancybox-tmp"),T.autoWidth||M.width(a),T.autoHeight||M.height(r),T.autoWidth&&(a=M.width()),T.autoHeight&&(r=M.height()),M.removeClass("fancybox-tmp"));if(W=g(a),_=g(r),d=a/r,E=g(f(E)?g(E,"w")-n:E),L=g(f(L)?g(L,"w")-n:L),R=g(f(R)?g(R,"h")-o:R),A=g(f(A)?g(A,"h")-o:A),l=L,c=A,T.fitToView&&(L=Math.min(w.w-n,L),A=Math.min(w.h-o,A)),u=w.w-I,y=w.h-D,T.aspectRatio?(W>L&&(_=g((W=L)/d)),_>A&&(W=g((_=A)*d)),W<E&&(_=g((W=E)/d)),_<R&&(W=g((_=R)*d))):(W=Math.max(E,Math.min(W,L)),T.autoHeight&&"iframe"!==T.type&&(M.width(W),_=M.height()),_=Math.max(R,Math.min(_,A))),T.fitToView)if(M.width(W).height(_),S.width(W+e),p=S.width(),h=S.height(),T.aspectRatio)for(;(p>u||h>y)&&W>E&&_>R&&!(b++>19);)_=Math.max(R,Math.min(A,_-10)),(W=g(_*d))<E&&(_=g((W=E)/d)),W>L&&(_=g((W=L)/d)),M.width(W).height(_),S.width(W+e),p=S.width(),h=S.height();else W=Math.max(E,Math.min(W,W-(p-u))),_=Math.max(R,Math.min(_,_-(h-y)));j&&"auto"===P&&_<r&&W+e+j<u&&(W+=j),M.width(W).height(_),S.width(W+e),p=S.width(),h=S.height(),k=(p>u||h>y)&&W>E&&_>R,C=T.aspectRatio?W<l&&_<c&&W<a&&_<r:(W<l||_<c)&&(W<a||_<r),i.extend(T,{dim:{width:m(p),height:m(h)},origWidth:a,origHeight:r,canShrink:k,canExpand:C,wPadding:e,hPadding:t,wrapSpace:h-O.outerHeight(!0),skinSpace:O.height()-_}),!x&&T.autoHeight&&_>R&&_<A&&!C&&M.height("auto")},_getPosition:function(e){var t=s.current,i=s.getViewport(),n=t.margin,o=s.wrap.width()+n[1]+n[3],a=s.wrap.height()+n[0]+n[2],r={position:"absolute",top:n[0],left:n[3]};return t.autoCenter&&t.fixed&&!e&&a<=i.h&&o<=i.w?r.position="fixed":t.locked||(r.top+=i.y,r.left+=i.x),r.top=m(Math.max(r.top,r.top+(i.h-a)*t.topRatio)),r.left=m(Math.max(r.left,r.left+(i.w-o)*t.leftRatio)),r},_afterZoomIn:function(){var e=s.current;e&&(s.isOpen=s.isOpened=!0,s.wrap.css("overflow","visible").addClass("fancybox-opened"),s.update(),(e.closeClick||e.nextClick&&s.group.length>1)&&s.inner.css("cursor","pointer").bind("click.fb",function(t){i(t.target).is("a")||i(t.target).parent().is("a")||(t.preventDefault(),s[e.closeClick?"close":"next"]())}),e.closeBtn&&i(e.tpl.closeBtn).appendTo(s.skin).bind("click.fb",function(e){e.preventDefault(),s.close()}),e.arrows&&s.group.length>1&&((e.loop||e.index>0)&&i(e.tpl.prev).appendTo(s.outer).bind("click.fb",s.prev),(e.loop||e.index<s.group.length-1)&&i(e.tpl.next).appendTo(s.outer).bind("click.fb",s.next)),s.trigger("afterShow"),e.loop||e.index!==e.group.length-1?s.opts.autoPlay&&!s.player.isActive&&(s.opts.autoPlay=!1,s.play()):s.play(!1))},_afterZoomOut:function(e){e=e||s.current,i(".fancybox-wrap").trigger("onReset").remove(),i.extend(s,{group:{},opts:{},router:!1,current:null,isActive:!1,isOpened:!1,isOpen:!1,isClosing:!1,wrap:null,skin:null,outer:null,inner:null}),s.trigger("afterClose",e)}}),s.transitions={getOrigPosition:function(){var e=s.current,t=e.element,i=e.orig,n={},o=50,a=50,r=e.hPadding,l=e.wPadding,c=s.getViewport();return!i&&e.isDom&&t.is(":visible")&&((i=t.find("img:first")).length||(i=t)),p(i)?(n=i.offset(),i.is("img")&&(o=i.outerWidth(),a=i.outerHeight())):(n.top=c.y+(c.h-a)*e.topRatio,n.left=c.x+(c.w-o)*e.leftRatio),("fixed"===s.wrap.css("position")||e.locked)&&(n.top-=c.y,n.left-=c.x),n={top:m(n.top-r*e.topRatio),left:m(n.left-l*e.leftRatio),width:m(o+l),height:m(a+r)}},step:function(e,t){var i,n,o=t.prop,a=s.current,r=a.wrapSpace,l=a.skinSpace;"width"!==o&&"height"!==o||(i=t.end===t.start?1:(e-t.start)/(t.end-t.start),s.isClosing&&(i=1-i),n=e-("width"===o?a.wPadding:a.hPadding),s.skin[o](g("width"===o?n:n-r*i)),s.inner[o](g("width"===o?n:n-r*i-l*i)))},zoomIn:function(){var e=s.current,t=e.pos,n=e.openEffect,o="elastic"===n,a=i.extend({opacity:1},t);delete a.position,o?(t=this.getOrigPosition(),e.openOpacity&&(t.opacity=.1)):"fade"===n&&(t.opacity=.1),s.wrap.css(t).animate(a,{duration:"none"===n?0:e.openSpeed,easing:e.openEasing,step:o?this.step:null,complete:s._afterZoomIn})},zoomOut:function(){var e=s.current,t=e.closeEffect,i="elastic"===t,n={opacity:.1};i&&(n=this.getOrigPosition(),e.closeOpacity&&(n.opacity=.1)),s.wrap.animate(n,{duration:"none"===t?0:e.closeSpeed,easing:e.closeEasing,step:i?this.step:null,complete:s._afterZoomOut})},changeIn:function(){var e,t=s.current,i=t.nextEffect,n=t.pos,o={opacity:1},a=s.direction;n.opacity=.1,"elastic"===i&&(e="down"===a||"up"===a?"top":"left","down"===a||"right"===a?(n[e]=m(g(n[e])-200),o[e]="+=200px"):(n[e]=m(g(n[e])+200),o[e]="-=200px")),"none"===i?s._afterZoomIn():s.wrap.css(n).animate(o,{duration:t.nextSpeed,easing:t.nextEasing,complete:s._afterZoomIn})},changeOut:function(){var e=s.previous,t=e.prevEffect,n={opacity:.1},o=s.direction;"elastic"===t&&(n["down"===o||"up"===o?"top":"left"]=("up"===o||"left"===o?"-":"+")+"=200px"),e.wrap.animate(n,{duration:"none"===t?0:e.prevSpeed,easing:e.prevEasing,complete:function(){i(this).trigger("onReset").remove()}})}},s.helpers.overlay={defaults:{closeClick:!0,speedOut:200,showEarly:!0,css:{},locked:!d,fixed:!0},overlay:null,fixed:!1,el:i("html"),create:function(e){e=i.extend({},this.defaults,e),this.overlay&&this.close(),this.overlay=i('<div class="fancybox-overlay"></div>').appendTo(s.coming?s.coming.parent:e.parent),this.fixed=!1,e.fixed&&s.defaults.fixed&&(this.overlay.addClass("fancybox-overlay-fixed"),this.fixed=!0)},open:function(e){var t=this;e=i.extend({},this.defaults,e),this.overlay?this.overlay.unbind(".overlay").width("auto").height("auto"):this.create(e),this.fixed||(a.bind("resize.overlay",i.proxy(this.update,this)),this.update()),e.closeClick&&this.overlay.bind("click.overlay",function(e){if(i(e.target).hasClass("fancybox-overlay"))return s.isActive?s.close():t.close(),!1}),this.overlay.css(e.css).show()},close:function(){var e,t;a.unbind("resize.overlay"),this.el.hasClass("fancybox-lock")&&(i(".fancybox-margin").removeClass("fancybox-margin"),e=a.scrollTop(),t=a.scrollLeft(),this.el.removeClass("fancybox-lock"),a.scrollTop(e).scrollLeft(t)),i(".fancybox-overlay").remove().hide(),i.extend(this,{overlay:null,fixed:!1})},update:function(){var e,i="100%";this.overlay.width(i).height("100%"),l?(e=Math.max(t.documentElement.offsetWidth,t.body.offsetWidth),r.width()>e&&(i=r.width())):r.width()>a.width()&&(i=r.width()),this.overlay.width(i).height(r.height())},onReady:function(e,t){var n=this.overlay;i(".fancybox-overlay").stop(!0,!0),n||this.create(e),e.locked&&this.fixed&&t.fixed&&(n||(this.margin=r.height()>a.height()&&i("html").css("margin-right").replace("px","")),t.locked=this.overlay.append(t.wrap),t.fixed=!1),!0===e.showEarly&&this.beforeShow.apply(this,arguments)},beforeShow:function(e,t){var n,o;t.locked&&(!1!==this.margin&&(i("*").filter(function(){return"fixed"===i(this).css("position")&&!i(this).hasClass("fancybox-overlay")&&!i(this).hasClass("fancybox-wrap")}).addClass("fancybox-margin"),this.el.addClass("fancybox-margin")),n=a.scrollTop(),o=a.scrollLeft(),this.el.addClass("fancybox-lock"),a.scrollTop(n).scrollLeft(o)),this.open(e)},onUpdate:function(){this.fixed||this.update()},afterClose:function(e){this.overlay&&!s.coming&&this.overlay.fadeOut(e.speedOut,i.proxy(this.close,this))}},s.helpers.title={defaults:{type:"float",position:"bottom"},beforeShow:function(e){var t,n,o=s.current,a=o.title,r=e.type;if(i.isFunction(a)&&(a=a.call(o.element,o)),h(a)&&""!==i.trim(a)){switch(t=i('<div class="fancybox-title fancybox-title-'+r+'-wrap">'+a+"</div>"),r){case"inside":n=s.skin;break;case"outside":n=s.wrap;break;case"over":n=s.inner;break;default:n=s.skin,t.appendTo("body"),l&&t.width(t.width()),t.wrapInner('<span class="child"></span>'),s.current.margin[2]+=Math.abs(g(t.css("margin-bottom")))}t["top"===e.position?"prependTo":"appendTo"](n)}}},i.fn.fancybox=function(e){var t,n=i(this),o=this.selector||"",a=function(a){var r,l,c=i(this).blur(),d=t;a.ctrlKey||a.altKey||a.shiftKey||a.metaKey||c.is(".fancybox-wrap")||(r=e.groupAttr||"data-fancybox-group",(l=c.attr(r))||(r="rel",l=c.get(0)[r]),l&&""!==l&&"nofollow"!==l&&(d=(c=(c=o.length?i(o):n).filter("["+r+'="'+l+'"]')).index(this)),e.index=d,!1!==s.open(c,e)&&a.preventDefault())};return e=e||{},t=e.index||0,o&&!1!==e.live?r.undelegate(o,"click.fb-start").delegate(o+":not('.fancybox-item, .fancybox-nav')","click.fb-start",a):n.unbind("click.fb-start").bind("click.fb-start",a),this.filter("[data-fancybox-start=1]").trigger("click"),this},r.ready(function(){var t,n;void 0===i.scrollbarWidth&&(i.scrollbarWidth=function(){var e=i('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo("body"),t=e.children(),n=t.innerWidth()-t.height(99).innerWidth();return e.remove(),n}),void 0===i.support.fixedPosition&&(i.support.fixedPosition=function(){var e=i('<div style="position:fixed;top:20px;"></div>').appendTo("body"),t=20===e[0].offsetTop||15===e[0].offsetTop;return e.remove(),t}()),i.extend(s.defaults,{scrollbarWidth:i.scrollbarWidth(),fixed:i.support.fixedPosition,parent:i("body")}),t=i(e).width(),o.addClass("fancybox-lock-test"),n=i(e).width(),o.removeClass("fancybox-lock-test"),i("<style type='text/css'>.fancybox-margin{margin-right:"+(n-t)+"px;}</style>").appendTo("head")})}(window,document,jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-fancybox-2.1.5.min.js
jquery-fancybox-2.1.5.min.js
(function(g){var c=function(){Error.apply(this,arguments)};c.prototype=new Error();c.prototype.type="XML-RPC fault";var a=g.xmlrpc=function(i,j){if(arguments.length===2){j.url=i}else{j=i;i=j.url}j.dataType="xml json";j.type="POST";j.contentType="text/xml";j.converters={"xml json":a.parseDocument};var k=a.document(j.methodName,j.params||[]);if("XMLSerializer" in window){j.data=new window.XMLSerializer().serializeToString(k)}else{j.data=k.xml}return g.ajax(j)};a.createXMLDocument=function(){if(document.implementation&&"createDocument" in document.implementation){return document.implementation.createDocument(null,null,null)}else{var l,m,j=["MSXML6.DomDocument","MSXML3.DomDocument","MSXML2.DomDocument","MSXML.DomDocument","Microsoft.XmlDom"];for(l=0,m=j.length;l<m;l++){try{return new ActiveXObject(j[l])}catch(k){}}}};a.document=function(l,o){var n=a.createXMLDocument();var m=function(p){return g(n.createElement(p))};var j=m("methodName").text(l);var i=m("params").append(g.map(o,function(q){var p=m("value").append(a.toXmlRpc(q,m));return m("param").append(p)}));var k=m("methodCall").append(j,i);n.appendChild(k.get(0));return n};var b=function(i){return(i===parseInt(i,10))&&!isNaN(i)};a.toXmlRpc=function(l,k){if(l instanceof f){return l.toXmlRpc(k)}var i=g.xmlrpc.types;var j=g.type(l);switch(j){case"undefined":case"null":return i.nil.encode(l,k);case"date":return i["datetime.iso8601"].encode(l,k);case"object":if(l instanceof ArrayBuffer){return i.base64.encode(l,k)}else{return i.struct.encode(l,k)}break;case"number":if(b(l)){return i["int"].encode(l,k)}else{return i["double"].encode(l,k)}break;case"array":case"boolean":case"string":return i[j].encode(l,k);default:throw new Error("Unknown type",l)}};a.parseDocument=function(o){var p=g(o);var i=p.children("methodresponse");var l=i.find("> fault");if(l.length===0){var j=i.find("> params > param > value > *");var k=j.toArray().map(a.parseNode);return k}else{var n=a.parseNode(l.find("> value > *").get(0));var m=new c(n.faultString);m.msg=m.message=n.faultString;m.type=m.code=n.faultCode;throw m}};a.parseNode=function(j){if(j===undefined){return null}var i=j.nodeName.toLowerCase();if(i in a.types){return a.types[i].decode(j)}else{throw new Error("Unknown type "+i)}};a.parseValue=function(i){var j=g(i).children()[0];if(j){return a.parseNode(j)}else{return g(i).text()}};var f=function(){};g.xmlrpc.types={};a.makeType=function(j,o,k,m){var i;i=function(p){this.value=p};i.prototype=new f();i.prototype.tagName=j;if(o){var l=k,n=m;k=function(q,p){var r=l(q);return p(i.tagName).text(r)};m=function(p){return n(g(p).text(),p)}}i.prototype.toXmlRpc=function(p){return i.encode(this.value,p)};i.tagName=j;i.encode=k;i.decode=m;a.types[j.toLowerCase()]=i};var e=function(i){return""+Math.floor(i)};var d=function(j,i){return parseInt(j,10)};a.makeType("int",true,e,d);a.makeType("i4",true,e,d);a.makeType("i8",true,e,d);a.makeType("i16",true,e,d);a.makeType("i32",true,e,d);a.makeType("double",true,String,function(i){return parseFloat(i,10)});a.makeType("string",true,String,String);a.makeType("boolean",true,function(i){return i?"1":"0"},function(i){return i==="1"});var h=function(i){return i<10?"0"+i:i};a.makeType("dateTime.iso8601",true,function(i){return[i.getUTCFullYear(),"-",h(i.getUTCMonth()+1),"-",h(i.getUTCDate()),"T",h(i.getUTCHours()),":",h(i.getUTCMinutes()),":",h(i.getUTCSeconds()),"Z"].join("")},function(i){return new Date(i)});a.binary=(function(){var k="=";var i=("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").split("");var j=i.reduce(function(n,m,l){n[m]=l;return n},{});return{toBase64:function(p){var o=[];var q=new Uint8Array(p);var m=0,n;for(;m<q.length;m+=3){n=(q[m+0]<<16)+(q[m+1]<<8)+(q[m+2]<<0);o.push(i[(n>>18)%64]);o.push(i[(n>>12)%64]);o.push(i[(n>>6)%64]);o.push(i[(n>>0)%64])}var l=3-((p.byteLength%3)||3);while(l--){o[o.length-l-1]=k}return o.join("")},fromBase64:function(m){var l=m.length;var s=(l/4)*3;if(m.charAt(l-1)===k){s--}if(m.charAt(l-2)===k){s--}var q=new ArrayBuffer(s);var r=new Uint8Array(q);var o=0,n=0,p;for(;o<l;o+=4,n+=3){p=(j[m[o+0]]<<18)+(j[m[o+1]]<<12)+(j[m[o+2]]<<6)+(j[m[o+3]]<<0);r[n+0]=(p>>16)%256;r[n+1]=(p>>8)%256;r[n+2]=(p>>0)%256}return q}}})();a.makeType("base64",true,function(i){return a.binary.toBase64(i)},function(i){return a.binary.fromBase64(i)});a.makeType("nil",false,function(j,i){return i("nil")},function(i){return null});a.makeType("struct",false,function(k,j){var i=j("struct");g.each(k,function(l,n){var o=j("name").text(l);var m=j("value").append(a.toXmlRpc(n,j));i.append(j("member").append(o,m))});return i},function(i){return g(i).find("> member").toArray().reduce(function(n,l){var k=g(l);var j=k.find("> name").text();var m=a.parseValue(k.find("> value"));n[j]=m;return n},{})});a.makeType("array",false,function(l,j){var k=j("array");var i=j("data");g.each(l,function(m,n){i.append(j("value").append(a.toXmlRpc(n,j)))});k.append(i);return k},function(i){return g(i).find("> data > value").toArray().map(a.parseValue)});a.force=function(i,j){return new a.types[i](j)}})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-xmlrpc.min.js
jquery-xmlrpc.min.js
(function ($) { var options = { tooltip: false, //boolean tooltipOpts: { content: "%s | X: %x | Y: %y.2", //%s -> series label, %x -> X value, %y -> Y value, %x.2 -> precision of X value, %p -> percent dateFormat: "%y-%0m-%0d", shifts: { x: 10, y: 20 }, defaultTheme: true } }; var init = function (plot) { var tipPosition = {x: 0, y: 0}; var opts = plot.getOptions(); var updateTooltipPosition = function (pos) { tipPosition.x = pos.x; tipPosition.y = pos.y; }; var onMouseMove = function (e) { var pos = {x: 0, y: 0}; pos.x = e.pageX; pos.y = e.pageY; updateTooltipPosition(pos); }; var timestampToDate = function (tmst) { var theDate = new Date(tmst); return $.plot.formatDate(theDate, opts.tooltipOpts.dateFormat); }; plot.hooks.bindEvents.push(function (plot, eventHolder) { var to = opts.tooltipOpts; var placeholder = plot.getPlaceholder(); var $tip; if (opts.tooltip === false) return; if ($('#flotTip').length > 0) { $tip = $('#flotTip'); } else { $tip = $('<div />').attr('id', 'flotTip'); $tip.appendTo('body').hide().css({position: 'absolute'}); if (to.defaultTheme) { $tip.css({ 'background': '#fff', 'z-index': '100', 'padding': '0.4em 0.6em', 'border-radius': '0.5em', 'font-size': '0.8em', 'border': '1px solid #111' }); } } $(placeholder).bind("plothover", function (event, pos, item) { if (item) { var tipText; if (opts.xaxis.mode === "time" || opts.xaxes[0].mode === "time") { tipText = stringFormat(to.content, item, timestampToDate); } else { tipText = stringFormat(to.content, item); } $tip.html(tipText).css({left: tipPosition.x + to.shifts.x, top: tipPosition.y + to.shifts.y}).show(); } else { $tip.hide().html(''); } }); eventHolder.mousemove(onMouseMove); }); var stringFormat = function (content, item, fnct) { var percentPattern = /%p\.{0,1}(\d{0,})/; var seriesPattern = /%s/; var xPattern = /%x\.{0,1}(\d{0,})/; var yPattern = /%y\.{0,1}(\d{0,})/; //percent match if (typeof (item.series.percent) !== 'undefined') { content = adjustValPrecision(percentPattern, content, item.series.percent); } //series match if (typeof(item.series.label) !== 'undefined') { content = content.replace(seriesPattern, item.series.label); } // xVal match if (typeof(fnct) === 'function') { content = content.replace(xPattern, fnct(item.series.data[item.dataIndex][0])); } else if (typeof item.series.data[item.dataIndex][0] === 'number') { content = adjustValPrecision(xPattern, content, item.series.data[item.dataIndex][0]); } // yVal match if (typeof item.series.data[item.dataIndex][1] === 'number') { content = adjustValPrecision(yPattern, content, item.series.data[item.dataIndex][1]); } return content; }; var adjustValPrecision = function (pattern, content, value) { var precision; if (content.match(pattern) !== 'null') { if (RegExp.$1 !== '') { precision = RegExp.$1; value = value.toFixed(precision) } content = content.replace(pattern, value); } return content; }; } $.plot.plugins.push({ init: init, options: options, name: 'tooltip', version: '0.4.4' }); })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-plot-tooltip-0.4.4.js
jquery-plot-tooltip-0.4.4.js
* @summary ColReorder * @description Provide the ability to reorder columns in a DataTable * @version 1.1.0 * @file dataTables.colReorder.js * @author SpryMedia Ltd (www.sprymedia.co.uk) * @contact www.sprymedia.co.uk/contact * @copyright Copyright 2010-2014 SpryMedia Ltd. * * This source file is free software, available under the following license: * MIT license - http://datatables.net/license/mit * * 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 */ (function (window, document, undefined) { /** * Switch the key value pairing of an index array to be value key (i.e. the old value is now the * key). For example consider [ 2, 0, 1 ] this would be returned as [ 1, 2, 0 ]. * @method fnInvertKeyValues * @param array aIn Array to switch around * @returns array */ function fnInvertKeyValues(aIn) { var aRet = []; for (var i = 0, iLen = aIn.length; i < iLen; i++) { aRet[ aIn[i] ] = i; } return aRet; } /** * Modify an array by switching the position of two elements * @method fnArraySwitch * @param array aArray Array to consider, will be modified by reference (i.e. no return) * @param int iFrom From point * @param int iTo Insert point * @returns void */ function fnArraySwitch(aArray, iFrom, iTo) { var mStore = aArray.splice(iFrom, 1)[0]; aArray.splice(iTo, 0, mStore); } /** * Switch the positions of nodes in a parent node (note this is specifically designed for * table rows). Note this function considers all element nodes under the parent! * @method fnDomSwitch * @param string sTag Tag to consider * @param int iFrom Element to move * @param int Point to element the element to (before this point), can be null for append * @returns void */ function fnDomSwitch(nParent, iFrom, iTo) { var anTags = []; for (var i = 0, iLen = nParent.childNodes.length; i < iLen; i++) { if (nParent.childNodes[i].nodeType == 1) { anTags.push(nParent.childNodes[i]); } } var nStore = anTags[ iFrom ]; if (iTo !== null) { nParent.insertBefore(nStore, anTags[iTo]); } else { nParent.appendChild(nStore); } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables plug-in API functions * * This are required by ColReorder in order to perform the tasks required, and also keep this * code portable, to be used for other column reordering projects with DataTables, if needed. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Plug-in for DataTables which will reorder the internal column structure by taking the column * from one position (iFrom) and insert it into a given point (iTo). * @method $.fn.dataTableExt.oApi.fnColReorder * @param object oSettings DataTables settings object - automatically added by DataTables! * @param int iFrom Take the column to be repositioned from this point * @param int iTo and insert it into this point * @returns void */ $.fn.dataTableExt.oApi.fnColReorder = function (oSettings, iFrom, iTo) { var v110 = $.fn.dataTable.Api ? true : false; var i, iLen, j, jLen, iCols = oSettings.aoColumns.length, nTrs, oCol; /* Sanity check in the input */ if (iFrom == iTo) { /* Pointless reorder */ return; } if (iFrom < 0 || iFrom >= iCols) { this.oApi._fnLog(oSettings, 1, "ColReorder 'from' index is out of bounds: " + iFrom); return; } if (iTo < 0 || iTo >= iCols) { this.oApi._fnLog(oSettings, 1, "ColReorder 'to' index is out of bounds: " + iTo); return; } /* * Calculate the new column array index, so we have a mapping between the old and new */ var aiMapping = []; for (i = 0, iLen = iCols; i < iLen; i++) { aiMapping[i] = i; } fnArraySwitch(aiMapping, iFrom, iTo); var aiInvertMapping = fnInvertKeyValues(aiMapping); /* * Convert all internal indexing to the new column order indexes */ /* Sorting */ for (i = 0, iLen = oSettings.aaSorting.length; i < iLen; i++) { oSettings.aaSorting[i][0] = aiInvertMapping[ oSettings.aaSorting[i][0] ]; } /* Fixed sorting */ if (oSettings.aaSortingFixed !== null) { for (i = 0, iLen = oSettings.aaSortingFixed.length; i < iLen; i++) { oSettings.aaSortingFixed[i][0] = aiInvertMapping[ oSettings.aaSortingFixed[i][0] ]; } } /* Data column sorting (the column which the sort for a given column should take place on) */ for (i = 0, iLen = iCols; i < iLen; i++) { oCol = oSettings.aoColumns[i]; for (j = 0, jLen = oCol.aDataSort.length; j < jLen; j++) { oCol.aDataSort[j] = aiInvertMapping[ oCol.aDataSort[j] ]; } // Update the column indexes if (v110) { oCol.idx = aiInvertMapping[ oCol.idx ]; } } if (v110) { // Update 1.10 optimised sort class removal variable $.each(oSettings.aLastSort, function (i, val) { oSettings.aLastSort[i].src = aiInvertMapping[ val.src ]; }); } /* Update the Get and Set functions for each column */ for (i = 0, iLen = iCols; i < iLen; i++) { oCol = oSettings.aoColumns[i]; if (typeof oCol.mData == 'number') { oCol.mData = aiInvertMapping[ oCol.mData ]; // regenerate the get / set functions oSettings.oApi._fnColumnOptions(oSettings, i, {}); } } /* * Move the DOM elements */ if (oSettings.aoColumns[iFrom].bVisible) { /* Calculate the current visible index and the point to insert the node before. The insert * before needs to take into account that there might not be an element to insert before, * in which case it will be null, and an appendChild should be used */ var iVisibleIndex = this.oApi._fnColumnIndexToVisible(oSettings, iFrom); var iInsertBeforeIndex = null; i = iTo < iFrom ? iTo : iTo + 1; while (iInsertBeforeIndex === null && i < iCols) { iInsertBeforeIndex = this.oApi._fnColumnIndexToVisible(oSettings, i); i++; } /* Header */ nTrs = oSettings.nTHead.getElementsByTagName('tr'); for (i = 0, iLen = nTrs.length; i < iLen; i++) { fnDomSwitch(nTrs[i], iVisibleIndex, iInsertBeforeIndex); } /* Footer */ if (oSettings.nTFoot !== null) { nTrs = oSettings.nTFoot.getElementsByTagName('tr'); for (i = 0, iLen = nTrs.length; i < iLen; i++) { fnDomSwitch(nTrs[i], iVisibleIndex, iInsertBeforeIndex); } } /* Body */ for (i = 0, iLen = oSettings.aoData.length; i < iLen; i++) { if (oSettings.aoData[i].nTr !== null) { fnDomSwitch(oSettings.aoData[i].nTr, iVisibleIndex, iInsertBeforeIndex); } } } /* * Move the internal array elements */ /* Columns */ fnArraySwitch(oSettings.aoColumns, iFrom, iTo); /* Search columns */ fnArraySwitch(oSettings.aoPreSearchCols, iFrom, iTo); /* Array array - internal data anodes cache */ for (i = 0, iLen = oSettings.aoData.length; i < iLen; i++) { if (v110) { // DataTables 1.10+ fnArraySwitch(oSettings.aoData[i].anCells, iFrom, iTo); } else { // DataTables 1.9- if ($.isArray(oSettings.aoData[i]._aData)) { fnArraySwitch(oSettings.aoData[i]._aData, iFrom, iTo); } fnArraySwitch(oSettings.aoData[i]._anHidden, iFrom, iTo); } } /* Reposition the header elements in the header layout array */ for (i = 0, iLen = oSettings.aoHeader.length; i < iLen; i++) { fnArraySwitch(oSettings.aoHeader[i], iFrom, iTo); } if (oSettings.aoFooter !== null) { for (i = 0, iLen = oSettings.aoFooter.length; i < iLen; i++) { fnArraySwitch(oSettings.aoFooter[i], iFrom, iTo); } } // In 1.10 we need to invalidate row cached data for sorting, filtering etc if (v110) { var api = new $.fn.dataTable.Api(oSettings); api.rows().invalidate(); } /* * Update DataTables' event handlers */ /* Sort listener */ for (i = 0, iLen = iCols; i < iLen; i++) { $(oSettings.aoColumns[i].nTh).off('click.DT'); this.oApi._fnSortAttachListener(oSettings, oSettings.aoColumns[i].nTh, i); } /* Fire an event so other plug-ins can update */ $(oSettings.oInstance).trigger('column-reorder', [ oSettings, { "iFrom": iFrom, "iTo": iTo, "aiInvertMapping": aiInvertMapping } ]); }; var factory = function ($, DataTable) { "use strict"; /** * ColReorder provides column visibility control for DataTables * @class ColReorder * @constructor * @param {object} dt DataTables settings object * @param {object} opts ColReorder options */ var ColReorder = function (dt, opts) { var oDTSettings; if ($.fn.dataTable.Api) { oDTSettings = new $.fn.dataTable.Api(dt).settings()[0]; } // 1.9 compatibility else if (dt.fnSettings) { // DataTables object, convert to the settings object oDTSettings = dt.fnSettings(); } else if (typeof dt === 'string') { // jQuery selector if ($.fn.dataTable.fnIsDataTable($(dt)[0])) { oDTSettings = $(dt).eq(0).dataTable().fnSettings(); } } else if (dt.nodeName && dt.nodeName.toLowerCase() === 'table') { // Table node if ($.fn.dataTable.fnIsDataTable(dt.nodeName)) { oDTSettings = $(dt.nodeName).dataTable().fnSettings(); } } else if (dt instanceof jQuery) { // jQuery object if ($.fn.dataTable.fnIsDataTable(dt[0])) { oDTSettings = dt.eq(0).dataTable().fnSettings(); } } else { // DataTables settings object oDTSettings = dt; } // Convert from camelCase to Hungarian, just as DataTables does if ($.fn.dataTable.camelToHungarian) { $.fn.dataTable.camelToHungarian(ColReorder.defaults, opts || {}); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for ColReorder instance */ this.s = { /** * DataTables settings object * @property dt * @type Object * @default null */ "dt": null, /** * Initialisation object used for this instance * @property init * @type object * @default {} */ "init": $.extend(true, {}, ColReorder.defaults, opts), /** * Number of columns to fix (not allow to be reordered) * @property fixed * @type int * @default 0 */ "fixed": 0, /** * Number of columns to fix counting from right (not allow to be reordered) * @property fixedRight * @type int * @default 0 */ "fixedRight": 0, /** * Callback function for once the reorder has been done * @property dropcallback * @type function * @default null */ "dropCallback": null, /** * @namespace Information used for the mouse drag */ "mouse": { "startX": -1, "startY": -1, "offsetX": -1, "offsetY": -1, "target": -1, "targetIndex": -1, "fromIndex": -1 }, /** * Information which is used for positioning the insert cusor and knowing where to do the * insert. Array of objects with the properties: * x: x-axis position * to: insert point * @property aoTargets * @type array * @default [] */ "aoTargets": [] }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * Dragging element (the one the mouse is moving) * @property drag * @type element * @default null */ "drag": null, /** * The insert cursor * @property pointer * @type element * @default null */ "pointer": null }; /* Constructor logic */ this.s.dt = oDTSettings.oInstance.fnSettings(); this.s.dt._colReorder = this; this._fnConstruct(); /* Add destroy callback */ oDTSettings.oApi._fnCallbackReg(oDTSettings, 'aoDestroyCallback', $.proxy(this._fnDestroy, this), 'ColReorder'); return this; }; ColReorder.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Reset the column ordering to the original ordering that was detected on * start up. * @return {this} Returns `this` for chaining. * * @example * // DataTables initialisation with ColReorder * var table = $('#example').dataTable( { * "sDom": 'Rlfrtip' * } ); * * // Add click event to a button to reset the ordering * $('#resetOrdering').click( function (e) { * e.preventDefault(); * $.fn.dataTable.ColReorder( table ).fnReset(); * } ); */ "fnReset": function () { var a = []; for (var i = 0, iLen = this.s.dt.aoColumns.length; i < iLen; i++) { a.push(this.s.dt.aoColumns[i]._ColReorder_iOrigCol); } this._fnOrderColumns(a); return this; }, /** * `Deprecated` - Get the current order of the columns, as an array. * @return {array} Array of column identifiers * @deprecated `fnOrder` should be used in preference to this method. * `fnOrder` acts as a getter/setter. */ "fnGetCurrentOrder": function () { return this.fnOrder(); }, /** * Get the current order of the columns, as an array. Note that the values * given in the array are unique identifiers for each column. Currently * these are the original ordering of the columns that was detected on * start up, but this could potentially change in future. * @return {array} Array of column identifiers * * @example * // Get column ordering for the table * var order = $.fn.dataTable.ColReorder( dataTable ).fnOrder(); *//** * Set the order of the columns, from the positions identified in the * ordering array given. Note that ColReorder takes a brute force approach * to reordering, so it is possible multiple reordering events will occur * before the final order is settled upon. * @param {array} [set] Array of column identifiers in the new order. Note * that every column must be included, uniquely, in this array. * @return {this} Returns `this` for chaining. * * @example * // Swap the first and second columns * $.fn.dataTable.ColReorder( dataTable ).fnOrder( [1, 0, 2, 3, 4] ); * * @example * // Move the first column to the end for the table `#example` * var curr = $.fn.dataTable.ColReorder( '#example' ).fnOrder(); * var first = curr.shift(); * curr.push( first ); * $.fn.dataTable.ColReorder( '#example' ).fnOrder( curr ); * * @example * // Reverse the table's order * $.fn.dataTable.ColReorder( '#example' ).fnOrder( * $.fn.dataTable.ColReorder( '#example' ).fnOrder().reverse() * ); */ "fnOrder": function (set) { if (set === undefined) { var a = []; for (var i = 0, iLen = this.s.dt.aoColumns.length; i < iLen; i++) { a.push(this.s.dt.aoColumns[i]._ColReorder_iOrigCol); } return a; } this._fnOrderColumns(fnInvertKeyValues(set)); return this; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Constructor logic * @method _fnConstruct * @returns void * @private */ "_fnConstruct": function () { var that = this; var iLen = this.s.dt.aoColumns.length; var i; /* Columns discounted from reordering - counting left to right */ if (this.s.init.iFixedColumns) { this.s.fixed = this.s.init.iFixedColumns; } /* Columns discounted from reordering - counting right to left */ this.s.fixedRight = this.s.init.iFixedColumnsRight ? this.s.init.iFixedColumnsRight : 0; /* Drop callback initialisation option */ if (this.s.init.fnReorderCallback) { this.s.dropCallback = this.s.init.fnReorderCallback; } /* Add event handlers for the drag and drop, and also mark the original column order */ for (i = 0; i < iLen; i++) { if (i > this.s.fixed - 1 && i < iLen - this.s.fixedRight) { this._fnMouseListener(i, this.s.dt.aoColumns[i].nTh); } /* Mark the original column order for later reference */ this.s.dt.aoColumns[i]._ColReorder_iOrigCol = i; } /* State saving */ this.s.dt.oApi._fnCallbackReg(this.s.dt, 'aoStateSaveParams', function (oS, oData) { that._fnStateSave.call(that, oData); }, "ColReorder_State"); /* An initial column order has been specified */ var aiOrder = null; if (this.s.init.aiOrder) { aiOrder = this.s.init.aiOrder.slice(); } /* State loading, overrides the column order given */ if (this.s.dt.oLoadedState && typeof this.s.dt.oLoadedState.ColReorder != 'undefined' && this.s.dt.oLoadedState.ColReorder.length == this.s.dt.aoColumns.length) { aiOrder = this.s.dt.oLoadedState.ColReorder; } /* If we have an order to apply - do so */ if (aiOrder) { /* We might be called during or after the DataTables initialisation. If before, then we need * to wait until the draw is done, if after, then do what we need to do right away */ if (!that.s.dt._bInitComplete) { var bDone = false; this.s.dt.aoDrawCallback.push({ "fn": function () { if (!that.s.dt._bInitComplete && !bDone) { bDone = true; var resort = fnInvertKeyValues(aiOrder); that._fnOrderColumns.call(that, resort); } }, "sName": "ColReorder_Pre" }); } else { var resort = fnInvertKeyValues(aiOrder); that._fnOrderColumns.call(that, resort); } } else { this._fnSetColumnIndexes(); } }, /** * Set the column order from an array * @method _fnOrderColumns * @param array a An array of integers which dictate the column order that should be applied * @returns void * @private */ "_fnOrderColumns": function (a) { if (a.length != this.s.dt.aoColumns.length) { this.s.dt.oInstance.oApi._fnLog(this.s.dt, 1, "ColReorder - array reorder does not " + "match known number of columns. Skipping."); return; } for (var i = 0, iLen = a.length; i < iLen; i++) { var currIndex = $.inArray(i, a); if (i != currIndex) { /* Reorder our switching array */ fnArraySwitch(a, currIndex, i); /* Do the column reorder in the table */ this.s.dt.oInstance.fnColReorder(currIndex, i); } } /* When scrolling we need to recalculate the column sizes to allow for the shift */ if (this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "") { this.s.dt.oInstance.fnAdjustColumnSizing(); } /* Save the state */ this.s.dt.oInstance.oApi._fnSaveState(this.s.dt); this._fnSetColumnIndexes(); }, /** * Because we change the indexes of columns in the table, relative to their starting point * we need to reorder the state columns to what they are at the starting point so we can * then rearrange them again on state load! * @method _fnStateSave * @param object oState DataTables state * @returns string JSON encoded cookie string for DataTables * @private */ "_fnStateSave": function (oState) { var i, iLen, aCopy, iOrigColumn; var oSettings = this.s.dt; /* Sorting */ for (i = 0; i < oState.aaSorting.length; i++) { oState.aaSorting[i][0] = oSettings.aoColumns[ oState.aaSorting[i][0] ]._ColReorder_iOrigCol; } var aSearchCopy = $.extend(true, [], oState.aoSearchCols); oState.ColReorder = []; for (i = 0, iLen = oSettings.aoColumns.length; i < iLen; i++) { iOrigColumn = oSettings.aoColumns[i]._ColReorder_iOrigCol; /* Column filter */ oState.aoSearchCols[ iOrigColumn ] = aSearchCopy[i]; /* Visibility */ oState.abVisCols[ iOrigColumn ] = oSettings.aoColumns[i].bVisible; /* Column reordering */ oState.ColReorder.push(iOrigColumn); } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Mouse drop and drag */ /** * Add a mouse down listener to a particluar TH element * @method _fnMouseListener * @param int i Column index * @param element nTh TH element clicked on * @returns void * @private */ "_fnMouseListener": function (i, nTh) { var that = this; $(nTh).on('mousedown.ColReorder', function (e) { e.preventDefault(); that._fnMouseDown.call(that, e, nTh); }); }, /** * Mouse down on a TH element in the table header * @method _fnMouseDown * @param event e Mouse event * @param element nTh TH element to be dragged * @returns void * @private */ "_fnMouseDown": function (e, nTh) { var that = this; /* Store information about the mouse position */ var target = $(e.target).closest('th, td'); var offset = target.offset(); var idx = parseInt($(nTh).attr('data-column-index'), 10); if (idx === undefined) { return; } this.s.mouse.startX = e.pageX; this.s.mouse.startY = e.pageY; this.s.mouse.offsetX = e.pageX - offset.left; this.s.mouse.offsetY = e.pageY - offset.top; this.s.mouse.target = this.s.dt.aoColumns[ idx ].nTh;//target[0]; this.s.mouse.targetIndex = idx; this.s.mouse.fromIndex = idx; this._fnRegions(); /* Add event handlers to the document */ $(document) .on('mousemove.ColReorder', function (e) { that._fnMouseMove.call(that, e); }) .on('mouseup.ColReorder', function (e) { that._fnMouseUp.call(that, e); }); }, /** * Deal with a mouse move event while dragging a node * @method _fnMouseMove * @param event e Mouse event * @returns void * @private */ "_fnMouseMove": function (e) { var that = this; if (this.dom.drag === null) { /* Only create the drag element if the mouse has moved a specific distance from the start * point - this allows the user to make small mouse movements when sorting and not have a * possibly confusing drag element showing up */ if (Math.pow( Math.pow(e.pageX - this.s.mouse.startX, 2) + Math.pow(e.pageY - this.s.mouse.startY, 2), 0.5) < 5) { return; } this._fnCreateDragNode(); } /* Position the element - we respect where in the element the click occured */ this.dom.drag.css({ left: e.pageX - this.s.mouse.offsetX, top: e.pageY - this.s.mouse.offsetY }); /* Based on the current mouse position, calculate where the insert should go */ var bSet = false; var lastToIndex = this.s.mouse.toIndex; for (var i = 1, iLen = this.s.aoTargets.length; i < iLen; i++) { if (e.pageX < this.s.aoTargets[i - 1].x + ((this.s.aoTargets[i].x - this.s.aoTargets[i - 1].x) / 2)) { this.dom.pointer.css('left', this.s.aoTargets[i - 1].x); this.s.mouse.toIndex = this.s.aoTargets[i - 1].to; bSet = true; break; } } // The insert element wasn't positioned in the array (less than // operator), so we put it at the end if (!bSet) { this.dom.pointer.css('left', this.s.aoTargets[this.s.aoTargets.length - 1].x); this.s.mouse.toIndex = this.s.aoTargets[this.s.aoTargets.length - 1].to; } // Perform reordering if realtime updating is on and the column has moved if (this.s.init.bRealtime && lastToIndex !== this.s.mouse.toIndex) { this.s.dt.oInstance.fnColReorder(this.s.mouse.fromIndex, this.s.mouse.toIndex); this.s.mouse.fromIndex = this.s.mouse.toIndex; this._fnRegions(); } }, /** * Finish off the mouse drag and insert the column where needed * @method _fnMouseUp * @param event e Mouse event * @returns void * @private */ "_fnMouseUp": function (e) { var that = this; $(document).off('mousemove.ColReorder mouseup.ColReorder'); if (this.dom.drag !== null) { /* Remove the guide elements */ this.dom.drag.remove(); this.dom.pointer.remove(); this.dom.drag = null; this.dom.pointer = null; /* Actually do the reorder */ this.s.dt.oInstance.fnColReorder(this.s.mouse.fromIndex, this.s.mouse.toIndex); this._fnSetColumnIndexes(); /* When scrolling we need to recalculate the column sizes to allow for the shift */ if (this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "") { this.s.dt.oInstance.fnAdjustColumnSizing(); } if (this.s.dropCallback !== null) { this.s.dropCallback.call(this); } /* Save the state */ this.s.dt.oInstance.oApi._fnSaveState(this.s.dt); } }, /** * Calculate a cached array with the points of the column inserts, and the * 'to' points * @method _fnRegions * @returns void * @private */ "_fnRegions": function () { var aoColumns = this.s.dt.aoColumns; this.s.aoTargets.splice(0, this.s.aoTargets.length); this.s.aoTargets.push({ "x": $(this.s.dt.nTable).offset().left, "to": 0 }); var iToPoint = 0; for (var i = 0, iLen = aoColumns.length; i < iLen; i++) { /* For the column / header in question, we want it's position to remain the same if the * position is just to it's immediate left or right, so we only incremement the counter for * other columns */ if (i != this.s.mouse.fromIndex) { iToPoint++; } if (aoColumns[i].bVisible) { this.s.aoTargets.push({ "x": $(aoColumns[i].nTh).offset().left + $(aoColumns[i].nTh).outerWidth(), "to": iToPoint }); } } /* Disallow columns for being reordered by drag and drop, counting right to left */ if (this.s.fixedRight !== 0) { this.s.aoTargets.splice(this.s.aoTargets.length - this.s.fixedRight); } /* Disallow columns for being reordered by drag and drop, counting left to right */ if (this.s.fixed !== 0) { this.s.aoTargets.splice(0, this.s.fixed); } }, /** * Copy the TH element that is being drags so the user has the idea that they are actually * moving it around the page. * @method _fnCreateDragNode * @returns void * @private */ "_fnCreateDragNode": function () { var scrolling = this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== ""; var origCell = this.s.dt.aoColumns[ this.s.mouse.targetIndex ].nTh; var origTr = origCell.parentNode; var origThead = origTr.parentNode; var origTable = origThead.parentNode; var cloneCell = $(origCell).clone(); // This is a slightly odd combination of jQuery and DOM, but it is the // fastest and least resource intensive way I could think of cloning // the table with just a single header cell in it. this.dom.drag = $(origTable.cloneNode(false)) .addClass('DTCR_clonedTable') .append( origThead.cloneNode(false).appendChild( origTr.cloneNode(false).appendChild( cloneCell[0] ) ) ) .css({ position: 'absolute', top: 0, left: 0, width: $(origCell).outerWidth(), height: $(origCell).outerHeight() }) .appendTo('body'); this.dom.pointer = $('<div></div>') .addClass('DTCR_pointer') .css({ position: 'absolute', top: scrolling ? $('div.dataTables_scroll', this.s.dt.nTableWrapper).offset().top : $(this.s.dt.nTable).offset().top, height: scrolling ? $('div.dataTables_scroll', this.s.dt.nTableWrapper).height() : $(this.s.dt.nTable).height() }) .appendTo('body'); }, /** * Clean up ColReorder memory references and event handlers * @method _fnDestroy * @returns void * @private */ "_fnDestroy": function () { var i, iLen; for (i = 0, iLen = this.s.dt.aoDrawCallback.length; i < iLen; i++) { if (this.s.dt.aoDrawCallback[i].sName === 'ColReorder_Pre') { this.s.dt.aoDrawCallback.splice(i, 1); break; } } $(this.s.dt.nTHead).find('*').off('.ColReorder'); $.each(this.s.dt.aoColumns, function (i, column) { $(column.nTh).removeAttr('data-column-index'); }); this.s.dt._colReorder = null; this.s = null; }, /** * Add a data attribute to the column headers, so we know the index of * the row to be reordered. This allows fast detection of the index, and * for this plug-in to work with FixedHeader which clones the nodes. * @private */ "_fnSetColumnIndexes": function () { $.each(this.s.dt.aoColumns, function (i, column) { $(column.nTh).attr('data-column-index', i); }); } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static parameters * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * ColReorder default settings for initialisation * @namespace * @static */ ColReorder.defaults = { /** * Predefined ordering for the columns that will be applied automatically * on initialisation. If not specified then the order that the columns are * found to be in the HTML is the order used. * @type array * @default null * @static * @example * // Using the `oColReorder` option in the DataTables options object * $('#example').dataTable( { * "sDom": 'Rlfrtip', * "oColReorder": { * "aiOrder": [ 4, 3, 2, 1, 0 ] * } * } ); * * @example * // Using `new` constructor * $('#example').dataTable() * * new $.fn.dataTable.ColReorder( '#example', { * "aiOrder": [ 4, 3, 2, 1, 0 ] * } ); */ aiOrder: null, /** * Redraw the table's column ordering as the end user draws the column * (`true`) or wait until the mouse is released (`false` - default). Note * that this will perform a redraw on each reordering, which involves an * Ajax request each time if you are using server-side processing in * DataTables. * @type boolean * @default false * @static * @example * // Using the `oColReorder` option in the DataTables options object * $('#example').dataTable( { * "sDom": 'Rlfrtip', * "oColReorder": { * "bRealtime": true * } * } ); * * @example * // Using `new` constructor * $('#example').dataTable() * * new $.fn.dataTable.ColReorder( '#example', { * "bRealtime": true * } ); */ bRealtime: false, /** * Indicate how many columns should be fixed in position (counting from the * left). This will typically be 1 if used, but can be as high as you like. * @type int * @default 0 * @static * @example * // Using the `oColReorder` option in the DataTables options object * $('#example').dataTable( { * "sDom": 'Rlfrtip', * "oColReorder": { * "iFixedColumns": 1 * } * } ); * * @example * // Using `new` constructor * $('#example').dataTable() * * new $.fn.dataTable.ColReorder( '#example', { * "iFixedColumns": 1 * } ); */ iFixedColumns: 0, /** * As `iFixedColumnsRight` but counting from the right. * @type int * @default 0 * @static * @example * // Using the `oColReorder` option in the DataTables options object * $('#example').dataTable( { * "sDom": 'Rlfrtip', * "oColReorder": { * "iFixedColumnsRight": 1 * } * } ); * * @example * // Using `new` constructor * $('#example').dataTable() * * new $.fn.dataTable.ColReorder( '#example', { * "iFixedColumnsRight": 1 * } ); */ iFixedColumnsRight: 0, /** * Callback function that is fired when columns are reordered * @type function():void * @default null * @static * @example * // Using the `oColReorder` option in the DataTables options object * $('#example').dataTable( { * "sDom": 'Rlfrtip', * "oColReorder": { * "fnReorderCallback": function () { * alert( 'Columns reordered' ); * } * } * } ); * * @example * // Using `new` constructor * $('#example').dataTable() * * new $.fn.dataTable.ColReorder( '#example', { * "fnReorderCallback": function () { * alert( 'Columns reordered' ); * } * } ); */ fnReorderCallback: null }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * ColReorder version * @constant version * @type String * @default As code */ ColReorder.version = "1.1.0"; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables interfaces * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ // Expose $.fn.dataTable.ColReorder = ColReorder; $.fn.DataTable.ColReorder = ColReorder; // Register a new feature with DataTables if (typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.9.3')) { $.fn.dataTableExt.aoFeatures.push({ "fnInit": function (settings) { var table = settings.oInstance; if (!settings._colReorder) { var dtInit = settings.oInit; var opts = dtInit.colReorder || dtInit.oColReorder || {}; new ColReorder(settings, opts); } else { table.oApi._fnLog(settings, 1, "ColReorder attempted to initialise twice. Ignoring second"); } return null; /* No node for DataTables to insert */ }, "cFeature": "R", "sFeature": "ColReorder" }); } else { alert("Warning: ColReorder requires DataTables 1.9.3 or greater - www.datatables.net/download"); } // API augmentation if ($.fn.dataTable.Api) { $.fn.dataTable.Api.register('colReorder.reset()', function () { return this.iterator('table', function (ctx) { ctx._colReorder.fnReset(); }); }); $.fn.dataTable.Api.register('colReorder.order()', function (set) { if (set) { return this.iterator('table', function (ctx) { ctx._colReorder.fnOrder(set); }); } return this.context.length ? this.context[0]._colReorder.fnOrder() : null; }); } return ColReorder; }; // /factory // Otherwise simply initialise as normal, stopping multiple evaluation factory(jQuery, jQuery.fn.dataTable); })(window, document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-colReorder.js
jquery-dataTables-colReorder.js
(function ($, window, undefined) { '$:nomunge'; // Used by YUI compressor. // A jQuery object containing all non-window elements to which the resize // event is bound. var elems = $([]), // Extend $.resize if it already exists, otherwise create it. jq_resize = $.resize = $.extend($.resize, {}), timeout_id, // Reused strings. str_setTimeout = 'setTimeout', str_resize = 'resize', str_data = str_resize + '-special-event', str_delay = 'delay', str_throttle = 'throttleWindow'; // Property: jQuery.resize.delay // // The numeric interval (in milliseconds) at which the resize event polling // loop executes. Defaults to 250. jq_resize[ str_delay ] = 250; // Property: jQuery.resize.throttleWindow // // Throttle the native window object resize event to fire no more than once // every <jQuery.resize.delay> milliseconds. Defaults to true. // // Because the window object has its own resize event, it doesn't need to be // provided by this plugin, and its execution can be left entirely up to the // browser. However, since certain browsers fire the resize event continuously // while others do not, enabling this will throttle the window resize event, // making event behavior consistent across all elements in all browsers. // // While setting this property to false will disable window object resize // event throttling, please note that this property must be changed before any // window object resize event callbacks are bound. jq_resize[ str_throttle ] = true; // Event: resize event // // Fired when an element's width or height changes. Because browsers only // provide this event for the window element, for other elements a polling // loop is initialized, running every <jQuery.resize.delay> milliseconds // to see if elements' dimensions have changed. You may bind with either // .resize( fn ) or .bind( "resize", fn ), and unbind with .unbind( "resize" ). // // Usage: // // > jQuery('selector').bind( 'resize', function(e) { // > // element's width or height has changed! // > ... // > }); // // Additional Notes: // // * The polling loop is not created until at least one callback is actually // bound to the 'resize' event, and this single polling loop is shared // across all elements. // // Double firing issue in jQuery 1.3.2: // // While this plugin works in jQuery 1.3.2, if an element's event callbacks // are manually triggered via .trigger( 'resize' ) or .resize() those // callbacks may double-fire, due to limitations in the jQuery 1.3.2 special // events system. This is not an issue when using jQuery 1.4+. // // > // While this works in jQuery 1.4+ // > $(elem).css({ width: new_w, height: new_h }).resize(); // > // > // In jQuery 1.3.2, you need to do this: // > var elem = $(elem); // > elem.css({ width: new_w, height: new_h }); // > elem.data( 'resize-special-event', { width: elem.width(), height: elem.height() } ); // > elem.resize(); $.event.special[ str_resize ] = { // Called only when the first 'resize' event callback is bound per element. setup: function () { // Since window has its own native 'resize' event, return false so that // jQuery will bind the event using DOM methods. Since only 'window' // objects have a .setTimeout method, this should be a sufficient test. // Unless, of course, we're throttling the 'resize' event for window. if (!jq_resize[ str_throttle ] && this[ str_setTimeout ]) { return false; } var elem = $(this); // Add this element to the list of internal elements to monitor. elems = elems.add(elem); // Initialize data store on the element. $.data(this, str_data, { w: elem.width(), h: elem.height() }); // If this is the first element added, start the polling loop. if (elems.length === 1) { loopy(); } }, // Called only when the last 'resize' event callback is unbound per element. teardown: function () { // Since window has its own native 'resize' event, return false so that // jQuery will unbind the event using DOM methods. Since only 'window' // objects have a .setTimeout method, this should be a sufficient test. // Unless, of course, we're throttling the 'resize' event for window. if (!jq_resize[ str_throttle ] && this[ str_setTimeout ]) { return false; } var elem = $(this); // Remove this element from the list of internal elements to monitor. elems = elems.not(elem); // Remove any data stored on the element. elem.removeData(str_data); // If this is the last element removed, stop the polling loop. if (!elems.length) { clearTimeout(timeout_id); } }, // Called every time a 'resize' event callback is bound per element (new in // jQuery 1.4). add: function (handleObj) { // Since window has its own native 'resize' event, return false so that // jQuery doesn't modify the event object. Unless, of course, we're // throttling the 'resize' event for window. if (!jq_resize[ str_throttle ] && this[ str_setTimeout ]) { return false; } var old_handler; // The new_handler function is executed every time the event is triggered. // This is used to update the internal element data store with the width // and height when the event is triggered manually, to avoid double-firing // of the event callback. See the "Double firing issue in jQuery 1.3.2" // comments above for more information. function new_handler(e, w, h) { var elem = $(this), data = $.data(this, str_data); // If called from the polling loop, w and h will be passed in as // arguments. If called manually, via .trigger( 'resize' ) or .resize(), // those values will need to be computed. data.w = w !== undefined ? w : elem.width(); data.h = h !== undefined ? h : elem.height(); old_handler.apply(this, arguments); }; // This may seem a little complicated, but it normalizes the special event // .add method between jQuery 1.4/1.4.1 and 1.4.2+ if ($.isFunction(handleObj)) { // 1.4, 1.4.1 old_handler = handleObj; return new_handler; } else { // 1.4.2+ old_handler = handleObj.handler; handleObj.handler = new_handler; } } }; function loopy() { // Start the polling loop, asynchronously. timeout_id = window[ str_setTimeout ](function () { // Iterate over all elements to which the 'resize' event is bound. elems.each(function () { var elem = $(this), width = elem.width(), height = elem.height(), data = $.data(this, str_data); // If element size has changed since the last time, update the element // data store and trigger the 'resize' event. if (width !== data.w || height !== data.h) { elem.trigger(str_resize, [ data.w = width, data.h = height ]); } }); // Loop. loopy(); }, jq_resize[ str_delay ]); }; })(jQuery, this);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-resize.js
jquery-resize.js
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof exports?require("jquery"):jQuery)}(function(e){var f,d=navigator.userAgent,c=/iphone/i.test(d),a=/chrome/i.test(d),b=/android/i.test(d);e.mask={definitions:{"9":"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},autoclear:!0,dataName:"rawMaskFn",placeholder:"_"},e.fn.extend({caret:function(i,g){var h;if(0!==this.length&&!this.is(":hidden")){return"number"==typeof i?(g="number"==typeof g?g:i,this.each(function(){this.setSelectionRange?this.setSelectionRange(i,g):this.createTextRange&&(h=this.createTextRange(),h.collapse(!0),h.moveEnd("character",g),h.moveStart("character",i),h.select())})):(this[0].setSelectionRange?(i=this[0].selectionStart,g=this[0].selectionEnd):document.selection&&document.selection.createRange&&(h=document.selection.createRange(),i=0-h.duplicate().moveStart("character",-100000),g=i+h.text.length),{begin:i,end:g})}},unmask:function(){return this.trigger("unmask")},mask:function(q,j){var n,k,h,i,p,g,l,o;if(!q&&this.length>0){n=e(this[0]);var m=n.data(e.mask.dataName);return m?m():void 0}return j=e.extend({autoclear:e.mask.autoclear,placeholder:e.mask.placeholder,completed:null},j),k=e.mask.definitions,h=[],i=l=q.length,p=null,e.each(q.split(""),function(r,s){"?"==s?(l--,i=r):k[s]?(h.push(new RegExp(k[s])),null===p&&(p=h.length-1),i>r&&(g=h.length-1)):h.push(null)}),this.trigger("unmask").each(function(){function r(){if(j.completed){for(var I=p;g>=I;I++){if(h[I]&&w[I]===E(I)){return}}j.completed.call(F)}}function E(I){return j.placeholder.charAt(I<j.placeholder.length?I:0)}function D(I){for(;++I<l&&!h[I];){}return I}function y(I){for(;--I>=0&&!h[I];){}return I}function v(L,I){var K,J;if(!(0>L)){for(K=L,J=D(I);l>K;K++){if(h[K]){if(!(l>J&&h[K].test(w[J]))){break}w[K]=w[J],w[J]=E(J),J=D(J)}}C(),F.caret(Math.max(p,L))}}function s(M){var K,L,I,J;for(K=M,L=E(M);l>K;K++){if(h[K]){if(I=D(K),J=w[K],w[K]=L,!(l>I&&h[I].test(J))){break}L=J}}}function A(){var I=F.val(),J=F.caret();if(o&&o.length&&o.length>I.length){for(u(!0);J.begin>0&&!h[J.begin-1];){J.begin--}if(0===J.begin){for(;J.begin<p&&!h[J.begin];){J.begin++}}F.caret(J.begin,J.begin)}else{for(u(!0);J.begin<l&&!h[J.begin];){J.begin++}F.caret(J.begin,J.begin)}r()}function x(){u(),F.val()!=H&&F.change()}function z(L){if(!F.prop("readonly")){var M,K,I,J=L.which||L.keyCode;o=F.val(),8===J||46===J||c&&127===J?(M=F.caret(),K=M.begin,I=M.end,I-K===0&&(K=46!==J?y(K):I=D(K-1),I=46===J?D(I):I),t(K,I),v(K,I-1),L.preventDefault()):13===J?x.call(this,L):27===J&&(F.val(H),F.caret(0,u()),L.preventDefault())}}function G(M){if(!F.prop("readonly")){var L,O,K,I=M.which||M.keyCode,N=F.caret();if(!(M.ctrlKey||M.altKey||M.metaKey||32>I)&&I&&13!==I){if(N.end-N.begin!==0&&(t(N.begin,N.end),v(N.begin,N.end-1)),L=D(N.begin-1),l>L&&(O=String.fromCharCode(I),h[L].test(O))){if(s(L),w[L]=O,C(),K=D(L),b){var J=function(){e.proxy(e.fn.caret,F,K)()};setTimeout(J,0)}else{F.caret(K)}N.begin<=g&&r()}M.preventDefault()}}}function t(K,I){var J;for(J=K;I>J&&l>J;J++){h[J]&&(w[J]=E(J))}}function C(){F.val(w.join(""))}function u(J){var I,N,M,L=F.val(),K=-1;for(I=0,M=0;l>I;I++){if(h[I]){for(w[I]=E(I);M++<L.length;){if(N=L.charAt(M-1),h[I].test(N)){w[I]=N,K=I;break}}if(M>L.length){t(I+1,l);break}}else{w[I]===L.charAt(M)&&M++,i>I&&(K=I)}}return J?C():i>K+1?j.autoclear||w.join("")===B?(F.val()&&F.val(""),t(0,l)):C():(C(),F.val(F.val().substring(0,K+1))),i?I:p}var F=e(this),w=e.map(q.split(""),function(J,I){return"?"!=J?k[J]?E(I):J:void 0}),B=w.join(""),H=F.val();F.data(e.mask.dataName,function(){return e.map(w,function(J,I){return h[I]&&J!=E(I)?J:null}).join("")}),F.one("unmask",function(){F.off(".mask").removeData(e.mask.dataName)}).on("focus.mask",function(){if(!F.prop("readonly")){clearTimeout(f);var I;H=F.val(),I=u(),f=setTimeout(function(){F.get(0)===document.activeElement&&(C(),I==q.replace("?","").length?F.caret(0,I):F.caret(I))},10)}}).on("blur.mask",x).on("keydown.mask",z).on("keypress.mask",G).on("input.mask paste.mask",function(){F.prop("readonly")||setTimeout(function(){var I=u(!0);F.caret(I),r()},0)}),a&&b&&F.off("input.mask").on("input.mask",A),u()})}})});
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-maskedinput-1.4.1.min.js
jquery-maskedinput-1.4.1.min.js
* @summary AutoFill * @description Add Excel like click and drag auto-fill options to DataTables * @version 1.2.0 * @file dataTables.autoFill.js * @author SpryMedia Ltd (www.sprymedia.co.uk) * @contact www.sprymedia.co.uk/contact * @copyright Copyright 2010-2014 SpryMedia Ltd. * * This source file is free software, available under the following license: * MIT license - http://datatables.net/license/mit * * 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 */ (function (window, document, undefined) { var factory = function ($, DataTable) { "use strict"; /** * AutoFill provides Excel like auto-fill features for a DataTable * * @class AutoFill * @constructor * @param {object} oTD DataTables settings object * @param {object} oConfig Configuration object for AutoFill */ var AutoFill = function (oDT, oConfig) { /* Sanity check that we are a new instance */ if (!(this instanceof AutoFill)) { throw( "Warning: AutoFill must be initialised with the keyword 'new'" ); } if (!$.fn.dataTableExt.fnVersionCheck('1.7.0')) { throw( "Warning: AutoFill requires DataTables 1.7 or greater"); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ this.c = {}; /** * @namespace Settings object which contains customisable information for AutoFill instance */ this.s = { /** * @namespace Cached information about the little dragging icon (the filler) */ "filler": { "height": 0, "width": 0 }, /** * @namespace Cached information about the border display */ "border": { "width": 2 }, /** * @namespace Store for live information for the current drag */ "drag": { "startX": -1, "startY": -1, "startTd": null, "endTd": null, "dragging": false }, /** * @namespace Data cache for information that we need for scrolling the screen when we near * the edges */ "screen": { "interval": null, "y": 0, "height": 0, "scrollTop": 0 }, /** * @namespace Data cache for the position of the DataTables scrolling element (when scrolling * is enabled) */ "scroller": { "top": 0, "bottom": 0 }, /** * @namespace Information stored for each column. An array of objects */ "columns": [] }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { "table": null, "filler": null, "borderTop": null, "borderRight": null, "borderBottom": null, "borderLeft": null, "currentTarget": null }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @method fnSettings * @returns {object} AutoFill settings object */ this.fnSettings = function () { return this.s; }; /* Constructor logic */ this._fnInit(oDT, oConfig); return this; }; AutoFill.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Initialisation * @method _fnInit * @param {object} dt DataTables settings object * @param {object} config Configuration object for AutoFill * @returns void */ "_fnInit": function (dt, config) { var that = this, i, iLen; // Use DataTables API to get the settings allowing selectors, instances // etc to be used, or for backwards compatibility get from the old // fnSettings method this.s.dt = DataTable.Api ? new DataTable.Api(dt).settings()[0] : dt.fnSettings(); this.s.init = config || {}; this.dom.table = this.s.dt.nTable; $.extend(true, this.c, AutoFill.defaults, config); /* Add and configure the columns */ this._initColumns(); /* Auto Fill click and drag icon */ var filler = $('<div/>', { 'class': 'AutoFill_filler' }) .appendTo('body'); this.dom.filler = filler[0]; // Get the height / width of the click element this.s.filler.height = filler.height(); this.s.filler.width = filler.width(); filler[0].style.display = "none"; /* Border display - one div for each side. We can't just use a single * one with a border, as we want the events to effectively pass through * the transparent bit of the box */ var border; var appender = document.body; if (that.s.dt.oScroll.sY !== "") { that.s.dt.nTable.parentNode.style.position = "relative"; appender = that.s.dt.nTable.parentNode; } border = $('<div/>', { "class": "AutoFill_border" }); this.dom.borderTop = border.clone().appendTo(appender)[0]; this.dom.borderRight = border.clone().appendTo(appender)[0]; this.dom.borderBottom = border.clone().appendTo(appender)[0]; this.dom.borderLeft = border.clone().appendTo(appender)[0]; /* Events */ filler.on('mousedown.DTAF', function (e) { this.onselectstart = function () { return false; }; that._fnFillerDragStart.call(that, e); return false; }); $('tbody', this.dom.table).on( 'mouseover.DTAF mouseout.DTAF', '>tr>td, >tr>th', function (e) { that._fnFillerDisplay.call(that, e); } ); $(this.dom.table).on('destroy.dt.DTAF', function () { filler.off('mousedown.DTAF').remove(); $('tbody', this.dom.table).off('mouseover.DTAF mouseout.DTAF'); }); }, _initColumns: function () { var that = this; var i, ien; var dt = this.s.dt; var config = this.s.init; for (i = 0, ien = dt.aoColumns.length; i < ien; i++) { this.s.columns[i] = $.extend(true, {}, AutoFill.defaults.column); } dt.oApi._fnApplyColumnDefs( dt, config.aoColumnDefs || config.columnDefs, config.aoColumns || config.columns, function (colIdx, def) { that._fnColumnOptions(colIdx, def); } ); // For columns which don't have read, write, step functions defined, // use the default ones for (i = 0, ien = dt.aoColumns.length; i < ien; i++) { var column = this.s.columns[i]; if (!column.read) { column.read = this._fnReadCell; } if (!column.write) { column.read = this._fnWriteCell; } if (!column.step) { column.read = this._fnStep; } } }, "_fnColumnOptions": function (i, opts) { var column = this.s.columns[ i ]; var set = function (outProp, inProp) { if (opts[ inProp[0] ] !== undefined) { column[ outProp ] = opts[ inProp[0] ]; } if (opts[ inProp[1] ] !== undefined) { column[ outProp ] = opts[ inProp[1] ]; } }; // Compatibility with the old Hungarian style of notation set('enable', ['bEnable', 'enable']); set('read', ['fnRead', 'read']); set('write', ['fnWrite', 'write']); set('step', ['fnStep', 'step']); set('increment', ['bIncrement', 'increment']); }, /** * Find out the coordinates of a given TD cell in a table * @method _fnTargetCoords * @param {Node} nTd * @returns {Object} x and y properties, for the position of the cell in the tables DOM */ "_fnTargetCoords": function (nTd) { var nTr = $(nTd).parents('tr')[0]; var position = this.s.dt.oInstance.fnGetPosition(nTd); return { "x": $('td', nTr).index(nTd), "y": $('tr', nTr.parentNode).index(nTr), "row": position[0], "column": position[2] }; }, /** * Display the border around one or more cells (from start to end) * @method _fnUpdateBorder * @param {Node} nStart Starting cell * @param {Node} nEnd Ending cell * @returns void */ "_fnUpdateBorder": function (nStart, nEnd) { var border = this.s.border.width, offsetStart = $(nStart).offset(), offsetEnd = $(nEnd).offset(), x1 = offsetStart.left - border, x2 = offsetEnd.left + $(nEnd).outerWidth(), y1 = offsetStart.top - border, y2 = offsetEnd.top + $(nEnd).outerHeight(), width = offsetEnd.left + $(nEnd).outerWidth() - offsetStart.left + (2 * border), height = offsetEnd.top + $(nEnd).outerHeight() - offsetStart.top + (2 * border), oStyle; // Recalculate start and end (when dragging "backwards") if (offsetStart.left > offsetEnd.left) { x1 = offsetEnd.left - border; x2 = offsetStart.left + $(nStart).outerWidth(); width = offsetStart.left + $(nStart).outerWidth() - offsetEnd.left + (2 * border); } if (this.s.dt.oScroll.sY !== "") { /* The border elements are inside the DT scroller - so position relative to that */ var offsetScroll = $(this.s.dt.nTable.parentNode).offset(), scrollTop = $(this.s.dt.nTable.parentNode).scrollTop(), scrollLeft = $(this.s.dt.nTable.parentNode).scrollLeft(); x1 -= offsetScroll.left - scrollLeft; x2 -= offsetScroll.left - scrollLeft; y1 -= offsetScroll.top - scrollTop; y2 -= offsetScroll.top - scrollTop; } /* Top */ oStyle = this.dom.borderTop.style; oStyle.top = y1 + "px"; oStyle.left = x1 + "px"; oStyle.height = this.s.border.width + "px"; oStyle.width = width + "px"; /* Bottom */ oStyle = this.dom.borderBottom.style; oStyle.top = y2 + "px"; oStyle.left = x1 + "px"; oStyle.height = this.s.border.width + "px"; oStyle.width = width + "px"; /* Left */ oStyle = this.dom.borderLeft.style; oStyle.top = y1 + "px"; oStyle.left = x1 + "px"; oStyle.height = height + "px"; oStyle.width = this.s.border.width + "px"; /* Right */ oStyle = this.dom.borderRight.style; oStyle.top = y1 + "px"; oStyle.left = x2 + "px"; oStyle.height = height + "px"; oStyle.width = this.s.border.width + "px"; }, /** * Mouse down event handler for starting a drag * @method _fnFillerDragStart * @param {Object} e Event object * @returns void */ "_fnFillerDragStart": function (e) { var that = this; var startingTd = this.dom.currentTarget; this.s.drag.dragging = true; that.dom.borderTop.style.display = "block"; that.dom.borderRight.style.display = "block"; that.dom.borderBottom.style.display = "block"; that.dom.borderLeft.style.display = "block"; var coords = this._fnTargetCoords(startingTd); this.s.drag.startX = coords.x; this.s.drag.startY = coords.y; this.s.drag.startTd = startingTd; this.s.drag.endTd = startingTd; this._fnUpdateBorder(startingTd, startingTd); $(document).bind('mousemove.AutoFill', function (e) { that._fnFillerDragMove.call(that, e); }); $(document).bind('mouseup.AutoFill', function (e) { that._fnFillerFinish.call(that, e); }); /* Scrolling information cache */ this.s.screen.y = e.pageY; this.s.screen.height = $(window).height(); this.s.screen.scrollTop = $(document).scrollTop(); if (this.s.dt.oScroll.sY !== "") { this.s.scroller.top = $(this.s.dt.nTable.parentNode).offset().top; this.s.scroller.bottom = this.s.scroller.top + $(this.s.dt.nTable.parentNode).height(); } /* Scrolling handler - we set an interval (which is cancelled on mouse up) which will fire * regularly and see if we need to do any scrolling */ this.s.screen.interval = setInterval(function () { var iScrollTop = $(document).scrollTop(); var iScrollDelta = iScrollTop - that.s.screen.scrollTop; that.s.screen.y += iScrollDelta; if (that.s.screen.height - that.s.screen.y + iScrollTop < 50) { $('html, body').animate({ "scrollTop": iScrollTop + 50 }, 240, 'linear'); } else if (that.s.screen.y - iScrollTop < 50) { $('html, body').animate({ "scrollTop": iScrollTop - 50 }, 240, 'linear'); } if (that.s.dt.oScroll.sY !== "") { if (that.s.screen.y > that.s.scroller.bottom - 50) { $(that.s.dt.nTable.parentNode).animate({ "scrollTop": $(that.s.dt.nTable.parentNode).scrollTop() + 50 }, 240, 'linear'); } else if (that.s.screen.y < that.s.scroller.top + 50) { $(that.s.dt.nTable.parentNode).animate({ "scrollTop": $(that.s.dt.nTable.parentNode).scrollTop() - 50 }, 240, 'linear'); } } }, 250); }, /** * Mouse move event handler for during a move. See if we want to update the display based on the * new cursor position * @method _fnFillerDragMove * @param {Object} e Event object * @returns void */ "_fnFillerDragMove": function (e) { if (e.target && e.target.nodeName.toUpperCase() == "TD" && e.target != this.s.drag.endTd) { var coords = this._fnTargetCoords(e.target); if (this.c.mode == "y" && coords.x != this.s.drag.startX) { e.target = $('tbody>tr:eq(' + coords.y + ')>td:eq(' + this.s.drag.startX + ')', this.dom.table)[0]; } if (this.c.mode == "x" && coords.y != this.s.drag.startY) { e.target = $('tbody>tr:eq(' + this.s.drag.startY + ')>td:eq(' + coords.x + ')', this.dom.table)[0]; } if (this.c.mode == "either") { if (coords.x != this.s.drag.startX) { e.target = $('tbody>tr:eq(' + this.s.drag.startY + ')>td:eq(' + coords.x + ')', this.dom.table)[0]; } else if (coords.y != this.s.drag.startY) { e.target = $('tbody>tr:eq(' + coords.y + ')>td:eq(' + this.s.drag.startX + ')', this.dom.table)[0]; } } // update coords if (this.c.mode !== "both") { coords = this._fnTargetCoords(e.target); } var drag = this.s.drag; drag.endTd = e.target; if (coords.y >= this.s.drag.startY) { this._fnUpdateBorder(drag.startTd, drag.endTd); } else { this._fnUpdateBorder(drag.endTd, drag.startTd); } this._fnFillerPosition(e.target); } /* Update the screen information so we can perform scrolling */ this.s.screen.y = e.pageY; this.s.screen.scrollTop = $(document).scrollTop(); if (this.s.dt.oScroll.sY !== "") { this.s.scroller.scrollTop = $(this.s.dt.nTable.parentNode).scrollTop(); this.s.scroller.top = $(this.s.dt.nTable.parentNode).offset().top; this.s.scroller.bottom = this.s.scroller.top + $(this.s.dt.nTable.parentNode).height(); } }, /** * Mouse release handler - end the drag and take action to update the cells with the needed values * @method _fnFillerFinish * @param {Object} e Event object * @returns void */ "_fnFillerFinish": function (e) { var that = this, i, iLen, j; $(document).unbind('mousemove.AutoFill mouseup.AutoFill'); this.dom.borderTop.style.display = "none"; this.dom.borderRight.style.display = "none"; this.dom.borderBottom.style.display = "none"; this.dom.borderLeft.style.display = "none"; this.s.drag.dragging = false; clearInterval(this.s.screen.interval); var cells = []; var table = this.dom.table; var coordsStart = this._fnTargetCoords(this.s.drag.startTd); var coordsEnd = this._fnTargetCoords(this.s.drag.endTd); var columnIndex = function (visIdx) { return that.s.dt.oApi._fnVisibleToColumnIndex(that.s.dt, visIdx); }; // xxx - urgh - there must be a way of reducing this... if (coordsStart.y <= coordsEnd.y) { for (i = coordsStart.y; i <= coordsEnd.y; i++) { if (coordsStart.x <= coordsEnd.x) { for (j = coordsStart.x; j <= coordsEnd.x; j++) { cells.push({ node: $('tbody>tr:eq(' + i + ')>td:eq(' + j + ')', table)[0], x: j - coordsStart.x, y: i - coordsStart.y, colIdx: columnIndex(j) }); } } else { for (j = coordsStart.x; j >= coordsEnd.x; j--) { cells.push({ node: $('tbody>tr:eq(' + i + ')>td:eq(' + j + ')', table)[0], x: j - coordsStart.x, y: i - coordsStart.y, colIdx: columnIndex(j) }); } } } } else { for (i = coordsStart.y; i >= coordsEnd.y; i--) { if (coordsStart.x <= coordsEnd.x) { for (j = coordsStart.x; j <= coordsEnd.x; j++) { cells.push({ node: $('tbody>tr:eq(' + i + ')>td:eq(' + j + ')', table)[0], x: j - coordsStart.x, y: i - coordsStart.y, colIdx: columnIndex(j) }); } } else { for (j = coordsStart.x; j >= coordsEnd.x; j--) { cells.push({ node: $('tbody>tr:eq(' + i + ')>td:eq(' + j + ')', table)[0], x: coordsStart.x - j, y: coordsStart.y - i, colIdx: columnIndex(j) }); } } } } // An auto-fill requires 2 or more cells if (cells.length <= 1) { return; } var edited = []; var previous; for (i = 0, iLen = cells.length; i < iLen; i++) { var cell = cells[i]; var column = this.s.columns[ cell.colIdx ]; var read = column.read.call(column, cell.node); var stepValue = column.step.call(column, cell.node, read, previous, i, cell.x, cell.y); column.write.call(column, cell.node, stepValue); previous = stepValue; edited.push({ cell: cell, colIdx: cell.colIdx, newValue: stepValue, oldValue: read }); } if (this.c.complete !== null) { this.c.complete.call(this, edited); } // In 1.10 we can do a static draw if (DataTable.Api) { new DataTable.Api(this.s.dt).draw(false); } else { this.s.dt.oInstance.fnDraw(); } }, /** * Display the drag handle on mouse over cell * @method _fnFillerDisplay * @param {Object} e Event object * @returns void */ "_fnFillerDisplay": function (e) { var filler = this.dom.filler; /* Don't display automatically when dragging */ if (this.s.drag.dragging) { return; } /* Check that we are allowed to AutoFill this column or not */ var nTd = (e.target.nodeName.toLowerCase() == 'td') ? e.target : $(e.target).parents('td')[0]; var iX = this._fnTargetCoords(nTd).column; if (!this.s.columns[iX].enable) { filler.style.display = "none"; return; } if (e.type == 'mouseover') { this.dom.currentTarget = nTd; this._fnFillerPosition(nTd); filler.style.display = "block"; } else if (!e.relatedTarget || !e.relatedTarget.className.match(/AutoFill/)) { filler.style.display = "none"; } }, /** * Position the filler icon over a cell * @method _fnFillerPosition * @param {Node} nTd Cell to position filler icon over * @returns void */ "_fnFillerPosition": function (nTd) { var offset = $(nTd).offset(); var filler = this.dom.filler; filler.style.top = (offset.top - (this.s.filler.height / 2) - 1 + $(nTd).outerHeight()) + "px"; filler.style.left = (offset.left - (this.s.filler.width / 2) - 1 + $(nTd).outerWidth()) + "px"; } }; // Alias for access DataTable.AutoFill = AutoFill; DataTable.AutoFill = AutoFill; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * AutoFill version * @constant version * @type String * @default See code */ AutoFill.version = "1.2.0"; /** * AutoFill defaults * @namespace */ AutoFill.defaults = { /** * Mode for dragging (restrict to y-axis only, x-axis only, either one or none): * * * `y` - y-axis only (default) * * `x` - x-axis only * * `either` - either one, but not both axis at the same time * * `both` - multiple cells allowed * * @type {string} * @default `y` */ mode: 'y', complete: null, /** * Column definition defaults * @namespace */ column: { /** * If AutoFill should be enabled on this column * * @type {boolean} * @default true */ enable: true, /** * Allow automatic increment / decrement on this column if a number * is found. * * @type {boolean} * @default true */ increment: true, /** * Cell read function * * Default function will simply read the value from the HTML of the * cell. * * @type {function} * @param {node} cell `th` / `td` element to read the value from * @return {string} Data that has been read */ read: function (cell) { return $(cell).html(); }, /** * Cell write function * * Default function will simply write to the HTML and tell the DataTable * to update. * * @type {function} * @param {node} cell `th` / `td` element to write the value to * @return {string} Data two write */ write: function (cell, val) { var table = $(cell).parents('table'); if (DataTable.Api) { // 1.10 table.DataTable().cell(cell).data(val); } else { // 1.9 var dt = table.dataTable(); var pos = dt.fnGetPosition(); dt.fnUpdate(val, pos[0], pos[2], false); } }, /** * Step function. This provides the ability to customise how the values * are incremented. * * @param {node} cell `th` / `td` element that is being operated upon * @param {string} read Cell value from `read` function * @param {string} last Value of the previous cell * @param {integer} i Loop counter * @param {integer} x Cell x-position in the current auto-fill. The * starting cell is coordinate 0 regardless of its physical position * in the DataTable. * @param {integer} y Cell y-position in the current auto-fill. The * starting cell is coordinate 0 regardless of its physical position * in the DataTable. * @return {string} Value to write */ step: function (cell, read, last, i, x, y) { // Increment a number if it is found var re = /(\-?\d+)/; var match = this.increment && last ? last.match(re) : null; if (match) { return last.replace(re, parseInt(match[1], 10) + (x < 0 || y < 0 ? -1 : 1)); } return last === undefined ? read : last; } } }; return AutoFill; }; // factory factory(jQuery, jQuery.fn.dataTable); }(window, document));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-autoFill.js
jquery-dataTables-autoFill.js
* @summary FixedColumns * @description Freeze columns in place on a scrolling DataTable * @version 3.0.0 * @file dataTables.fixedColumns.js * @author SpryMedia Ltd (www.sprymedia.co.uk) * @contact www.sprymedia.co.uk/contact * @copyright Copyright 2010-2014 SpryMedia Ltd. * * This source file is free software, available under the following license: * MIT license - http://datatables.net/license/mit * * 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 */ (function (window, document, undefined) { var factory = function ($, DataTable) { "use strict"; /** * When making use of DataTables' x-axis scrolling feature, you may wish to * fix the left most column in place. This plug-in for DataTables provides * exactly this option (note for non-scrolling tables, please use the * FixedHeader plug-in, which can fix headers, footers and columns). Key * features include: * * * Freezes the left or right most columns to the side of the table * * Option to freeze two or more columns * * Full integration with DataTables' scrolling options * * Speed - FixedColumns is fast in its operation * * @class * @constructor * @global * @param {object} dt DataTables instance. With DataTables 1.10 this can also * be a jQuery collection, a jQuery selector, DataTables API instance or * settings object. * @param {object} [init={}] Configuration object for FixedColumns. Options are * defined by {@link FixedColumns.defaults} * * @requires jQuery 1.7+ * @requires DataTables 1.8.0+ * * @example * var table = $('#example').dataTable( { * "scrollX": "100%" * } ); * new $.fn.dataTable.fixedColumns( table ); */ var FixedColumns = function (dt, init) { var that = this; /* Sanity check - you just know it will happen */ if (!this instanceof FixedColumns) { alert("FixedColumns warning: FixedColumns must be initialised with the 'new' keyword."); return; } if (typeof init == 'undefined') { init = {}; } // Use the DataTables Hungarian notation mapping method, if it exists to // provide forwards compatibility for camel case variables if ($.fn.dataTable.camelToHungarian) { $.fn.dataTable.camelToHungarian(FixedColumns.defaults, init); } // v1.10 allows the settings object to be got form a number of sources var dtSettings = $.fn.dataTable.Api ? new $.fn.dataTable.Api(dt).settings()[0] : dt.fnSettings(); /** * Settings object which contains customisable information for FixedColumns instance * @namespace * @extends FixedColumns.defaults * @private */ this.s = { /** * DataTables settings objects * @type object * @default Obtained from DataTables instance */ "dt": dtSettings, /** * Number of columns in the DataTable - stored for quick access * @type int * @default Obtained from DataTables instance */ "iTableColumns": dtSettings.aoColumns.length, /** * Original outer widths of the columns as rendered by DataTables - used to calculate * the FixedColumns grid bounding box * @type array.<int> * @default [] */ "aiOuterWidths": [], /** * Original inner widths of the columns as rendered by DataTables - used to apply widths * to the columns * @type array.<int> * @default [] */ "aiInnerWidths": [] }; /** * DOM elements used by the class instance * @namespace * @private * */ this.dom = { /** * DataTables scrolling element * @type node * @default null */ "scroller": null, /** * DataTables header table * @type node * @default null */ "header": null, /** * DataTables body table * @type node * @default null */ "body": null, /** * DataTables footer table * @type node * @default null */ "footer": null, /** * Display grid elements * @namespace */ "grid": { /** * Grid wrapper. This is the container element for the 3x3 grid * @type node * @default null */ "wrapper": null, /** * DataTables scrolling element. This element is the DataTables * component in the display grid (making up the main table - i.e. * not the fixed columns). * @type node * @default null */ "dt": null, /** * Left fixed column grid components * @namespace */ "left": { "wrapper": null, "head": null, "body": null, "foot": null }, /** * Right fixed column grid components * @namespace */ "right": { "wrapper": null, "head": null, "body": null, "foot": null } }, /** * Cloned table nodes * @namespace */ "clone": { /** * Left column cloned table nodes * @namespace */ "left": { /** * Cloned header table * @type node * @default null */ "header": null, /** * Cloned body table * @type node * @default null */ "body": null, /** * Cloned footer table * @type node * @default null */ "footer": null }, /** * Right column cloned table nodes * @namespace */ "right": { /** * Cloned header table * @type node * @default null */ "header": null, /** * Cloned body table * @type node * @default null */ "body": null, /** * Cloned footer table * @type node * @default null */ "footer": null } } }; /* Attach the instance to the DataTables instance so it can be accessed easily */ dtSettings._oFixedColumns = this; /* Let's do it */ if (!dtSettings._bInitComplete) { dtSettings.oApi._fnCallbackReg(dtSettings, 'aoInitComplete', function () { that._fnConstruct(init); }, 'FixedColumns'); } else { this._fnConstruct(init); } }; FixedColumns.prototype = /** @lends FixedColumns.prototype */{ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Update the fixed columns - including headers and footers. Note that FixedColumns will * automatically update the display whenever the host DataTable redraws. * @returns {void} * @example * var table = $('#example').dataTable( { * "scrollX": "100%" * } ); * var fc = new $.fn.dataTable.fixedColumns( table ); * * // at some later point when the table has been manipulated.... * fc.fnUpdate(); */ "fnUpdate": function () { this._fnDraw(true); }, /** * Recalculate the resizes of the 3x3 grid that FixedColumns uses for display of the table. * This is useful if you update the width of the table container. Note that FixedColumns will * perform this function automatically when the window.resize event is fired. * @returns {void} * @example * var table = $('#example').dataTable( { * "scrollX": "100%" * } ); * var fc = new $.fn.dataTable.fixedColumns( table ); * * // Resize the table container and then have FixedColumns adjust its layout.... * $('#content').width( 1200 ); * fc.fnRedrawLayout(); */ "fnRedrawLayout": function () { this._fnColCalc(); this._fnGridLayout(); this.fnUpdate(); }, /** * Mark a row such that it's height should be recalculated when using 'semiauto' row * height matching. This function will have no effect when 'none' or 'auto' row height * matching is used. * @param {Node} nTr TR element that should have it's height recalculated * @returns {void} * @example * var table = $('#example').dataTable( { * "scrollX": "100%" * } ); * var fc = new $.fn.dataTable.fixedColumns( table ); * * // manipulate the table - mark the row as needing an update then update the table * // this allows the redraw performed by DataTables fnUpdate to recalculate the row * // height * fc.fnRecalculateHeight(); * table.fnUpdate( $('#example tbody tr:eq(0)')[0], ["insert date", 1, 2, 3 ... ]); */ "fnRecalculateHeight": function (nTr) { delete nTr._DTTC_iHeight; nTr.style.height = 'auto'; }, /** * Set the height of a given row - provides cross browser compatibility * @param {Node} nTarget TR element that should have it's height recalculated * @param {int} iHeight Height in pixels to set * @returns {void} * @example * var table = $('#example').dataTable( { * "scrollX": "100%" * } ); * var fc = new $.fn.dataTable.fixedColumns( table ); * * // You may want to do this after manipulating a row in the fixed column * fc.fnSetRowHeight( $('#example tbody tr:eq(0)')[0], 50 ); */ "fnSetRowHeight": function (nTarget, iHeight) { nTarget.style.height = iHeight + "px"; }, /** * Get data index information about a row or cell in the table body. * This function is functionally identical to fnGetPosition in DataTables, * taking the same parameter (TH, TD or TR node) and returning exactly the * the same information (data index information). THe difference between * the two is that this method takes into account the fixed columns in the * table, so you can pass in nodes from the master table, or the cloned * tables and get the index position for the data in the main table. * @param {node} node TR, TH or TD element to get the information about * @returns {int} If nNode is given as a TR, then a single index is * returned, or if given as a cell, an array of [row index, column index * (visible), column index (all)] is given. */ "fnGetPosition": function (node) { var idx; var inst = this.s.dt.oInstance; if (!$(node).parents('.DTFC_Cloned').length) { // Not in a cloned table return inst.fnGetPosition(node); } else { // Its in the cloned table, so need to look up position if (node.nodeName.toLowerCase() === 'tr') { idx = $(node).index(); return inst.fnGetPosition($('tr', this.s.dt.nTBody)[ idx ]); } else { var colIdx = $(node).index(); idx = $(node.parentNode).index(); var row = inst.fnGetPosition($('tr', this.s.dt.nTBody)[ idx ]); return [ row, colIdx, inst.oApi._fnVisibleToColumnIndex(this.s.dt, colIdx) ]; } } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Initialisation for FixedColumns * @param {Object} oInit User settings for initialisation * @returns {void} * @private */ "_fnConstruct": function (oInit) { var i, iLen, iWidth, that = this; /* Sanity checking */ if (typeof this.s.dt.oInstance.fnVersionCheck != 'function' || this.s.dt.oInstance.fnVersionCheck('1.8.0') !== true) { alert("FixedColumns " + FixedColumns.VERSION + " required DataTables 1.8.0 or later. " + "Please upgrade your DataTables installation"); return; } if (this.s.dt.oScroll.sX === "") { this.s.dt.oInstance.oApi._fnLog(this.s.dt, 1, "FixedColumns is not needed (no " + "x-scrolling in DataTables enabled), so no action will be taken. Use 'FixedHeader' for " + "column fixing when scrolling is not enabled"); return; } /* Apply the settings from the user / defaults */ this.s = $.extend(true, this.s, FixedColumns.defaults, oInit); /* Set up the DOM as we need it and cache nodes */ var classes = this.s.dt.oClasses; this.dom.grid.dt = $(this.s.dt.nTable).parents('div.' + classes.sScrollWrapper)[0]; this.dom.scroller = $('div.' + classes.sScrollBody, this.dom.grid.dt)[0]; /* Set up the DOM that we want for the fixed column layout grid */ this._fnColCalc(); this._fnGridSetup(); /* Event handlers */ var mouseController; // When the body is scrolled - scroll the left and right columns $(this.dom.scroller) .on('mouseover.DTFC', function () { mouseController = 'main'; }) .on('scroll.DTFC', function () { if (mouseController === 'main') { if (that.s.iLeftColumns > 0) { that.dom.grid.left.liner.scrollTop = that.dom.scroller.scrollTop; } if (that.s.iRightColumns > 0) { that.dom.grid.right.liner.scrollTop = that.dom.scroller.scrollTop; } } }); if (that.s.iLeftColumns > 0) { // When scrolling the left column, scroll the body and right column $(that.dom.grid.left.liner) .on('mouseover.DTFC', function () { mouseController = 'left'; }) .on('scroll.DTFC', function () { if (mouseController === 'left') { that.dom.scroller.scrollTop = that.dom.grid.left.liner.scrollTop; if (that.s.iRightColumns > 0) { that.dom.grid.right.liner.scrollTop = that.dom.grid.left.liner.scrollTop; } } }) .on("wheel.DTFC", function (e) { // Pass horizontal scrolling through var xDelta = -e.originalEvent.deltaX; that.dom.scroller.scrollLeft -= xDelta; }); } if (that.s.iRightColumns > 0) { // When scrolling the right column, scroll the body and the left column $(that.dom.grid.right.liner) .on('mouseover.DTFC', function () { mouseController = 'right'; }) .on('scroll.DTFC', function () { if (mouseController === 'right') { that.dom.scroller.scrollTop = that.dom.grid.right.liner.scrollTop; if (that.s.iLeftColumns > 0) { that.dom.grid.left.liner.scrollTop = that.dom.grid.right.liner.scrollTop; } } }) .on("wheel.DTFC", function (e) { // Pass horizontal scrolling through var xDelta = -e.originalEvent.deltaX; that.dom.scroller.scrollLeft -= xDelta; }); } $(window).on('resize.DTFC', function () { that._fnGridLayout.call(that); }); var bFirstDraw = true; var jqTable = $(this.s.dt.nTable); jqTable .on('draw.dt.DTFC', function () { that._fnDraw.call(that, bFirstDraw); bFirstDraw = false; }) .on('column-sizing.dt.DTFC', function () { that._fnColCalc(); that._fnGridLayout(that); }) .on('column-visibility.dt.DTFC', function () { that._fnColCalc(); that._fnGridLayout(that); that._fnDraw(true); }) .on('destroy.dt.DTFC', function () { jqTable.off('column-sizing.dt.DTFC destroy.dt.DTFC draw.dt.DTFC'); $(that.dom.scroller).fn('scroll.DTFC mouseover.DTFC'); $(window).off('resize.DTFC'); $(that.dom.grid.left.liner).on('scroll.DTFC wheel.DTFC mouseover.DTFC'); $(that.dom.grid.left.wrapper).remove(); $(that.dom.grid.right.liner).on('scroll.DTFC wheel.DTFC mouseover.DTFC'); $(that.dom.grid.right.wrapper).remove(); }); /* Get things right to start with - note that due to adjusting the columns, there must be * another redraw of the main table. It doesn't need to be a full redraw however. */ this._fnGridLayout(); this.s.dt.oInstance.fnDraw(false); }, /** * Calculate the column widths for the grid layout * @returns {void} * @private */ "_fnColCalc": function () { var that = this; var iLeftWidth = 0; var iRightWidth = 0; this.s.aiInnerWidths = []; this.s.aiOuterWidths = []; $.each(this.s.dt.aoColumns, function (i, col) { var th = $(col.nTh); if (!th.filter(':visible').length) { that.s.aiInnerWidths.push(0); that.s.aiOuterWidths.push(0); } else { // Inner width is used to assign widths to cells // Outer width is used to calculate the container var iWidth = th.outerWidth(); // When working with the left most-cell, need to add on the // table's border to the outerWidth, since we need to take // account of it, but it isn't in any cell if (that.s.aiOuterWidths.length === 0) { iWidth += parseInt($(that.s.dt.nTable).css('border-left-width'), 10); } that.s.aiOuterWidths.push(iWidth); that.s.aiInnerWidths.push(th.width()); if (i < that.s.iLeftColumns) { iLeftWidth += iWidth; } if (that.s.iTableColumns - that.s.iRightColumns <= i) { iRightWidth += iWidth; } } }); this.s.iLeftWidth = iLeftWidth; this.s.iRightWidth = iRightWidth; }, /** * Set up the DOM for the fixed column. The way the layout works is to create a 1x3 grid * for the left column, the DataTable (for which we just reuse the scrolling element DataTable * puts into the DOM) and the right column. In each of he two fixed column elements there is a * grouping wrapper element and then a head, body and footer wrapper. In each of these we then * place the cloned header, body or footer tables. This effectively gives as 3x3 grid structure. * @returns {void} * @private */ "_fnGridSetup": function () { var that = this; var oOverflow = this._fnDTOverflow(); var block; this.dom.body = this.s.dt.nTable; this.dom.header = this.s.dt.nTHead.parentNode; this.dom.header.parentNode.parentNode.style.position = "relative"; var nSWrapper = $('<div class="DTFC_ScrollWrapper" style="position:relative; clear:both;">' + '<div class="DTFC_LeftWrapper" style="position:absolute; top:0; left:0;">' + '<div class="DTFC_LeftHeadWrapper" style="position:relative; top:0; left:0; overflow:hidden;"></div>' + '<div class="DTFC_LeftBodyWrapper" style="position:relative; top:0; left:0; overflow:hidden;">' + '<div class="DTFC_LeftBodyLiner" style="position:relative; top:0; left:0; overflow-y:scroll;"></div>' + '</div>' + '<div class="DTFC_LeftFootWrapper" style="position:relative; top:0; left:0; overflow:hidden;"></div>' + '</div>' + '<div class="DTFC_RightWrapper" style="position:absolute; top:0; left:0;">' + '<div class="DTFC_RightHeadWrapper" style="position:relative; top:0; left:0;">' + '<div class="DTFC_RightHeadBlocker DTFC_Blocker" style="position:absolute; top:0; bottom:0;"></div>' + '</div>' + '<div class="DTFC_RightBodyWrapper" style="position:relative; top:0; left:0; overflow:hidden;">' + '<div class="DTFC_RightBodyLiner" style="position:relative; top:0; left:0; overflow-y:scroll;"></div>' + '</div>' + '<div class="DTFC_RightFootWrapper" style="position:relative; top:0; left:0;">' + '<div class="DTFC_RightFootBlocker DTFC_Blocker" style="position:absolute; top:0; bottom:0;"></div>' + '</div>' + '</div>' + '</div>')[0]; var nLeft = nSWrapper.childNodes[0]; var nRight = nSWrapper.childNodes[1]; this.dom.grid.dt.parentNode.insertBefore(nSWrapper, this.dom.grid.dt); nSWrapper.appendChild(this.dom.grid.dt); this.dom.grid.wrapper = nSWrapper; if (this.s.iLeftColumns > 0) { this.dom.grid.left.wrapper = nLeft; this.dom.grid.left.head = nLeft.childNodes[0]; this.dom.grid.left.body = nLeft.childNodes[1]; this.dom.grid.left.liner = $('div.DTFC_LeftBodyLiner', nSWrapper)[0]; nSWrapper.appendChild(nLeft); } if (this.s.iRightColumns > 0) { this.dom.grid.right.wrapper = nRight; this.dom.grid.right.head = nRight.childNodes[0]; this.dom.grid.right.body = nRight.childNodes[1]; this.dom.grid.right.liner = $('div.DTFC_RightBodyLiner', nSWrapper)[0]; block = $('div.DTFC_RightHeadBlocker', nSWrapper)[0]; block.style.width = oOverflow.bar + "px"; block.style.right = -oOverflow.bar + "px"; this.dom.grid.right.headBlock = block; block = $('div.DTFC_RightFootBlocker', nSWrapper)[0]; block.style.width = oOverflow.bar + "px"; block.style.right = -oOverflow.bar + "px"; this.dom.grid.right.footBlock = block; nSWrapper.appendChild(nRight); } if (this.s.dt.nTFoot) { this.dom.footer = this.s.dt.nTFoot.parentNode; if (this.s.iLeftColumns > 0) { this.dom.grid.left.foot = nLeft.childNodes[2]; } if (this.s.iRightColumns > 0) { this.dom.grid.right.foot = nRight.childNodes[2]; } } }, /** * Style and position the grid used for the FixedColumns layout * @returns {void} * @private */ "_fnGridLayout": function () { var oGrid = this.dom.grid; var iWidth = $(oGrid.wrapper).width(); var iBodyHeight = $(this.s.dt.nTable.parentNode).height(); var iFullHeight = $(this.s.dt.nTable.parentNode.parentNode).height(); var oOverflow = this._fnDTOverflow(); var iLeftWidth = this.s.iLeftWidth, iRightWidth = this.s.iRightWidth, iRight; // When x scrolling - don't paint the fixed columns over the x scrollbar if (oOverflow.x) { iBodyHeight -= oOverflow.bar; } oGrid.wrapper.style.height = iFullHeight + "px"; if (this.s.iLeftColumns > 0) { oGrid.left.wrapper.style.width = iLeftWidth + "px"; oGrid.left.wrapper.style.height = "1px"; oGrid.left.body.style.height = iBodyHeight + "px"; if (oGrid.left.foot) { oGrid.left.foot.style.top = (oOverflow.x ? oOverflow.bar : 0) + "px"; // shift footer for scrollbar } oGrid.left.liner.style.width = (iLeftWidth + oOverflow.bar) + "px"; oGrid.left.liner.style.height = iBodyHeight + "px"; } if (this.s.iRightColumns > 0) { iRight = iWidth - iRightWidth; if (oOverflow.y) { iRight -= oOverflow.bar; } oGrid.right.wrapper.style.width = iRightWidth + "px"; oGrid.right.wrapper.style.left = iRight + "px"; oGrid.right.wrapper.style.height = "1px"; oGrid.right.body.style.height = iBodyHeight + "px"; if (oGrid.right.foot) { oGrid.right.foot.style.top = (oOverflow.x ? oOverflow.bar : 0) + "px"; } oGrid.right.liner.style.width = (iRightWidth + oOverflow.bar) + "px"; oGrid.right.liner.style.height = iBodyHeight + "px"; oGrid.right.headBlock.style.display = oOverflow.y ? 'block' : 'none'; oGrid.right.footBlock.style.display = oOverflow.y ? 'block' : 'none'; } }, /** * Get information about the DataTable's scrolling state - specifically if the table is scrolling * on either the x or y axis, and also the scrollbar width. * @returns {object} Information about the DataTables scrolling state with the properties: * 'x', 'y' and 'bar' * @private */ "_fnDTOverflow": function () { var nTable = this.s.dt.nTable; var nTableScrollBody = nTable.parentNode; var out = { "x": false, "y": false, "bar": this.s.dt.oScroll.iBarWidth }; if (nTable.offsetWidth > nTableScrollBody.clientWidth) { out.x = true; } if (nTable.offsetHeight > nTableScrollBody.clientHeight) { out.y = true; } return out; }, /** * Clone and position the fixed columns * @returns {void} * @param {Boolean} bAll Indicate if the header and footer should be updated as well (true) * @private */ "_fnDraw": function (bAll) { this._fnGridLayout(); this._fnCloneLeft(bAll); this._fnCloneRight(bAll); /* Draw callback function */ if (this.s.fnDrawCallback !== null) { this.s.fnDrawCallback.call(this, this.dom.clone.left, this.dom.clone.right); } /* Event triggering */ $(this).trigger('draw.dtfc', { "leftClone": this.dom.clone.left, "rightClone": this.dom.clone.right }); }, /** * Clone the right columns * @returns {void} * @param {Boolean} bAll Indicate if the header and footer should be updated as well (true) * @private */ "_fnCloneRight": function (bAll) { if (this.s.iRightColumns <= 0) { return; } var that = this, i, jq, aiColumns = []; for (i = this.s.iTableColumns - this.s.iRightColumns; i < this.s.iTableColumns; i++) { if (this.s.dt.aoColumns[i].bVisible) { aiColumns.push(i); } } this._fnClone(this.dom.clone.right, this.dom.grid.right, aiColumns, bAll); }, /** * Clone the left columns * @returns {void} * @param {Boolean} bAll Indicate if the header and footer should be updated as well (true) * @private */ "_fnCloneLeft": function (bAll) { if (this.s.iLeftColumns <= 0) { return; } var that = this, i, jq, aiColumns = []; for (i = 0; i < this.s.iLeftColumns; i++) { if (this.s.dt.aoColumns[i].bVisible) { aiColumns.push(i); } } this._fnClone(this.dom.clone.left, this.dom.grid.left, aiColumns, bAll); }, /** * Make a copy of the layout object for a header or footer element from DataTables. Note that * this method will clone the nodes in the layout object. * @returns {Array} Copy of the layout array * @param {Object} aoOriginal Layout array from DataTables (aoHeader or aoFooter) * @param {Object} aiColumns Columns to copy * @private */ "_fnCopyLayout": function (aoOriginal, aiColumns) { var aReturn = []; var aClones = []; var aCloned = []; for (var i = 0, iLen = aoOriginal.length; i < iLen; i++) { var aRow = []; aRow.nTr = $(aoOriginal[i].nTr).clone(true, true)[0]; for (var j = 0, jLen = this.s.iTableColumns; j < jLen; j++) { if ($.inArray(j, aiColumns) === -1) { continue; } var iCloned = $.inArray(aoOriginal[i][j].cell, aCloned); if (iCloned === -1) { var nClone = $(aoOriginal[i][j].cell).clone(true, true)[0]; aClones.push(nClone); aCloned.push(aoOriginal[i][j].cell); aRow.push({ "cell": nClone, "unique": aoOriginal[i][j].unique }); } else { aRow.push({ "cell": aClones[ iCloned ], "unique": aoOriginal[i][j].unique }); } } aReturn.push(aRow); } return aReturn; }, /** * Clone the DataTable nodes and place them in the DOM (sized correctly) * @returns {void} * @param {Object} oClone Object containing the header, footer and body cloned DOM elements * @param {Object} oGrid Grid object containing the display grid elements for the cloned * column (left or right) * @param {Array} aiColumns Column indexes which should be operated on from the DataTable * @param {Boolean} bAll Indicate if the header and footer should be updated as well (true) * @private */ "_fnClone": function (oClone, oGrid, aiColumns, bAll) { var that = this, i, iLen, j, jLen, jq, nTarget, iColumn, nClone, iIndex, aoCloneLayout, jqCloneThead, aoFixedHeader; /* * Header */ if (bAll) { if (oClone.header !== null) { oClone.header.parentNode.removeChild(oClone.header); } oClone.header = $(this.dom.header).clone(true, true)[0]; oClone.header.className += " DTFC_Cloned"; oClone.header.style.width = "100%"; oGrid.head.appendChild(oClone.header); /* Copy the DataTables layout cache for the header for our floating column */ aoCloneLayout = this._fnCopyLayout(this.s.dt.aoHeader, aiColumns); jqCloneThead = $('>thead', oClone.header); jqCloneThead.empty(); /* Add the created cloned TR elements to the table */ for (i = 0, iLen = aoCloneLayout.length; i < iLen; i++) { jqCloneThead[0].appendChild(aoCloneLayout[i].nTr); } /* Use the handy _fnDrawHead function in DataTables to do the rowspan/colspan * calculations for us */ this.s.dt.oApi._fnDrawHead(this.s.dt, aoCloneLayout, true); } else { /* To ensure that we copy cell classes exactly, regardless of colspan, multiple rows * etc, we make a copy of the header from the DataTable again, but don't insert the * cloned cells, just copy the classes across. To get the matching layout for the * fixed component, we use the DataTables _fnDetectHeader method, allowing 1:1 mapping */ aoCloneLayout = this._fnCopyLayout(this.s.dt.aoHeader, aiColumns); aoFixedHeader = []; this.s.dt.oApi._fnDetectHeader(aoFixedHeader, $('>thead', oClone.header)[0]); for (i = 0, iLen = aoCloneLayout.length; i < iLen; i++) { for (j = 0, jLen = aoCloneLayout[i].length; j < jLen; j++) { aoFixedHeader[i][j].cell.className = aoCloneLayout[i][j].cell.className; // If jQuery UI theming is used we need to copy those elements as well $('span.DataTables_sort_icon', aoFixedHeader[i][j].cell).each(function () { this.className = $('span.DataTables_sort_icon', aoCloneLayout[i][j].cell)[0].className; }); } } } this._fnEqualiseHeights('thead', this.dom.header, oClone.header); /* * Body */ if (this.s.sHeightMatch == 'auto') { /* Remove any heights which have been applied already and let the browser figure it out */ $('>tbody>tr', that.dom.body).css('height', 'auto'); } if (oClone.body !== null) { oClone.body.parentNode.removeChild(oClone.body); oClone.body = null; } oClone.body = $(this.dom.body).clone(true)[0]; oClone.body.className += " DTFC_Cloned"; oClone.body.style.paddingBottom = this.s.dt.oScroll.iBarWidth + "px"; oClone.body.style.marginBottom = (this.s.dt.oScroll.iBarWidth * 2) + "px"; /* For IE */ if (oClone.body.getAttribute('id') !== null) { oClone.body.removeAttribute('id'); } $('>thead>tr', oClone.body).empty(); $('>tfoot', oClone.body).remove(); var nBody = $('tbody', oClone.body)[0]; $(nBody).empty(); if (this.s.dt.aiDisplay.length > 0) { /* Copy the DataTables' header elements to force the column width in exactly the * same way that DataTables does it - have the header element, apply the width and * colapse it down */ var nInnerThead = $('>thead>tr', oClone.body)[0]; for (iIndex = 0; iIndex < aiColumns.length; iIndex++) { iColumn = aiColumns[iIndex]; nClone = $(this.s.dt.aoColumns[iColumn].nTh).clone(true)[0]; nClone.innerHTML = ""; var oStyle = nClone.style; oStyle.paddingTop = "0"; oStyle.paddingBottom = "0"; oStyle.borderTopWidth = "0"; oStyle.borderBottomWidth = "0"; oStyle.height = 0; oStyle.width = that.s.aiInnerWidths[iColumn] + "px"; nInnerThead.appendChild(nClone); } /* Add in the tbody elements, cloning form the master table */ $('>tbody>tr', that.dom.body).each(function (z) { var n = this.cloneNode(false); n.removeAttribute('id'); var i = that.s.dt.oFeatures.bServerSide === false ? that.s.dt.aiDisplay[ that.s.dt._iDisplayStart + z ] : z; for (iIndex = 0; iIndex < aiColumns.length; iIndex++) { var aTds = that.s.dt.aoData[i].anCells || that.s.dt.oApi._fnGetTdNodes(that.s.dt, i); iColumn = aiColumns[iIndex]; if (aTds.length > 0) { nClone = $(aTds[iColumn]).clone(true, true)[0]; n.appendChild(nClone); } } nBody.appendChild(n); }); } else { $('>tbody>tr', that.dom.body).each(function (z) { nClone = this.cloneNode(true); nClone.className += ' DTFC_NoData'; $('td', nClone).html(''); nBody.appendChild(nClone); }); } oClone.body.style.width = "100%"; oClone.body.style.margin = "0"; oClone.body.style.padding = "0"; if (bAll) { if (typeof this.s.dt.oScroller != 'undefined') { oGrid.liner.appendChild(this.s.dt.oScroller.dom.force.cloneNode(true)); } } oGrid.liner.appendChild(oClone.body); this._fnEqualiseHeights('tbody', that.dom.body, oClone.body); /* * Footer */ if (this.s.dt.nTFoot !== null) { if (bAll) { if (oClone.footer !== null) { oClone.footer.parentNode.removeChild(oClone.footer); } oClone.footer = $(this.dom.footer).clone(true, true)[0]; oClone.footer.className += " DTFC_Cloned"; oClone.footer.style.width = "100%"; oGrid.foot.appendChild(oClone.footer); /* Copy the footer just like we do for the header */ aoCloneLayout = this._fnCopyLayout(this.s.dt.aoFooter, aiColumns); var jqCloneTfoot = $('>tfoot', oClone.footer); jqCloneTfoot.empty(); for (i = 0, iLen = aoCloneLayout.length; i < iLen; i++) { jqCloneTfoot[0].appendChild(aoCloneLayout[i].nTr); } this.s.dt.oApi._fnDrawHead(this.s.dt, aoCloneLayout, true); } else { aoCloneLayout = this._fnCopyLayout(this.s.dt.aoFooter, aiColumns); var aoCurrFooter = []; this.s.dt.oApi._fnDetectHeader(aoCurrFooter, $('>tfoot', oClone.footer)[0]); for (i = 0, iLen = aoCloneLayout.length; i < iLen; i++) { for (j = 0, jLen = aoCloneLayout[i].length; j < jLen; j++) { aoCurrFooter[i][j].cell.className = aoCloneLayout[i][j].cell.className; } } } this._fnEqualiseHeights('tfoot', this.dom.footer, oClone.footer); } /* Equalise the column widths between the header footer and body - body get's priority */ var anUnique = this.s.dt.oApi._fnGetUniqueThs(this.s.dt, $('>thead', oClone.header)[0]); $(anUnique).each(function (i) { iColumn = aiColumns[i]; this.style.width = that.s.aiInnerWidths[iColumn] + "px"; }); if (that.s.dt.nTFoot !== null) { anUnique = this.s.dt.oApi._fnGetUniqueThs(this.s.dt, $('>tfoot', oClone.footer)[0]); $(anUnique).each(function (i) { iColumn = aiColumns[i]; this.style.width = that.s.aiInnerWidths[iColumn] + "px"; }); } }, /** * From a given table node (THEAD etc), get a list of TR direct child elements * @param {Node} nIn Table element to search for TR elements (THEAD, TBODY or TFOOT element) * @returns {Array} List of TR elements found * @private */ "_fnGetTrNodes": function (nIn) { var aOut = []; for (var i = 0, iLen = nIn.childNodes.length; i < iLen; i++) { if (nIn.childNodes[i].nodeName.toUpperCase() == "TR") { aOut.push(nIn.childNodes[i]); } } return aOut; }, /** * Equalise the heights of the rows in a given table node in a cross browser way * @returns {void} * @param {String} nodeName Node type - thead, tbody or tfoot * @param {Node} original Original node to take the heights from * @param {Node} clone Copy the heights to * @private */ "_fnEqualiseHeights": function (nodeName, original, clone) { if (this.s.sHeightMatch == 'none' && nodeName !== 'thead' && nodeName !== 'tfoot') { return; } var that = this, i, iLen, iHeight, iHeight2, iHeightOriginal, iHeightClone, rootOriginal = original.getElementsByTagName(nodeName)[0], rootClone = clone.getElementsByTagName(nodeName)[0], jqBoxHack = $('>' + nodeName + '>tr:eq(0)', original).children(':first'), iBoxHack = jqBoxHack.outerHeight() - jqBoxHack.height(), anOriginal = this._fnGetTrNodes(rootOriginal), anClone = this._fnGetTrNodes(rootClone), heights = []; for (i = 0, iLen = anClone.length; i < iLen; i++) { iHeightOriginal = anOriginal[i].offsetHeight; iHeightClone = anClone[i].offsetHeight; iHeight = iHeightClone > iHeightOriginal ? iHeightClone : iHeightOriginal; if (this.s.sHeightMatch == 'semiauto') { anOriginal[i]._DTTC_iHeight = iHeight; } heights.push(iHeight); } for (i = 0, iLen = anClone.length; i < iLen; i++) { anClone[i].style.height = heights[i] + "px"; anOriginal[i].style.height = heights[i] + "px"; } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Statics * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * FixedColumns default settings for initialisation * @name FixedColumns.defaults * @namespace * @static */ FixedColumns.defaults = /** @lends FixedColumns.defaults */{ /** * Number of left hand columns to fix in position * @type int * @default 1 * @static * @example * var = $('#example').dataTable( { * "scrollX": "100%" * } ); * new $.fn.dataTable.fixedColumns( table, { * "leftColumns": 2 * } ); */ "iLeftColumns": 1, /** * Number of right hand columns to fix in position * @type int * @default 0 * @static * @example * var table = $('#example').dataTable( { * "scrollX": "100%" * } ); * new $.fn.dataTable.fixedColumns( table, { * "rightColumns": 1 * } ); */ "iRightColumns": 0, /** * Draw callback function which is called when FixedColumns has redrawn the fixed assets * @type function(object, object):void * @default null * @static * @example * var table = $('#example').dataTable( { * "scrollX": "100%" * } ); * new $.fn.dataTable.fixedColumns( table, { * "drawCallback": function () { * alert( "FixedColumns redraw" ); * } * } ); */ "fnDrawCallback": null, /** * Height matching algorthim to use. This can be "none" which will result in no height * matching being applied by FixedColumns (height matching could be forced by CSS in this * case), "semiauto" whereby the height calculation will be performed once, and the result * cached to be used again (fnRecalculateHeight can be used to force recalculation), or * "auto" when height matching is performed on every draw (slowest but must accurate) * @type string * @default semiauto * @static * @example * var table = $('#example').dataTable( { * "scrollX": "100%" * } ); * new $.fn.dataTable.fixedColumns( table, { * "heightMatch": "auto" * } ); */ "sHeightMatch": "semiauto" }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * FixedColumns version * @name FixedColumns.version * @type String * @default See code * @static */ FixedColumns.version = "3.0.0"; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Fired events (for documentation) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Event fired whenever FixedColumns redraws the fixed columns (i.e. clones the table elements from the main DataTable). This will occur whenever the DataTable that the FixedColumns instance is attached does its own draw. * @name FixedColumns#draw.dtfc * @event * @param {event} e jQuery event object * @param {object} o Event parameters from FixedColumns * @param {object} o.leftClone Instance's object dom.clone.left for easy reference. This object contains references to the left fixed clumn column's nodes * @param {object} o.rightClone Instance's object dom.clone.right for easy reference. This object contains references to the right fixed clumn column's nodes */ // Make FixedColumns accessible from the DataTables instance $.fn.dataTable.FixedColumns = FixedColumns; $.fn.DataTable.FixedColumns = FixedColumns; return FixedColumns; }; // /factory factory(jQuery, jQuery.fn.dataTable); })(window, document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-fixedColumns.js
jquery-dataTables-fixedColumns.js
(function(c,a,d){var b=function(g,f){var e=function(h,i){if(!(this instanceof e)){throw ("Warning: AutoFill must be initialised with the keyword 'new'")}if(!g.fn.dataTableExt.fnVersionCheck("1.7.0")){throw ("Warning: AutoFill requires DataTables 1.7 or greater")}this.c={};this.s={filler:{height:0,width:0},border:{width:2},drag:{startX:-1,startY:-1,startTd:null,endTd:null,dragging:false},screen:{interval:null,y:0,height:0,scrollTop:0},scroller:{top:0,bottom:0},columns:[]};this.dom={table:null,filler:null,borderTop:null,borderRight:null,borderBottom:null,borderLeft:null,currentTarget:null};this.fnSettings=function(){return this.s};this._fnInit(h,i);return this};e.prototype={_fnInit:function(p,l){var o=this,n,h;this.s.dt=f.Api?new f.Api(p).settings()[0]:p.fnSettings();this.s.init=l||{};this.dom.table=this.s.dt.nTable;g.extend(true,this.c,e.defaults,l);this._initColumns();var m=g("<div/>",{"class":"AutoFill_filler"}).appendTo("body");this.dom.filler=m[0];this.s.filler.height=m.height();this.s.filler.width=m.width();m[0].style.display="none";var k;var j=a.body;if(o.s.dt.oScroll.sY!==""){o.s.dt.nTable.parentNode.style.position="relative";j=o.s.dt.nTable.parentNode}k=g("<div/>",{"class":"AutoFill_border"});this.dom.borderTop=k.clone().appendTo(j)[0];this.dom.borderRight=k.clone().appendTo(j)[0];this.dom.borderBottom=k.clone().appendTo(j)[0];this.dom.borderLeft=k.clone().appendTo(j)[0];m.on("mousedown.DTAF",function(i){this.onselectstart=function(){return false};o._fnFillerDragStart.call(o,i);return false});g("tbody",this.dom.table).on("mouseover.DTAF mouseout.DTAF",">tr>td, >tr>th",function(i){o._fnFillerDisplay.call(o,i)});g(this.dom.table).on("destroy.dt.DTAF",function(){m.off("mousedown.DTAF").remove();g("tbody",this.dom.table).off("mouseover.DTAF mouseout.DTAF")})},_initColumns:function(){var n=this;var k,h;var m=this.s.dt;var j=this.s.init;for(k=0,h=m.aoColumns.length;k<h;k++){this.s.columns[k]=g.extend(true,{},e.defaults.column)}m.oApi._fnApplyColumnDefs(m,j.aoColumnDefs||j.columnDefs,j.aoColumns||j.columns,function(o,i){n._fnColumnOptions(o,i)});for(k=0,h=m.aoColumns.length;k<h;k++){var l=this.s.columns[k];if(!l.read){l.read=this._fnReadCell}if(!l.write){l.read=this._fnWriteCell}if(!l.step){l.read=this._fnStep}}},_fnColumnOptions:function(h,k){var j=this.s.columns[h];var l=function(i,m){if(k[m[0]]!==d){j[i]=k[m[0]]}if(k[m[1]]!==d){j[i]=k[m[1]]}};l("enable",["bEnable","enable"]);l("read",["fnRead","read"]);l("write",["fnWrite","write"]);l("step",["fnStep","step"]);l("increment",["bIncrement","increment"])},_fnTargetCoords:function(i){var j=g(i).parents("tr")[0];var h=this.s.dt.oInstance.fnGetPosition(i);return{x:g("td",j).index(i),y:g("tr",j.parentNode).index(j),row:h[0],column:h[2]}},_fnUpdateBorder:function(p,q){var n=this.s.border.width,o=g(p).offset(),s=g(q).offset(),k=o.left-n,i=s.left+g(q).outerWidth(),t=o.top-n,r=s.top+g(q).outerHeight(),j=s.left+g(q).outerWidth()-o.left+(2*n),v=s.top+g(q).outerHeight()-o.top+(2*n),u;if(o.left>s.left){k=s.left-n;i=o.left+g(p).outerWidth();j=o.left+g(p).outerWidth()-s.left+(2*n)}if(this.s.dt.oScroll.sY!==""){var h=g(this.s.dt.nTable.parentNode).offset(),l=g(this.s.dt.nTable.parentNode).scrollTop(),m=g(this.s.dt.nTable.parentNode).scrollLeft();k-=h.left-m;i-=h.left-m;t-=h.top-l;r-=h.top-l}u=this.dom.borderTop.style;u.top=t+"px";u.left=k+"px";u.height=this.s.border.width+"px";u.width=j+"px";u=this.dom.borderBottom.style;u.top=r+"px";u.left=k+"px";u.height=this.s.border.width+"px";u.width=j+"px";u=this.dom.borderLeft.style;u.top=t+"px";u.left=k+"px";u.height=v+"px";u.width=this.s.border.width+"px";u=this.dom.borderRight.style;u.top=t+"px";u.left=i+"px";u.height=v+"px";u.width=this.s.border.width+"px"},_fnFillerDragStart:function(j){var h=this;var k=this.dom.currentTarget;this.s.drag.dragging=true;h.dom.borderTop.style.display="block";h.dom.borderRight.style.display="block";h.dom.borderBottom.style.display="block";h.dom.borderLeft.style.display="block";var i=this._fnTargetCoords(k);this.s.drag.startX=i.x;this.s.drag.startY=i.y;this.s.drag.startTd=k;this.s.drag.endTd=k;this._fnUpdateBorder(k,k);g(a).bind("mousemove.AutoFill",function(l){h._fnFillerDragMove.call(h,l)});g(a).bind("mouseup.AutoFill",function(l){h._fnFillerFinish.call(h,l)});this.s.screen.y=j.pageY;this.s.screen.height=g(c).height();this.s.screen.scrollTop=g(a).scrollTop();if(this.s.dt.oScroll.sY!==""){this.s.scroller.top=g(this.s.dt.nTable.parentNode).offset().top;this.s.scroller.bottom=this.s.scroller.top+g(this.s.dt.nTable.parentNode).height()}this.s.screen.interval=setInterval(function(){var l=g(a).scrollTop();var m=l-h.s.screen.scrollTop;h.s.screen.y+=m;if(h.s.screen.height-h.s.screen.y+l<50){g("html, body").animate({scrollTop:l+50},240,"linear")}else{if(h.s.screen.y-l<50){g("html, body").animate({scrollTop:l-50},240,"linear")}}if(h.s.dt.oScroll.sY!==""){if(h.s.screen.y>h.s.scroller.bottom-50){g(h.s.dt.nTable.parentNode).animate({scrollTop:g(h.s.dt.nTable.parentNode).scrollTop()+50},240,"linear")}else{if(h.s.screen.y<h.s.scroller.top+50){g(h.s.dt.nTable.parentNode).animate({scrollTop:g(h.s.dt.nTable.parentNode).scrollTop()-50},240,"linear")}}}},250)},_fnFillerDragMove:function(j){if(j.target&&j.target.nodeName.toUpperCase()=="TD"&&j.target!=this.s.drag.endTd){var i=this._fnTargetCoords(j.target);if(this.c.mode=="y"&&i.x!=this.s.drag.startX){j.target=g("tbody>tr:eq("+i.y+")>td:eq("+this.s.drag.startX+")",this.dom.table)[0]}if(this.c.mode=="x"&&i.y!=this.s.drag.startY){j.target=g("tbody>tr:eq("+this.s.drag.startY+")>td:eq("+i.x+")",this.dom.table)[0]}if(this.c.mode=="either"){if(i.x!=this.s.drag.startX){j.target=g("tbody>tr:eq("+this.s.drag.startY+")>td:eq("+i.x+")",this.dom.table)[0]}else{if(i.y!=this.s.drag.startY){j.target=g("tbody>tr:eq("+i.y+")>td:eq("+this.s.drag.startX+")",this.dom.table)[0]}}}if(this.c.mode!=="both"){i=this._fnTargetCoords(j.target)}var h=this.s.drag;h.endTd=j.target;if(i.y>=this.s.drag.startY){this._fnUpdateBorder(h.startTd,h.endTd)}else{this._fnUpdateBorder(h.endTd,h.startTd)}this._fnFillerPosition(j.target)}this.s.screen.y=j.pageY;this.s.screen.scrollTop=g(a).scrollTop();if(this.s.dt.oScroll.sY!==""){this.s.scroller.scrollTop=g(this.s.dt.nTable.parentNode).scrollTop();this.s.scroller.top=g(this.s.dt.nTable.parentNode).offset().top;this.s.scroller.bottom=this.s.scroller.top+g(this.s.dt.nTable.parentNode).height()}},_fnFillerFinish:function(s){var p=this,n,k,m;g(a).unbind("mousemove.AutoFill mouseup.AutoFill");this.dom.borderTop.style.display="none";this.dom.borderRight.style.display="none";this.dom.borderBottom.style.display="none";this.dom.borderLeft.style.display="none";this.s.drag.dragging=false;clearInterval(this.s.screen.interval);var y=[];var x=this.dom.table;var q=this._fnTargetCoords(this.s.drag.startTd);var w=this._fnTargetCoords(this.s.drag.endTd);var r=function(i){return p.s.dt.oApi._fnVisibleToColumnIndex(p.s.dt,i)};if(q.y<=w.y){for(n=q.y;n<=w.y;n++){if(q.x<=w.x){for(m=q.x;m<=w.x;m++){y.push({node:g("tbody>tr:eq("+n+")>td:eq("+m+")",x)[0],x:m-q.x,y:n-q.y,colIdx:r(m)})}}else{for(m=q.x;m>=w.x;m--){y.push({node:g("tbody>tr:eq("+n+")>td:eq("+m+")",x)[0],x:m-q.x,y:n-q.y,colIdx:r(m)})}}}}else{for(n=q.y;n>=w.y;n--){if(q.x<=w.x){for(m=q.x;m<=w.x;m++){y.push({node:g("tbody>tr:eq("+n+")>td:eq("+m+")",x)[0],x:m-q.x,y:n-q.y,colIdx:r(m)})}}else{for(m=q.x;m>=w.x;m--){y.push({node:g("tbody>tr:eq("+n+")>td:eq("+m+")",x)[0],x:q.x-m,y:q.y-n,colIdx:r(m)})}}}}if(y.length<=1){return}var u=[];var o;for(n=0,k=y.length;n<k;n++){var v=y[n];var l=this.s.columns[v.colIdx];var h=l.read.call(l,v.node);var t=l.step.call(l,v.node,h,o,n,v.x,v.y);l.write.call(l,v.node,t);o=t;u.push({cell:v,colIdx:v.colIdx,newValue:t,oldValue:h})}if(this.c.complete!==null){this.c.complete.call(this,u)}if(f.Api){new f.Api(this.s.dt).draw(false)}else{this.s.dt.oInstance.fnDraw()}},_fnFillerDisplay:function(k){var j=this.dom.filler;if(this.s.drag.dragging){return}var i=(k.target.nodeName.toLowerCase()=="td")?k.target:g(k.target).parents("td")[0];var h=this._fnTargetCoords(i).column;if(!this.s.columns[h].enable){j.style.display="none";return}if(k.type=="mouseover"){this.dom.currentTarget=i;this._fnFillerPosition(i);j.style.display="block"}else{if(!k.relatedTarget||!k.relatedTarget.className.match(/AutoFill/)){j.style.display="none"}}},_fnFillerPosition:function(h){var j=g(h).offset();var i=this.dom.filler;i.style.top=(j.top-(this.s.filler.height/2)-1+g(h).outerHeight())+"px";i.style.left=(j.left-(this.s.filler.width/2)-1+g(h).outerWidth())+"px"}};f.AutoFill=e;f.AutoFill=e;e.version="1.2.0";e.defaults={mode:"y",complete:null,column:{enable:true,increment:true,read:function(h){return g(h).html()},write:function(h,k){var j=g(h).parents("table");if(f.Api){j.DataTable().cell(h).data(k)}else{var i=j.dataTable();var l=i.fnGetPosition();i.fnUpdate(k,l[0],l[2],false)}},step:function(j,o,n,l,h,p){var m=/(\-?\d+)/;var k=this.increment&&n?n.match(m):null;if(k){return n.replace(m,parseInt(k[1],10)+(h<0||p<0?-1:1))}return n===d?o:n}}};return e};b(jQuery,jQuery.fn.dataTable)}(window,document));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-autoFill.min.js
jquery-dataTables-autoFill.min.js
(function ($, window, document) { /** * Switch the key value pairing of an index array to be value key (i.e. the old value is now the * key). For example consider [ 2, 0, 1 ] this would be returned as [ 1, 2, 0 ]. * @method fnInvertKeyValues * @param array aIn Array to switch around * @returns array */ function fnInvertKeyValues(aIn) { var aRet = []; for (var i = 0, iLen = aIn.length; i < iLen; i++) { aRet[ aIn[i] ] = i; } return aRet; } /** * Modify an array by switching the position of two elements * @method fnArraySwitch * @param array aArray Array to consider, will be modified by reference (i.e. no return) * @param int iFrom From point * @param int iTo Insert point * @returns void */ function fnArraySwitch(aArray, iFrom, iTo) { var mStore = aArray.splice(iFrom, 1)[0]; aArray.splice(iTo, 0, mStore); } /** * Switch the positions of nodes in a parent node (note this is specifically designed for * table rows). Note this function considers all element nodes under the parent! * @method fnDomSwitch * @param string sTag Tag to consider * @param int iFrom Element to move * @param int Point to element the element to (before this point), can be null for append * @returns void */ function fnDomSwitch(nParent, iFrom, iTo) { var anTags = []; for (var i = 0, iLen = nParent.childNodes.length; i < iLen; i++) { if (nParent.childNodes[i].nodeType == 1) { anTags.push(nParent.childNodes[i]); } } var nStore = anTags[ iFrom ]; if (iTo !== null) { nParent.insertBefore(nStore, anTags[iTo]); } else { nParent.appendChild(nStore); } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables plug-in API functions * * This are required by ColReorder in order to perform the tasks required, and also keep this * code portable, to be used for other column reordering projects with DataTables, if needed. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Plug-in for DataTables which will reorder the internal column structure by taking the column * from one position (iFrom) and insert it into a given point (iTo). * @method $.fn.dataTableExt.oApi.fnColReorder * @param object oSettings DataTables settings object - automatically added by DataTables! * @param int iFrom Take the column to be repositioned from this point * @param int iTo and insert it into this point * @returns void */ $.fn.dataTableExt.oApi.fnColReorder = function (oSettings, iFrom, iTo) { var i, iLen, j, jLen, iCols = oSettings.aoColumns.length, nTrs, oCol; /* Sanity check in the input */ if (iFrom == iTo) { /* Pointless reorder */ return; } if (iFrom < 0 || iFrom >= iCols) { this.oApi._fnLog(oSettings, 1, "ColReorder 'from' index is out of bounds: " + iFrom); return; } if (iTo < 0 || iTo >= iCols) { this.oApi._fnLog(oSettings, 1, "ColReorder 'to' index is out of bounds: " + iTo); return; } /* * Calculate the new column array index, so we have a mapping between the old and new */ var aiMapping = []; for (i = 0, iLen = iCols; i < iLen; i++) { aiMapping[i] = i; } fnArraySwitch(aiMapping, iFrom, iTo); var aiInvertMapping = fnInvertKeyValues(aiMapping); /* * Convert all internal indexing to the new column order indexes */ /* Sorting */ for (i = 0, iLen = oSettings.aaSorting.length; i < iLen; i++) { oSettings.aaSorting[i][0] = aiInvertMapping[ oSettings.aaSorting[i][0] ]; } /* Fixed sorting */ if (oSettings.aaSortingFixed !== null) { for (i = 0, iLen = oSettings.aaSortingFixed.length; i < iLen; i++) { oSettings.aaSortingFixed[i][0] = aiInvertMapping[ oSettings.aaSortingFixed[i][0] ]; } } /* Data column sorting (the column which the sort for a given column should take place on) */ for (i = 0, iLen = iCols; i < iLen; i++) { oCol = oSettings.aoColumns[i]; for (j = 0, jLen = oCol.aDataSort.length; j < jLen; j++) { oCol.aDataSort[j] = aiInvertMapping[ oCol.aDataSort[j] ]; } } /* Update the Get and Set functions for each column */ for (i = 0, iLen = iCols; i < iLen; i++) { oCol = oSettings.aoColumns[i]; if (typeof oCol.mData == 'number') { oCol.mData = aiInvertMapping[ oCol.mData ]; oCol.fnGetData = oSettings.oApi._fnGetObjectDataFn(oCol.mData); oCol.fnSetData = oSettings.oApi._fnSetObjectDataFn(oCol.mData); } } /* * Move the DOM elements */ if (oSettings.aoColumns[iFrom].bVisible) { /* Calculate the current visible index and the point to insert the node before. The insert * before needs to take into account that there might not be an element to insert before, * in which case it will be null, and an appendChild should be used */ var iVisibleIndex = this.oApi._fnColumnIndexToVisible(oSettings, iFrom); var iInsertBeforeIndex = null; i = iTo < iFrom ? iTo : iTo + 1; while (iInsertBeforeIndex === null && i < iCols) { iInsertBeforeIndex = this.oApi._fnColumnIndexToVisible(oSettings, i); i++; } /* Header */ nTrs = oSettings.nTHead.getElementsByTagName('tr'); for (i = 0, iLen = nTrs.length; i < iLen; i++) { fnDomSwitch(nTrs[i], iVisibleIndex, iInsertBeforeIndex); } /* Footer */ if (oSettings.nTFoot !== null) { nTrs = oSettings.nTFoot.getElementsByTagName('tr'); for (i = 0, iLen = nTrs.length; i < iLen; i++) { fnDomSwitch(nTrs[i], iVisibleIndex, iInsertBeforeIndex); } } /* Body */ for (i = 0, iLen = oSettings.aoData.length; i < iLen; i++) { if (oSettings.aoData[i].nTr !== null) { fnDomSwitch(oSettings.aoData[i].nTr, iVisibleIndex, iInsertBeforeIndex); } } } /* * Move the internal array elements */ /* Columns */ fnArraySwitch(oSettings.aoColumns, iFrom, iTo); /* Search columns */ fnArraySwitch(oSettings.aoPreSearchCols, iFrom, iTo); /* Array array - internal data anodes cache */ for (i = 0, iLen = oSettings.aoData.length; i < iLen; i++) { if ($.isArray(oSettings.aoData[i]._aData)) { fnArraySwitch(oSettings.aoData[i]._aData, iFrom, iTo); } fnArraySwitch(oSettings.aoData[i]._anHidden, iFrom, iTo); } /* Reposition the header elements in the header layout array */ for (i = 0, iLen = oSettings.aoHeader.length; i < iLen; i++) { fnArraySwitch(oSettings.aoHeader[i], iFrom, iTo); } if (oSettings.aoFooter !== null) { for (i = 0, iLen = oSettings.aoFooter.length; i < iLen; i++) { fnArraySwitch(oSettings.aoFooter[i], iFrom, iTo); } } /* * Update DataTables' event handlers */ /* Sort listener */ for (i = 0, iLen = iCols; i < iLen; i++) { //Martin Marchetta: //Update this field which is the one used by DataTables for getting the column's data for sorting. oSettings.aoColumns[i].aDataSort = [i]; //Update the internal column index, since columns are actually being re-ordered in the internal structure oSettings.aoColumns[i]._ColReorder_iOrigCol = i; /////////////////////////////////// $(oSettings.aoColumns[i].nTh).unbind('click'); this.oApi._fnSortAttachListener(oSettings, oSettings.aoColumns[i].nTh, i); } /* * Any extra operations for the other plug-ins */ if (typeof ColVis != 'undefined') { ColVis.fnRebuild(oSettings.oInstance); } /* Fire an event so other plug-ins can update */ $(oSettings.oInstance).trigger('column-reorder', [ oSettings, { "iFrom": iFrom, "iTo": iTo, "aiInvertMapping": aiInvertMapping } ]); if (typeof oSettings.oInstance._oPluginFixedHeader != 'undefined') { oSettings.oInstance._oPluginFixedHeader.fnUpdate(); } }; /** * ColReorder provides column visiblity control for DataTables * @class ColReorder * @constructor * @param {object} DataTables settings object * @param {object} ColReorder options */ ColReorder = function (oDTSettings, oOpts) { /* Santiy check that we are a new instance */ if (!this.CLASS || this.CLASS != "ColReorder") { alert("Warning: ColReorder must be initialised with the keyword 'new'"); } if (typeof oOpts == 'undefined') { oOpts = {}; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for ColReorder instance */ this.s = { /** * DataTables settings object * @property dt * @type Object * @default null */ "dt": null, /** * Initialisation object used for this instance * @property init * @type object * @default {} */ "init": oOpts, /** * Allow Reorder functionnality * @property allowReorder * @type boolean * @default true */ "allowReorder": true, /** * Allow Resize functionnality * @property allowResize * @type boolean * @default true */ "allowResize": true, /** * Number of columns to fix (not allow to be reordered) * @property fixed * @type int * @default 0 */ "fixed": 0, /** * Callback function for once the reorder has been done * @property dropcallback * @type function * @default null */ "dropCallback": null, /** * @namespace Information used for the mouse drag */ "mouse": { "startX": -1, "startY": -1, "offsetX": -1, "offsetY": -1, "target": -1, "targetIndex": -1, "fromIndex": -1 }, /** * Information which is used for positioning the insert cusor and knowing where to do the * insert. Array of objects with the properties: * x: x-axis position * to: insert point * @property aoTargets * @type array * @default [] */ "aoTargets": [] }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * Dragging element (the one the mouse is moving) * @property drag * @type element * @default null */ "drag": null, /** * Resizing a column * @property drag * @type element * @default null */ "resize": null, /** * The insert cursor * @property pointer * @type element * @default null */ "pointer": null }; ///////////////// //Martin Marchetta: keep the current table's size in order to resize it if columns are resized and scrollX is enabled this.table_size = -1; ///////////////// /* Constructor logic */ this.s.dt = oDTSettings.oInstance.fnSettings(); this._fnConstruct(); /* Add destroy callback */ oDTSettings.oApi._fnCallbackReg(oDTSettings, 'aoDestroyCallback', jQuery.proxy(this._fnDestroy, this), 'ColReorder'); /* Store the instance for later use */ ColReorder.aoInstances.push(this); return this; }; ColReorder.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ "fnReset": function () { var a = []; for (var i = 0, iLen = this.s.dt.aoColumns.length; i < iLen; i++) { a.push(this.s.dt.aoColumns[i]._ColReorder_iOrigCol); } this._fnOrderColumns(a); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Constructor logic * @method _fnConstruct * @returns void * @private */ "_fnConstruct": function () { var that = this; var i, iLen; /* allow reorder */ if (typeof this.s.init.allowReorder != 'undefined') { this.s.allowReorder = this.s.init.allowReorder; } /* allow resize */ if (typeof this.s.init.allowResize != 'undefined') { this.s.allowResize = this.s.init.allowResize; } /* Columns discounted from reordering - counting left to right */ if (typeof this.s.init.iFixedColumns != 'undefined') { this.s.fixed = this.s.init.iFixedColumns; } /* Drop callback initialisation option */ if (typeof this.s.init.fnReorderCallback != 'undefined') { this.s.dropCallback = this.s.init.fnReorderCallback; } /* Add event handlers for the drag and drop, and also mark the original column order */ for (i = 0, iLen = this.s.dt.aoColumns.length; i < iLen; i++) { if (i > this.s.fixed - 1) { this._fnMouseListener(i, this.s.dt.aoColumns[i].nTh); } /* Mark the original column order for later reference */ this.s.dt.aoColumns[i]._ColReorder_iOrigCol = i; } /* State saving */ this.s.dt.oApi._fnCallbackReg(this.s.dt, 'aoStateSaveParams', function (oS, oData) { that._fnStateSave.call(that, oData); }, "ColReorder_State"); /* An initial column order has been specified */ var aiOrder = null; if (typeof this.s.init.aiOrder != 'undefined') { aiOrder = this.s.init.aiOrder.slice(); } /* State loading, overrides the column order given */ if (this.s.dt.oLoadedState && typeof this.s.dt.oLoadedState.ColReorder != 'undefined' && this.s.dt.oLoadedState.ColReorder.length == this.s.dt.aoColumns.length) { aiOrder = this.s.dt.oLoadedState.ColReorder; } /* If we have an order to apply - do so */ if (aiOrder) { /* We might be called during or after the DataTables initialisation. If before, then we need * to wait until the draw is done, if after, then do what we need to do right away */ if (!that.s.dt._bInitComplete) { var bDone = false; this.s.dt.aoDrawCallback.push({ "fn": function () { if (!that.s.dt._bInitComplete && !bDone) { bDone = true; var resort = fnInvertKeyValues(aiOrder); that._fnOrderColumns.call(that, resort); } }, "sName": "ColReorder_Pre" }); } else { var resort = fnInvertKeyValues(aiOrder); that._fnOrderColumns.call(that, resort); } } }, /** * Set the column order from an array * @method _fnOrderColumns * @param array a An array of integers which dictate the column order that should be applied * @returns void * @private */ "_fnOrderColumns": function (a) { if (a.length != this.s.dt.aoColumns.length) { this.s.dt.oInstance.oApi._fnLog(oDTSettings, 1, "ColReorder - array reorder does not " + "match known number of columns. Skipping."); return; } for (var i = 0, iLen = a.length; i < iLen; i++) { var currIndex = $.inArray(i, a); if (i != currIndex) { /* Reorder our switching array */ fnArraySwitch(a, currIndex, i); /* Do the column reorder in the table */ this.s.dt.oInstance.fnColReorder(currIndex, i); } } /* When scrolling we need to recalculate the column sizes to allow for the shift */ if (this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "") { this.s.dt.oInstance.fnAdjustColumnSizing(); } /* Save the state */ this.s.dt.oInstance.oApi._fnSaveState(this.s.dt); }, /** * Because we change the indexes of columns in the table, relative to their starting point * we need to reorder the state columns to what they are at the starting point so we can * then rearrange them again on state load! * @method _fnStateSave * @param object oState DataTables state * @returns string JSON encoded cookie string for DataTables * @private */ "_fnStateSave": function (oState) { var i, iLen, aCopy, iOrigColumn; var oSettings = this.s.dt; /* Sorting */ for (i = 0; i < oState.aaSorting.length; i++) { oState.aaSorting[i][0] = oSettings.aoColumns[ oState.aaSorting[i][0] ]._ColReorder_iOrigCol; } aSearchCopy = $.extend(true, [], oState.aoSearchCols); oState.ColReorder = []; for (i = 0, iLen = oSettings.aoColumns.length; i < iLen; i++) { iOrigColumn = oSettings.aoColumns[i]._ColReorder_iOrigCol; /* Column filter */ oState.aoSearchCols[ iOrigColumn ] = aSearchCopy[i]; /* Visibility */ oState.abVisCols[ iOrigColumn ] = oSettings.aoColumns[i].bVisible; /* Column reordering */ oState.ColReorder.push(iOrigColumn); } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Mouse drop and drag */ /** * Add a mouse down listener to a particluar TH element * @method _fnMouseListener * @param int i Column index * @param element nTh TH element clicked on * @returns void * @private */ "_fnMouseListener": function (i, nTh) { var that = this; //Martin Marchetta (rebind events since after column re-order they use wrong column indices) $(nTh).unbind('mousemove.ColReorder'); $(nTh).unbind('mousedown.ColReorder'); //////////////// // listen to mousemove event for resize if (this.s.allowResize) { $(nTh).bind('mousemove.ColReorder', function (e) { if (that.dom.drag === null && that.dom.resize === null) { /* Store information about the mouse position */ var nThTarget = e.target.nodeName == "TH" ? e.target : $(e.target).parents('TH')[0]; var offset = $(nThTarget).offset(); var nLength = $(nThTarget).innerWidth(); /* are we on the col border (if so, resize col) */ if (Math.abs(e.pageX - Math.round(offset.left + nLength)) <= 5) { $(nThTarget).css({'cursor': 'col-resize'}); } else $(nThTarget).css({'cursor': 'pointer'}); } }); } // listen to mousedown event $(nTh).bind('mousedown.ColReorder', function (e) { that._fnMouseDown.call(that, e, nTh, i); //Martin Marchetta: added the index of the column dragged or resized return false; }); }, /** * Mouse down on a TH element in the table header * @method _fnMouseDown * @param event e Mouse event * @param element nTh TH element to be dragged * @param i The column that's resized/dragged * @returns void * @private */ "_fnMouseDown": function (e, nTh, i) { var that = this, aoColumns = this.s.dt.aoColumns; /* are we resizing a column ? */ if ($(nTh).css('cursor') == 'col-resize') { this.s.mouse.startX = e.pageX; this.s.mouse.startWidth = $(nTh).width(); this.s.mouse.resizeElem = $(nTh); var nThNext = $(nTh).next(); this.s.mouse.nextStartWidth = $(nThNext).width(); that.dom.resize = true; //////////////////// //Martin Marchetta //a. Disable column sorting so as to avoid issues when finishing column resizing this.s.dt.aoColumns[i].bSortable = false; //b. Disable Autowidth feature (now the user is in charge of setting column width so keeping this enabled looses changes after operations) this.s.dt.oFeatures.bAutoWidth = false; //////////////////// } else if (this.s.allowReorder) { that.dom.resize = null; /* Store information about the mouse position */ var nThTarget = e.target.nodeName == "TH" ? e.target : $(e.target).parents('TH')[0]; var offset = $(nThTarget).offset(); this.s.mouse.startX = e.pageX; this.s.mouse.startY = e.pageY; this.s.mouse.offsetX = e.pageX - offset.left; this.s.mouse.offsetY = e.pageY - offset.top; this.s.mouse.target = nTh; this.s.mouse.targetIndex = $('th', nTh.parentNode).index(nTh); this.s.mouse.fromIndex = this.s.dt.oInstance.oApi._fnVisibleToColumnIndex(this.s.dt, this.s.mouse.targetIndex); /* Calculate a cached array with the points of the column inserts, and the 'to' points */ this.s.aoTargets.splice(0, this.s.aoTargets.length); this.s.aoTargets.push({ "x": $(this.s.dt.nTable).offset().left, "to": 0 }); var iToPoint = 0; for (var i = 0, iLen = aoColumns.length; i < iLen; i++) { /* For the column / header in question, we want it's position to remain the same if the * position is just to it's immediate left or right, so we only incremement the counter for * other columns */ if (i != this.s.mouse.fromIndex) { iToPoint++; } if (aoColumns[i].bVisible) { this.s.aoTargets.push({ "x": $(aoColumns[i].nTh).offset().left + $(aoColumns[i].nTh).outerWidth(), "to": iToPoint }); } } /* Disallow columns for being reordered by drag and drop, counting left to right */ if (this.s.fixed !== 0) { this.s.aoTargets.splice(0, this.s.fixed); } } /* Add event handlers to the document */ $(document).bind('mousemove.ColReorder', function (e) { that._fnMouseMove.call(that, e, i); //Martin Marchetta: Added index of the call being dragged or resized }); $(document).bind('mouseup.ColReorder', function (e) { //Martin Marcheta: Added this small delay in order to prevent collision with column sort feature (there must be a better //way of doing this, but I don't have more time to digg into it) setTimeout(function () { that._fnMouseUp.call(that, e, i); //Martin Marchetta: Added index of the call being dragged or resized }, 10); }); }, /** * Deal with a mouse move event while dragging a node * @method _fnMouseMove * @param event e Mouse event * @param colResized Index of the column that's being dragged or resized (index within the internal model, not the visible order) * @returns void * @private */ "_fnMouseMove": function (e, colResized) { var that = this; //////////////////// //Martin Marchetta: Determine if ScrollX is enabled var scrollXEnabled; scrollXEnabled = this.s.dt.oInit.sScrollX === "" ? false : true; //Keep the current table's width (used in case sScrollX is enabled to resize the whole table, giving an Excel-like behavior) if (this.table_size < 0 && scrollXEnabled && $('div.dataTables_scrollHead', this.s.dt.nTableWrapper) != undefined) { if ($('div.dataTables_scrollHead', this.s.dt.nTableWrapper).length > 0) this.table_size = $($('div.dataTables_scrollHead', this.s.dt.nTableWrapper)[0].childNodes[0].childNodes[0]).width(); } //////////////////// /* are we resizing a column ? */ if (this.dom.resize) { var nTh = this.s.mouse.resizeElem; var nThNext = $(nTh).next(); var moveLength = e.pageX - this.s.mouse.startX; if (moveLength != 0 && !scrollXEnabled) $(nThNext).width(this.s.mouse.nextStartWidth - moveLength); $(nTh).width(this.s.mouse.startWidth + moveLength); //Martin Marchetta: Resize the header too (if sScrollX is enabled) if (scrollXEnabled && $('div.dataTables_scrollHead', this.s.dt.nTableWrapper) != undefined) { if ($('div.dataTables_scrollHead', this.s.dt.nTableWrapper).length > 0) $($('div.dataTables_scrollHead', this.s.dt.nTableWrapper)[0].childNodes[0].childNodes[0]).width(this.table_size + moveLength); } //////////////////////// //Martin Marchetta: Fixed col resizing when the scroller is enabled. var visibleColumnIndex; //First determine if this plugin is being used along with the smart scroller... if ($('div.dataTables_scrollBody') != null) { //...if so, when resizing the header, also resize the table's body (when enabling the Scroller, the table's header and //body are split into different tables, so the column resizing doesn't work anymore) if ($('div.dataTables_scrollBody').length > 0) { //Since some columns might have been hidden, find the correct one to resize in the table's body var currentColumnIndex; visibleColumnIndex = -1; for (currentColumnIndex = -1; currentColumnIndex < this.s.dt.aoColumns.length - 1 && currentColumnIndex != colResized; currentColumnIndex++) { if (this.s.dt.aoColumns[currentColumnIndex + 1].bVisible) visibleColumnIndex++; } //Get the scroller's div tableScroller = $('div.dataTables_scrollBody', this.s.dt.nTableWrapper)[0]; //Get the table scrollingTableHead = $(tableScroller)[0].childNodes[0].childNodes[0].childNodes[0]; //Resize the columns if (moveLength != 0 && !scrollXEnabled) { $($(scrollingTableHead)[0].childNodes[visibleColumnIndex + 1]).width(this.s.mouse.nextStartWidth - moveLength); } $($(scrollingTableHead)[0].childNodes[visibleColumnIndex]).width(this.s.mouse.startWidth + moveLength); //Resize the table too if (scrollXEnabled) $($(tableScroller)[0].childNodes[0]).width(this.table_size + moveLength); } } //////////////////////// return; } else if (this.s.allowReorder) { if (this.dom.drag === null) { /* Only create the drag element if the mouse has moved a specific distance from the start * point - this allows the user to make small mouse movements when sorting and not have a * possibly confusing drag element showing up */ if (Math.pow( Math.pow(e.pageX - this.s.mouse.startX, 2) + Math.pow(e.pageY - this.s.mouse.startY, 2), 0.5) < 5) { return; } this._fnCreateDragNode(); } /* Position the element - we respect where in the element the click occured */ this.dom.drag.style.left = (e.pageX - this.s.mouse.offsetX) + "px"; this.dom.drag.style.top = (e.pageY - this.s.mouse.offsetY) + "px"; /* Based on the current mouse position, calculate where the insert should go */ var bSet = false; for (var i = 1, iLen = this.s.aoTargets.length; i < iLen; i++) { if (e.pageX < this.s.aoTargets[i - 1].x + ((this.s.aoTargets[i].x - this.s.aoTargets[i - 1].x) / 2)) { this.dom.pointer.style.left = this.s.aoTargets[i - 1].x + "px"; this.s.mouse.toIndex = this.s.aoTargets[i - 1].to; bSet = true; break; } } /* The insert element wasn't positioned in the array (less than operator), so we put it at * the end */ if (!bSet) { this.dom.pointer.style.left = this.s.aoTargets[this.s.aoTargets.length - 1].x + "px"; this.s.mouse.toIndex = this.s.aoTargets[this.s.aoTargets.length - 1].to; } } }, /** * Finish off the mouse drag and insert the column where needed * @method _fnMouseUp * @param event e Mouse event * @param colResized The index of the column that was just dragged or resized (index within the internal model, not the visible order). * @returns void * @private */ "_fnMouseUp": function (e, colResized) { var that = this; $(document).unbind('mousemove.ColReorder'); $(document).unbind('mouseup.ColReorder'); if (this.dom.drag !== null) { /* Remove the guide elements */ document.body.removeChild(this.dom.drag); document.body.removeChild(this.dom.pointer); this.dom.drag = null; this.dom.pointer = null; /* Actually do the reorder */ this.s.dt.oInstance.fnColReorder(this.s.mouse.fromIndex, this.s.mouse.toIndex); /* When scrolling we need to recalculate the column sizes to allow for the shift */ if (this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "") { this.s.dt.oInstance.fnAdjustColumnSizing(); } if (this.s.dropCallback !== null) { this.s.dropCallback.call(this); } //////////// //Martin Marchetta: Re-initialize so as to register the new column order //(otherwise the events remain bound to the original column indices) this._fnConstruct(); /////////// /* Save the state */ this.s.dt.oInstance.oApi._fnSaveState(this.s.dt); } /////////////////////////////////////////////////////// //Martin Marchetta else if (this.dom.resize !== null) { var i; var j; var currentColumn; var nextVisibleColumnIndex; var previousVisibleColumnIndex; var scrollXEnabled; //Re-enable column sorting this.s.dt.aoColumns[colResized].bSortable = true; //Save the new resized column's width this.s.dt.aoColumns[colResized].sWidth = $(this.s.mouse.resizeElem).innerWidth() + "px"; //If other columns might have changed their size, save their size too scrollXEnabled = this.s.dt.oInit.sScrollX === "" ? false : true; if (!scrollXEnabled) { //The colResized index (internal model) here might not match the visible index since some columns might have been hidden for (nextVisibleColumnIndex = colResized + 1; nextVisibleColumnIndex < this.s.dt.aoColumns.length; nextVisibleColumnIndex++) { if (this.s.dt.aoColumns[nextVisibleColumnIndex].bVisible) break; } for (previousVisibleColumnIndex = colResized - 1; previousVisibleColumnIndex >= 0; previousVisibleColumnIndex--) { if (this.s.dt.aoColumns[previousVisibleColumnIndex].bVisible) break; } if (this.s.dt.aoColumns.length > nextVisibleColumnIndex) this.s.dt.aoColumns[nextVisibleColumnIndex].sWidth = $(this.s.mouse.resizeElem).next().innerWidth() + "px"; else { //The column resized is the right-most, so save the sizes of all the columns at the left currentColumn = this.s.mouse.resizeElem; for (i = previousVisibleColumnIndex; i > 0; i--) { if (this.s.dt.aoColumns[i].bVisible) { currentColumn = $(currentColumn).prev(); this.s.dt.aoColumns[i].sWidth = $(currentColumn).innerWidth() + "px"; } } } } //Update the internal storage of the table's width (in case we changed it because the user resized some column and scrollX was enabled if (scrollXEnabled && $('div.dataTables_scrollHead', this.s.dt.nTableWrapper) != undefined) { if ($('div.dataTables_scrollHead', this.s.dt.nTableWrapper).length > 0) this.table_size = $($('div.dataTables_scrollHead', this.s.dt.nTableWrapper)[0].childNodes[0].childNodes[0]).width(); } //Save the state this.s.dt.oInstance.oApi._fnSaveState(this.s.dt); } /////////////////////////////////////////////////////// this.dom.resize = null; }, /** * Copy the TH element that is being drags so the user has the idea that they are actually * moving it around the page. * @method _fnCreateDragNode * @returns void * @private */ "_fnCreateDragNode": function () { var that = this; this.dom.drag = $(this.s.dt.nTHead.parentNode).clone(true)[0]; this.dom.drag.className += " DTCR_clonedTable"; while (this.dom.drag.getElementsByTagName('caption').length > 0) { this.dom.drag.removeChild(this.dom.drag.getElementsByTagName('caption')[0]); } while (this.dom.drag.getElementsByTagName('tbody').length > 0) { this.dom.drag.removeChild(this.dom.drag.getElementsByTagName('tbody')[0]); } while (this.dom.drag.getElementsByTagName('tfoot').length > 0) { this.dom.drag.removeChild(this.dom.drag.getElementsByTagName('tfoot')[0]); } $('thead tr:eq(0)', this.dom.drag).each(function () { $('th:not(:eq(' + that.s.mouse.targetIndex + '))', this).remove(); }); $('tr', this.dom.drag).height($('tr:eq(0)', that.s.dt.nTHead).height()); $('thead tr:gt(0)', this.dom.drag).remove(); $('thead th:eq(0)', this.dom.drag).each(function (i) { this.style.width = $('th:eq(' + that.s.mouse.targetIndex + ')', that.s.dt.nTHead).width() + "px"; }); this.dom.drag.style.position = "absolute"; this.dom.drag.style.zIndex = 1200; this.dom.drag.style.top = "0px"; this.dom.drag.style.left = "0px"; this.dom.drag.style.width = $('th:eq(' + that.s.mouse.targetIndex + ')', that.s.dt.nTHead).outerWidth() + "px"; this.dom.pointer = document.createElement('div'); this.dom.pointer.className = "DTCR_pointer"; this.dom.pointer.style.position = "absolute"; if (this.s.dt.oScroll.sX === "" && this.s.dt.oScroll.sY === "") { this.dom.pointer.style.top = $(this.s.dt.nTable).offset().top + "px"; this.dom.pointer.style.height = $(this.s.dt.nTable).height() + "px"; } else { this.dom.pointer.style.top = $('div.dataTables_scroll', this.s.dt.nTableWrapper).offset().top + "px"; this.dom.pointer.style.height = $('div.dataTables_scroll', this.s.dt.nTableWrapper).height() + "px"; } document.body.appendChild(this.dom.pointer); document.body.appendChild(this.dom.drag); }, /** * Clean up ColReorder memory references and event handlers * @method _fnDestroy * @returns void * @private */ "_fnDestroy": function () { for (var i = 0, iLen = ColReorder.aoInstances.length; i < iLen; i++) { if (ColReorder.aoInstances[i] === this) { ColReorder.aoInstances.splice(i, 1); break; } } $(this.s.dt.nTHead).find('*').unbind('.ColReorder'); this.s.dt.oInstance._oPluginColReorder = null; this.s = null; } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static parameters * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Array of all ColReorder instances for later reference * @property ColReorder.aoInstances * @type array * @default [] * @static */ ColReorder.aoInstances = []; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static functions * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Reset the column ordering for a DataTables instance * @method ColReorder.fnReset * @param object oTable DataTables instance to consider * @returns void * @static */ ColReorder.fnReset = function (oTable) { for (var i = 0, iLen = ColReorder.aoInstances.length; i < iLen; i++) { if (ColReorder.aoInstances[i].s.dt.oInstance == oTable) { ColReorder.aoInstances[i].fnReset(); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Name of this class * @constant CLASS * @type String * @default ColReorder */ ColReorder.prototype.CLASS = "ColReorder"; /** * ColReorder version * @constant VERSION * @type String * @default As code */ ColReorder.VERSION = "1.0.7"; ColReorder.prototype.VERSION = ColReorder.VERSION; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Register a new feature with DataTables */ if (typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.9.3')) { $.fn.dataTableExt.aoFeatures.push({ "fnInit": function (oDTSettings) { var oTable = oDTSettings.oInstance; if (typeof oTable._oPluginColReorder == 'undefined') { var opts = typeof oDTSettings.oInit.oColReorder != 'undefined' ? oDTSettings.oInit.oColReorder : {}; oTable._oPluginColReorder = new ColReorder(oDTSettings, opts); } else { oTable.oApi._fnLog(oDTSettings, 1, "ColReorder attempted to initialise twice. Ignoring second"); } return null; /* No node to insert */ }, "cFeature": "R", "sFeature": "ColReorder" }); } else { alert("Warning: ColReorder requires DataTables 1.9.3 or greater - www.datatables.net/download"); } })(jQuery, window, document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-colReorderWithResize.js
jquery-dataTables-colReorderWithResize.js
(function ($) { $.extend({ progressBar: new function () { this.defaults = { steps: 20, // steps taken to reach target step_duration: 20, max: 100, // Upon 100% i'd assume, but configurable showText: true, // show text with percentage in next to the progressbar? - default : true textFormat: 'percentage', // Or otherwise, set to 'fraction' width: 120, // Width of the progressbar - don't forget to adjust your image too!!! // Image to use in the progressbar. Can be a single image too: 'images/progressbg_green.gif' height: 12, // Height of the progressbar - don't forget to adjust your image too!!! callback: null, // Calls back with the config object that has the current percentage, target percentage, current image, etc boxImage: '/--static--/ztfy.jqueryui/img/progressbar.gif', // boxImage : image around the progress bar barImage: { 0: '/--static--/ztfy.jqueryui/img/progressbg_red.gif', 30: '/--static--/ztfy.jqueryui/img/progressbg_orange.gif', 70: '/--static--/ztfy.jqueryui/img/progressbg_green.gif' }, // Internal use running_value: 0, value: 0, image: null }; /* public methods */ this.construct = function (arg1, arg2) { var argvalue = null; var argconfig = null; if (arg1 != null) { if (!isNaN(arg1)) { argvalue = arg1; if (arg2 != null) { argconfig = arg2; } } else { argconfig = arg1; } } return this.each(function (child) { var pb = this; var config = this.config; if (argvalue != null && this.bar != null && this.config != null) { this.config.value = argvalue if (argconfig != null) pb.config = $.extend(this.config, argconfig); config = pb.config; } else { var $this = $(this); var config = $.extend({}, $.progressBar.defaults, argconfig); config.id = $this.attr('id') ? $this.attr('id') : Math.ceil(Math.random() * 100000); // random id, if none provided if (argvalue == null) argvalue = $this.html().replace("%", "") // parse percentage config.value = argvalue; config.running_value = 0; config.image = getBarImage(config); $this.html(""); var bar = document.createElement('img'); var text = document.createElement('span'); var $bar = $(bar); var $text = $(text); pb.bar = $bar; $bar.attr('id', config.id + "_pbImage"); $text.attr('id', config.id + "_pbText"); $text.html(getText(config)); $bar.attr('title', getText(config)); $bar.attr('alt', getText(config)); $bar.attr('src', config.boxImage); $bar.attr('width', config.width); $bar.css("width", config.width + "px"); $bar.css("height", config.height + "px"); $bar.css("background-image", "url(" + config.image + ")"); $bar.css("background-position", ((config.width * -1)) + 'px 50%'); $bar.css("padding", "0"); $bar.css("margin", "0"); $this.append($bar); $this.append($text); } function getPercentage(config) { return config.running_value * 100 / config.max; } function getBarImage(config) { var image = config.barImage; if (typeof(config.barImage) == 'object') { for (var i in config.barImage) { if (getPercentage(config) >= parseInt(i)) { image = config.barImage[i]; } else { break; } } } return image; } function getText(config) { if (config.showText) { if (config.textFormat == 'percentage') { return " " + Math.round(config.running_value) + "%"; } else if (config.textFormat == 'fraction') { return " " + config.running_value + '/' + config.max; } } } config.increment = Math.round((config.value - config.running_value) / config.steps); if (config.increment < 0) config.increment *= -1; if (config.increment < 1) config.increment = 1; var t = setInterval(function () { var pixels = config.width / 100; // Define how many pixels go into 1% var stop = false; if (config.running_value > config.value) { if (config.running_value - config.increment < config.value) { config.running_value = config.value; } else { config.running_value -= config.increment; } } else if (config.running_value < config.value) { if (config.running_value + config.increment > config.value) { config.running_value = config.value; } else { config.running_value += config.increment; } } if (config.running_value == config.value) clearInterval(t); var $bar = $("#" + config.id + "_pbImage"); var $text = $("#" + config.id + "_pbText"); var image = getBarImage(config); if (image != config.image) { $bar.css("background-image", "url(" + image + ")"); config.image = image; } $bar.css("background-position", (((config.width * -1)) + (getPercentage(config) * pixels)) + 'px 50%'); $bar.attr('title', getText(config)); $text.html(getText(config)); if (config.callback != null && typeof(config.callback) == 'function') config.callback(config); pb.config = config; }, config.step_duration); }); }; this.submit = function (form) { var files = $('input:file', form); if (files.length > 0) { var frame = $('iframe[name=progress]', form); if (frame.length > 0) { var uuid = ""; for (var i = 0; i < 32; i++) { uuid += Math.floor(Math.random() * 16).toString(16); } var action = $(form).attr("action"); if (old_id = /X-Progress-ID=([^&]+)/.exec(action)) { action = action.replace(old_id[1], uuid); } else { action = action + "?X-Progress-ID=" + uuid; } $(form).attr("action", action); var progress = $(frame).get(0).contentWindow.updateUploadProgress; if (progress) { progress(uuid); return uuid; } } } } } }); $.fn.extend({ progressBar: $.progressBar.construct }); })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-progressbar.js
jquery-progressbar.js
var KeyTable;(function(c,a,d){var b=function(f,e){KeyTable=function(x){this.block=false;this.event={remove:{}};this.fnGetCurrentPosition=function(){return[i,g]};this.fnGetCurrentData=function(){return t.innerHTML};this.fnGetCurrentTD=function(){return t};this.fnSetPosition=function(P,Q){if(typeof P=="object"&&P.nodeName){h(P)}else{h(M(P,Q))}};this.fnBlur=function(){B()};var l=null;var t=null;var i=null;var g=null;var O=null;var o="focus";var D=false;var y={action:[],esc:[],focus:[],blur:[]};var k=null;var u;var z;var K=false;function J(P){return function(Q,T,S){if((Q===null||typeof Q=="number")&&(T===null||typeof T=="number")&&typeof S=="function"){E(P,Q,T,S)}else{if(typeof Q=="object"&&typeof T=="function"){var R=q(Q);E(P,R[0],R[1],T)}else{alert("Unhandable event type was added: x"+Q+" y:"+T+" z:"+S)}}}}function j(P){return function(Q,T,S){if((Q===null||typeof arguments[0]=="number")&&(T===null||typeof arguments[1]=="number")){if(typeof arguments[2]=="function"){N(P,Q,T,S)}else{N(P,Q,T)}}else{if(typeof arguments[0]=="object"){var R=q(Q);if(typeof arguments[1]=="function"){N(P,R[0],R[1],T)}else{N(P,R[0],R[1])}}else{alert("Unhandable event type was removed: x"+Q+" y:"+T+" z:"+S)}}}}for(var v in y){if(v){this.event[v]=J(v);this.event.remove[v]=j(v)}}function E(S,P,R,Q){y[S].push({x:P,y:R,fn:Q})}function N(V,Q,U,S){var T=0;for(var R=0,P=y[V].length;R<P-T;R++){if(typeof S!="undefined"){if(y[V][R-T].x==Q&&y[V][R-T].y==U&&y[V][R-T].fn==S){y[V].splice(R-T,1);T++}}else{if(y[V][R-T].x==Q&&y[V][R-T].y==U){y[V].splice(R,1);return 1}}}return T}function H(U,P,T){var S=0;var Q=y[U];for(var R=0;R<Q.length;R++){if((Q[R].x==P&&Q[R].y==T)||(Q[R].x===null&&Q[R].y==T)||(Q[R].x==P&&Q[R].y===null)||(Q[R].x===null&&Q[R].y===null)){Q[R].fn(M(P,T),P,T);S++}}return S}function h(U,ac){if(t==U){return}if(typeof ac=="undefined"){ac=true}if(t!==null){w(t)}f(U).addClass(o);f(U).parent().addClass(o);var R;if(k){R=k;var X=m(U)[1];var Y=D;while(X>=R.fnDisplayEnd()){if(R._iDisplayLength>=0){if(R._iDisplayStart+R._iDisplayLength<R.fnRecordsDisplay()){R._iDisplayStart+=R._iDisplayLength}}else{R._iDisplayStart=0}k.oApi._fnCalculateEnd(R)}while(X<R._iDisplayStart){R._iDisplayStart=R._iDisplayLength>=0?R._iDisplayStart-R._iDisplayLength:0;if(R._iDisplayStart<0){R._iDisplayStart=0}k.oApi._fnCalculateEnd(R)}k.oApi._fnDraw(R);D=Y}var V=q(U);t=U;i=V[0];g=V[1];var Z,ab,T,W,P,Q,aa;if(ac){Z=f(c).height();ab=f(c).width();T=f(a).scrollTop();W=f(a).scrollLeft();P=U.offsetHeight;Q=U.offsetWidth;aa=F(U);if(k&&typeof R.oScroll!="undefined"&&(R.oScroll.sX!==""||R.oScroll.sY!=="")){aa[1]-=f(R.nTable.parentNode).scrollTop();aa[0]-=f(R.nTable.parentNode).scrollLeft()}if(aa[1]+P>T+Z){G(aa[1]+P-Z)}else{if(aa[1]<T){G(aa[1])}}if(aa[0]+Q>W+ab){A(aa[0]+Q-ab)}else{if(aa[0]<W){A(aa[0])}}}if(k&&typeof R.oScroll!="undefined"&&(R.oScroll.sX!==""||R.oScroll.sY!=="")){var S=R.nTable.parentNode;Z=S.clientHeight;ab=S.clientWidth;T=S.scrollTop;W=S.scrollLeft;P=U.offsetHeight;Q=U.offsetWidth;if(U.offsetTop+P>Z+T){S.scrollTop=(U.offsetTop+P)-Z}else{if(U.offsetTop<T){S.scrollTop=U.offsetTop}}if(U.offsetLeft+Q>ab+W){S.scrollLeft=(U.offsetLeft+Q)-ab}else{if(U.offsetLeft<W){S.scrollLeft=U.offsetLeft}}}L();H("focus",i,g)}function B(){w(t);i=null;g=null;t=null;r()}function w(P){f(P).removeClass(o);f(P).parent().removeClass(o);H("blur",i,g)}function s(P){var Q=this;while(Q.nodeName!="TD"){Q=Q.parentNode}h(Q);L()}function n(U){if(O.block||!D){return true}if(U.metaKey||U.altKey||U.ctrlKey){return true}var Q,V,T=l.getElementsByTagName("tr")[0].getElementsByTagName("td").length,P;if(k){P=k.aiDisplay.length;var S=m(t);if(S===null){return}i=S[0];g=S[1]}else{P=l.getElementsByTagName("tr").length}var R=(U.keyCode==9&&U.shiftKey)?-1:U.keyCode;switch(R){case 13:U.preventDefault();U.stopPropagation();H("action",i,g);return true;case 27:if(!H("esc",i,g)){B();return}Q=i;V=g;break;case -1:case 37:if(i>0){Q=i-1;V=g}else{if(g>0){Q=T-1;V=g-1}else{if(R==-1&&u){K=true;z.focus();setTimeout(function(){K=false},0);D=false;B();return true}else{return false}}}break;case 38:if(g>0){Q=i;V=g-1}else{return false}break;case 36:Q=i;V=0;break;case 33:Q=i;V=g-10;if(V<0){V=0}break;case 9:case 39:if(i<T-1){Q=i+1;V=g}else{if(g<P-1){Q=0;V=g+1}else{if(R==9&&u){K=true;z.focus();setTimeout(function(){K=false},0);D=false;B();return true}else{return false}}}break;case 40:if(g<P-1){Q=i;V=g+1}else{return false}break;case 35:Q=i;V=P-1;break;case 34:Q=i;V=g+10;if(V>P-1){V=P-1}break;default:return true}h(M(Q,V));return false}function L(){if(!D){D=true}}function r(){D=false}function M(P,Q){if(k){if(typeof k.aoData[k.aiDisplay[Q]]!="undefined"){return k.aoData[k.aiDisplay[Q]].nTr.getElementsByTagName("td")[P]}else{return null}}else{return f("tr:eq("+Q+")>td:eq("+P+")",l)[0]}}function q(P){if(k){return[f("td",P.parentNode).index(P),f("tr",P.parentNode.parentNode).index(P.parentNode)+k._iDisplayStart]}else{return[f("td",P.parentNode).index(P),f("tr",P.parentNode.parentNode).index(P.parentNode)]}}function G(P){a.documentElement.scrollTop=P;a.body.scrollTop=P}function A(P){a.documentElement.scrollLeft=P;a.body.scrollLeft=P}function F(R){var Q=0;var P=0;if(R.offsetParent){Q=R.offsetLeft;P=R.offsetTop;R=R.offsetParent;while(R){Q+=R.offsetLeft;P+=R.offsetTop;R=R.offsetParent}}return[Q,P]}function m(V){for(var S=0,P=k.aiDisplay.length;S<P;S++){var U=k.aoData[k.aiDisplay[S]].nTr;var Q=U.getElementsByTagName("td");for(var R=0,T=Q.length;R<T;R++){if(Q[R]==V){return[R,S]}}}return null}function C(T,Q,P,S){O=S;if(typeof P=="undefined"){P={}}if(typeof P.focus=="undefined"){P.focus=[0,0]}P.table=T;f(P.table).addClass("KeyTable");if(typeof P.focusClass!="undefined"){o=P.focusClass}if(typeof Q!="undefined"){k=Q}if(typeof P.initScroll=="undefined"){P.initScroll=true}if(typeof P.form=="undefined"){P.form=false}u=P.form;l=P.table.getElementsByTagName("tbody")[0];if(u){var R=a.createElement("div");z=a.createElement("input");R.style.height="1px";R.style.width="0px";R.style.overflow="hidden";if(typeof P.tabIndex!="undefined"){z.tabIndex=P.tabIndex}R.appendChild(z);P.table.parentNode.insertBefore(R,P.table.nextSibling);f(z).focus(function(){if(!K){D=true;K=false;if(typeof P.focus.nodeName!="undefined"){h(P.focus,P.initScroll)}else{h(M(P.focus[0],P.focus[1]),P.initScroll)}setTimeout(function(){z.blur()},0)}});D=false}else{if(typeof P.focus.nodeName!="undefined"){h(P.focus,P.initScroll)}else{h(M(P.focus[0],P.focus[1]),P.initScroll)}L()}f(a).bind("keydown",n);if(k){f(k.nTable).on("click","td",s)}else{f(l).on("click","td",s)}f(a).click(function(V){var W=V.target;var U=false;while(W){if(W==P.table){U=true;break}W=W.parentNode}if(!U){B()}})}var I,p;if(x===d){I=f("table.KeyTable")[0];p=null}else{if(f.isPlainObject(x)){I=x.table;p=x.datatable}else{p=new f.fn.dataTable.Api(x).settings()[0];I=p.nTable}}C(I,p,x,this)};KeyTable.version="1.2.0";f.fn.dataTable.KeyTable=KeyTable;f.fn.DataTable.KeyTable=KeyTable;return KeyTable};b(jQuery,jQuery.fn.dataTable)})(window,document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-keyTable.min.js
jquery-dataTables-keyTable.min.js
;(function (factory) { var registeredInModuleLoader = false; if (typeof define === 'function' && define.amd) { define(factory); registeredInModuleLoader = true; } if (typeof exports === 'object') { module.exports = factory(); registeredInModuleLoader = true; } if (!registeredInModuleLoader) { var OldCookies = window.Cookies; var api = window.Cookies = factory(); api.noConflict = function () { window.Cookies = OldCookies; return api; }; } }(function () { function extend () { var i = 0; var result = {}; for (; i < arguments.length; i++) { var attributes = arguments[ i ]; for (var key in attributes) { result[key] = attributes[key]; } } return result; } function init (converter) { function api (key, value, attributes) { var result; if (typeof document === 'undefined') { return; } // Write if (arguments.length > 1) { attributes = extend({ path: '/' }, api.defaults, attributes); if (typeof attributes.expires === 'number') { var expires = new Date(); expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5); attributes.expires = expires; } // We're using "expires" because "max-age" is not supported by IE attributes.expires = attributes.expires ? attributes.expires.toUTCString() : ''; try { result = JSON.stringify(value); if (/^[\{\[]/.test(result)) { value = result; } } catch (e) {} if (!converter.write) { value = encodeURIComponent(String(value)) .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent); } else { value = converter.write(value, key); } key = encodeURIComponent(String(key)); key = key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent); key = key.replace(/[\(\)]/g, escape); var stringifiedAttributes = ''; for (var attributeName in attributes) { if (!attributes[attributeName]) { continue; } stringifiedAttributes += '; ' + attributeName; if (attributes[attributeName] === true) { continue; } stringifiedAttributes += '=' + attributes[attributeName]; } return (document.cookie = key + '=' + value + stringifiedAttributes); } // Read if (!key) { result = {}; } // To prevent the for loop in the first place assign an empty array // in case there are no cookies at all. Also prevents odd result when // calling "get()" var cookies = document.cookie ? document.cookie.split('; ') : []; var rdecode = /(%[0-9A-Z]{2})+/g; var i = 0; for (; i < cookies.length; i++) { var parts = cookies[i].split('='); var cookie = parts.slice(1).join('='); if (!this.json && cookie.charAt(0) === '"') { cookie = cookie.slice(1, -1); } try { var name = parts[0].replace(rdecode, decodeURIComponent); cookie = converter.read ? converter.read(cookie, name) : converter(cookie, name) || cookie.replace(rdecode, decodeURIComponent); if (this.json) { try { cookie = JSON.parse(cookie); } catch (e) {} } if (key === name) { result = cookie; break; } if (!key) { result[name] = cookie; } } catch (e) {} } return result; } api.set = api; api.get = function (key) { return api.call(api, key); }; api.getJSON = function () { return api.apply({ json: true }, [].slice.call(arguments)); }; api.defaults = {}; api.remove = function (key, attributes) { api(key, '', extend(attributes, { expires: -1 })); }; api.withConverter = init; return api; } return init(function () {}); }));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/js-cookie.js
js-cookie.js
if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') } +function ($) { 'use strict'; var version = $.fn.jquery.split(' ')[0].split('.') if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1)) { throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher') } }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.3.2 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition : 'webkitTransitionEnd', MozTransition : 'transitionend', OTransition : 'oTransitionEnd otransitionend', transition : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false var $el = this $(this).one('bsTransitionEnd', function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() if (!$.support.transition) return $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function (e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.3.2 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.3.2' Alert.TRANSITION_DURATION = 150 Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.closest('.alert') } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.3.2 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.3.2' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) // push to event loop to allow forms to submit setTimeout($.proxy(function () { $el[val](data[state] == null ? this.options[state] : data[state]) if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')) } if (changed) this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document) .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') Plugin.call($btn, 'toggle') e.preventDefault() }) .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) { $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.3.2 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.3.2' Carousel.TRANSITION_DURATION = 600 Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true } Carousel.prototype.keydown = function (e) { if (/input|textarea/i.test(e.target.tagName)) return switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.getItemForDirection = function (direction, active) { var activeIndex = this.getItemIndex(active) var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1)) if (willWrap && !this.options.wrap) return active var delta = direction == 'prev' ? -1 : 1 var itemIndex = (activeIndex + delta) % this.$items.length return this.$items.eq(itemIndex) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || this.getItemForDirection(type, $active) var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var that = this if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= var clickHandler = function (e) { var href var $this = $(this) var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() } $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.3.2 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.$trigger = $(this.options.trigger).filter('[href="#' + element.id + '"], [data-target="#' + element.id + '"]') this.transitioning = null if (this.options.parent) { this.$parent = this.getParent() } else { this.addAriaAndCollapsedClass(this.$element, this.$trigger) } if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.3.2' Collapse.TRANSITION_DURATION = 350 Collapse.DEFAULTS = { toggle: true, trigger: '[data-toggle="collapse"]' } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var activesData var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing') if (actives && actives.length) { activesData = actives.data('bs.collapse') if (activesData && activesData.transitioning) return } var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return if (actives && actives.length) { Plugin.call(actives, 'hide') activesData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) .attr('aria-expanded', true) this.$trigger .removeClass('collapsed') .attr('aria-expanded', true) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse in') .attr('aria-expanded', false) this.$trigger .addClass('collapsed') .attr('aria-expanded', false) this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .removeClass('collapsing') .addClass('collapse') .trigger('hidden.bs.collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } Collapse.prototype.getParent = function () { return $(this.options.parent) .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') .each($.proxy(function (i, element) { var $element = $(element) this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) }, this)) .end() } Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) { var isOpen = $element.hasClass('in') $element.attr('aria-expanded', isOpen) $trigger .toggleClass('collapsed', !isOpen) .attr('aria-expanded', isOpen) } function getTargetFromTrigger($trigger) { var href var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 return $(target) } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && option == 'show') options.toggle = false if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { var $this = $(this) if (!$this.attr('data-target')) e.preventDefault() var $target = getTargetFromTrigger($this) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $.extend({}, $this.data(), { trigger: this }) Plugin.call($target, option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.3.2 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle="dropdown"]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.VERSION = '3.3.2' Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } var relatedTarget = { relatedTarget: this } $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this .trigger('focus') .attr('aria-expanded', 'true') $parent .toggleClass('open') .trigger('shown.bs.dropdown', relatedTarget) } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if ((!isActive && e.which != 27) || (isActive && e.which == 27)) { if (e.which == 27) $parent.find(toggle).trigger('focus') return $this.trigger('click') } var desc = ' li:not(.divider):visible a' var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc) if (!$items.length) return var index = $items.index(e.target) if (e.which == 38 && index > 0) index-- // up if (e.which == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).trigger('focus') } function clearMenus(e) { if (e && e.which === 3) return $(backdrop).remove() $(toggle).each(function () { var $this = $(this) var $parent = getParent($this) var relatedTarget = { relatedTarget: this } if (!$parent.hasClass('open')) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this.attr('aria-expanded', 'false') $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget) }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown $.fn.dropdown = Plugin $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '[role="menu"]', Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '[role="listbox"]', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.3.2 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$body = $(document.body) this.$element = $(element) this.$backdrop = this.isShown = null this.scrollbarWidth = 0 if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.VERSION = '3.3.2' Modal.TRANSITION_DURATION = 300 Modal.BACKDROP_TRANSITION_DURATION = 150 Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.checkScrollbar() this.setScrollbar() this.$body.addClass('modal-open') this.escape() this.resize() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(that.$body) // don't move modals dom position } that.$element .show() .scrollTop(0) if (that.options.backdrop) that.adjustBackdrop() that.adjustDialog() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one('bsTransitionEnd', function () { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() this.resize() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keydown.dismiss.bs.modal') } } Modal.prototype.resize = function () { if (this.isShown) { $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this)) } else { $(window).off('resize.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.$body.removeClass('modal-open') that.resetAdjustments() that.resetScrollbar() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .prependTo(this.$element) .on('click.dismiss.bs.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') var callbackRemove = function () { that.removeBackdrop() callback && callback() } $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callbackRemove() } else if (callback) { callback() } } // these following methods are used to handle overflowing modals Modal.prototype.handleUpdate = function () { if (this.options.backdrop) this.adjustBackdrop() this.adjustDialog() } Modal.prototype.adjustBackdrop = function () { this.$backdrop .css('height', 0) .css('height', this.$element[0].scrollHeight) } Modal.prototype.adjustDialog = function () { var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight this.$element.css({ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' }) } Modal.prototype.resetAdjustments = function () { this.$element.css({ paddingLeft: '', paddingRight: '' }) } Modal.prototype.checkScrollbar = function () { this.bodyIsOverflowing = document.body.scrollHeight > document.documentElement.clientHeight this.scrollbarWidth = this.measureScrollbar() } Modal.prototype.setScrollbar = function () { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) } Modal.prototype.resetScrollbar = function () { this.$body.css('padding-right', '') } Modal.prototype.measureScrollbar = function () { // thx walsh var scrollDiv = document.createElement('div') scrollDiv.className = 'modal-scrollbar-measure' this.$body.append(scrollDiv) var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth this.$body[0].removeChild(scrollDiv) return scrollbarWidth } // MODAL PLUGIN DEFINITION // ======================= function Plugin(option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal $.fn.modal = Plugin $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target.one('show.bs.modal', function (showEvent) { if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown $target.one('hidden.bs.modal', function () { $this.is(':visible') && $this.trigger('focus') }) }) Plugin.call($target, option, this) }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.3.2 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.VERSION = '3.3.2' Tooltip.TRANSITION_DURATION = 150 Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 } } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (self && self.$tip && self.$tip.is(':visible')) { self.hoverState = 'in' return } if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]) if (e.isDefaultPrevented() || !inDom) return var that = this var $tip = this.tip() var tipId = this.getUID(this.type) this.setContent() $tip.attr('id', tipId) this.$element.attr('aria-describedby', tipId) if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) .data('bs.' + this.type, this) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var orgPlacement = placement var $container = this.options.container ? $(this.options.container) : this.$element.parent() var containerDim = this.getPosition($container) placement = placement == 'bottom' && pos.bottom + actualHeight > containerDim.bottom ? 'top' : placement == 'top' && pos.top - actualHeight < containerDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > containerDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < containerDim.left ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) var complete = function () { var prevHoverState = that.hoverState that.$element.trigger('shown.bs.' + that.type) that.hoverState = null if (prevHoverState == 'out') that.leave(that) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight) if (delta.left) offset.left += delta.left else offset.top += delta.top var isVertical = /top|bottom/.test(placement) var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight' $tip.offset(offset) this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) } Tooltip.prototype.replaceArrow = function (delta, dimension, isHorizontal) { this.arrow() .css(isHorizontal ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') .css(isHorizontal ? 'top' : 'left', '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function (callback) { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() that.$element .removeAttr('aria-describedby') .trigger('hidden.bs.' + that.type) callback && callback() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function ($element) { $element = $element || this.$element var el = $element[0] var isBody = el.tagName == 'BODY' var elRect = el.getBoundingClientRect() if (elRect.width == null) { // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top }) } var elOffset = isBody ? { top: 0, left: 0 } : $element.offset() var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() } var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null return $.extend({}, elRect, scroll, outerDims, elOffset) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) { var delta = { top: 0, left: 0 } if (!this.$viewport) return delta var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 var viewportDimensions = this.getPosition(this.$viewport) if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight if (topEdgeOffset < viewportDimensions.top) { // top overflow delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left - viewportPadding var rightEdgeOffset = pos.left + viewportPadding + actualWidth if (leftEdgeOffset < viewportDimensions.left) { // left overflow delta.left = viewportDimensions.left - leftEdgeOffset } else if (rightEdgeOffset > viewportDimensions.width) { // right overflow delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset } } return delta } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.getUID = function (prefix) { do prefix += ~~(Math.random() * 1000000) while (document.getElementById(prefix)) return prefix } Tooltip.prototype.tip = function () { return (this.$tip = this.$tip || $(this.options.template)) } Tooltip.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = this if (e) { self = $(e.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()) $(e.currentTarget).data('bs.' + this.type, self) } } self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { var that = this clearTimeout(this.timeout) this.hide(function () { that.$element.off('.' + that.type).removeData('bs.' + that.type) }) } // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip $.fn.tooltip = Plugin $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.3.2 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.VERSION = '3.3.2' Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.arrow')) } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } // POPOVER PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.popover $.fn.popover = Plugin $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.3.2 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var process = $.proxy(this.process, this) this.$body = $('body') this.$scrollElement = $(element).is('body') ? $(window) : $(element) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || '') + ' .nav li > a' this.offsets = [] this.targets = [] this.activeTarget = null this.scrollHeight = 0 this.$scrollElement.on('scroll.bs.scrollspy', process) this.refresh() this.process() } ScrollSpy.VERSION = '3.3.2' ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.getScrollHeight = function () { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) } ScrollSpy.prototype.refresh = function () { var offsetMethod = 'offset' var offsetBase = 0 if (!$.isWindow(this.$scrollElement[0])) { offsetMethod = 'position' offsetBase = this.$scrollElement.scrollTop() } this.offsets = [] this.targets = [] this.scrollHeight = this.getScrollHeight() var self = this this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [[$href[offsetMethod]().top + offsetBase, href]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.getScrollHeight() var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (this.scrollHeight != scrollHeight) { this.refresh() } if (scrollTop >= maxScroll) { return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } if (activeTarget && scrollTop < offsets[0]) { this.activeTarget = null return this.clear() } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate(targets[i]) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target this.clear() var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } ScrollSpy.prototype.clear = function () { $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') } // SCROLLSPY PLUGIN DEFINITION // =========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.scrollspy $.fn.scrollspy = Plugin $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load.bs.scrollspy.data-api', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) Plugin.call($spy, $spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.3.2 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { this.element = $(element) } Tab.VERSION = '3.3.2' Tab.TRANSITION_DURATION = 150 Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } if ($this.parent('li').hasClass('active')) return var $previous = $ul.find('.active:last a') var hideEvent = $.Event('hide.bs.tab', { relatedTarget: $this[0] }) var showEvent = $.Event('show.bs.tab', { relatedTarget: $previous[0] }) $previous.trigger(hideEvent) $this.trigger(showEvent) if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return var $target = $(selector) this.activate($this.closest('li'), $ul) this.activate($target, $target.parent(), function () { $previous.trigger({ type: 'hidden.bs.tab', relatedTarget: $this[0] }) $this.trigger({ type: 'shown.bs.tab', relatedTarget: $previous[0] }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && (($active.length && $active.hasClass('fade')) || !!container.find('> .fade').length) function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', false) element .addClass('active') .find('[data-toggle="tab"]') .attr('aria-expanded', true) if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element .closest('li.dropdown') .addClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', true) } callback && callback() } $active.length && transition ? $active .one('bsTransitionEnd', next) .emulateTransitionEnd(Tab.TRANSITION_DURATION) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tab $.fn.tab = Plugin $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ var clickHandler = function (e) { e.preventDefault() Plugin.call($(this), 'show') } $(document) .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler) .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.3.2 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$target = $(this.options.target) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = this.pinnedOffset = null this.checkPosition() } Affix.VERSION = '3.3.2' Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0, target: window } Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) { var scrollTop = this.$target.scrollTop() var position = this.$element.offset() var targetHeight = this.$target.height() if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false if (this.affixed == 'bottom') { if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom' return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom' } var initializing = this.affixed == null var colliderTop = initializing ? scrollTop : position.top var colliderHeight = initializing ? targetHeight : height if (offsetTop != null && scrollTop <= offsetTop) return 'top' if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom' return false } Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$target.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var height = this.$element.height() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom var scrollHeight = $('body').height() if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom) if (this.affixed != affix) { if (this.unpin != null) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger(affixType.replace('affix', 'affixed') + '.bs.affix') } if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - height - offsetBottom }) } } // AFFIX PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.affix $.fn.affix = Plugin $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom if (data.offsetTop != null) data.offset.top = data.offsetTop Plugin.call($spy, data) }) }) }(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/bootstrap-3.3.2.js
bootstrap-3.3.2.js
!function ($, window, document, undefined) { // Determine if this is a touch device var hasTouch = 'ontouchstart' in document.documentElement, startEvent = 'touchstart mousedown', moveEvent = 'touchmove mousemove', endEvent = 'touchend mouseup'; // If we're on a touch device, then wire up the events // see http://stackoverflow.com/a/8456194/1316086 hasTouch && $.each("touchstart touchmove touchend".split(" "), function(i, name) { $.event.fixHooks[name] = $.event.mouseHooks; }); $(document).ready(function () { function parseStyle(css) { var objMap = {}, parts = css.match(/([^;:]+)/g) || []; while (parts.length) objMap[parts.shift()] = parts.shift().trim(); return objMap; } $('table').each(function () { if ($(this).data('table') == 'dnd') { $(this).tableDnD({ onDragStyle: $(this).data('ondragstyle') && parseStyle($(this).data('ondragstyle')) || null, onDropStyle: $(this).data('ondropstyle') && parseStyle($(this).data('ondropstyle')) || null, onDragClass: $(this).data('ondragclass') == undefined && "tDnD_whileDrag" || $(this).data('ondragclass'), onDrop: $(this).data('ondrop') && new Function('table', 'row', $(this).data('ondrop')), // 'return eval("'+$(this).data('ondrop')+'");') || null, onDragStart: $(this).data('ondragstart') && new Function('table', 'row' ,$(this).data('ondragstart')), // 'return eval("'+$(this).data('ondragstart')+'");') || null, scrollAmount: $(this).data('scrollamount') || 5, sensitivity: $(this).data('sensitivity') || 10, hierarchyLevel: $(this).data('hierarchylevel') || 0, indentArtifact: $(this).data('indentartifact') || '<div class="indent">&nbsp;</div>', autoWidthAdjust: $(this).data('autowidthadjust') || true, autoCleanRelations: $(this).data('autocleanrelations') || true, jsonPretifySeparator: $(this).data('jsonpretifyseparator') || '\t', serializeRegexp: $(this).data('serializeregexp') && new RegExp($(this).data('serializeregexp')) || /[^\-]*$/, serializeParamName: $(this).data('serializeparamname') || false, dragHandle: $(this).data('draghandle') || null }); } }); }); jQuery.tableDnD = { /** Keep hold of the current table being dragged */ currentTable: null, /** Keep hold of the current drag object if any */ dragObject: null, /** The current mouse offset */ mouseOffset: null, /** Remember the old value of X and Y so that we don't do too much processing */ oldX: 0, oldY: 0, /** Actually build the structure */ build: function(options) { // Set up the defaults if any this.each(function() { // This is bound to each matching table, set up the defaults and override with user options this.tableDnDConfig = $.extend({ onDragStyle: null, onDropStyle: null, // Add in the default class for whileDragging onDragClass: "tDnD_whileDrag", onDrop: null, onDragStart: null, scrollAmount: 5, /** Sensitivity setting will throttle the trigger rate for movement detection */ sensitivity: 10, /** Hierarchy level to support parent child. 0 switches this functionality off */ hierarchyLevel: 0, /** The html artifact to prepend the first cell with as indentation */ indentArtifact: '<div class="indent">&nbsp;</div>', /** Automatically adjust width of first cell */ autoWidthAdjust: true, /** Automatic clean-up to ensure relationship integrity */ autoCleanRelations: true, /** Specify a number (4) as number of spaces or any indent string for JSON.stringify */ jsonPretifySeparator: '\t', /** The regular expression to use to trim row IDs */ serializeRegexp: /[^\-]*$/, /** If you want to specify another parameter name instead of the table ID */ serializeParamName: false, /** If you give the name of a class here, then only Cells with this class will be draggable */ dragHandle: null }, options || {}); // Now make the rows draggable $.tableDnD.makeDraggable(this); // Prepare hierarchy support this.tableDnDConfig.hierarchyLevel && $.tableDnD.makeIndented(this); }); // Don't break the chain return this; }, makeIndented: function (table) { var config = table.tableDnDConfig, rows = table.rows, firstCell = $(rows).first().find('td:first')[0], indentLevel = 0, cellWidth = 0, longestCell, tableStyle; if ($(table).hasClass('indtd')) return null; tableStyle = $(table).addClass('indtd').attr('style'); $(table).css({whiteSpace: "nowrap"}); for (var w = 0; w < rows.length; w++) { if (cellWidth < $(rows[w]).find('td:first').text().length) { cellWidth = $(rows[w]).find('td:first').text().length; longestCell = w; } } $(firstCell).css({width: 'auto'}); for (w = 0; w < config.hierarchyLevel; w++) $(rows[longestCell]).find('td:first').prepend(config.indentArtifact); firstCell && $(firstCell).css({width: firstCell.offsetWidth}); tableStyle && $(table).css(tableStyle); for (w = 0; w < config.hierarchyLevel; w++) $(rows[longestCell]).find('td:first').children(':first').remove(); config.hierarchyLevel && $(rows).each(function () { indentLevel = $(this).data('level') || 0; indentLevel <= config.hierarchyLevel && $(this).data('level', indentLevel) || $(this).data('level', 0); for (var i = 0; i < $(this).data('level'); i++) $(this).find('td:first').prepend(config.indentArtifact); }); return this; }, /** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */ makeDraggable: function(table) { var config = table.tableDnDConfig; config.dragHandle // We only need to add the event to the specified cells && $(config.dragHandle, table).each(function() { // The cell is bound to "this" $(this).bind(startEvent, function(e) { $.tableDnD.initialiseDrag($(this).parents('tr')[0], table, this, e, config); return false; }); }) // For backwards compatibility, we add the event to the whole row // get all the rows as a wrapped set || $(table.rows).each(function() { // Iterate through each row, the row is bound to "this" if (! $(this).hasClass("nodrag")) { $(this).bind(startEvent, function(e) { if (e.target.tagName == "TD") { $.tableDnD.initialiseDrag(this, table, this, e, config); return false; } }).css("cursor", "move"); // Store the tableDnD object } }); }, currentOrder: function() { var rows = this.currentTable.rows; return $.map(rows, function (val) { return ($(val).data('level') + val.id).replace(/\s/g, ''); }).join(''); }, initialiseDrag: function(dragObject, table, target, e, config) { this.dragObject = dragObject; this.currentTable = table; this.mouseOffset = this.getMouseOffset(target, e); this.originalOrder = this.currentOrder(); // Now we need to capture the mouse up and mouse move event // We can use bind so that we don't interfere with other event handlers $(document) .bind(moveEvent, this.mousemove) .bind(endEvent, this.mouseup); // Call the onDragStart method if there is one config.onDragStart && config.onDragStart(table, target); }, updateTables: function() { this.each(function() { // this is now bound to each matching table if (this.tableDnDConfig) $.tableDnD.makeDraggable(this); }); }, /** Get the mouse coordinates from the event (allowing for browser differences) */ mouseCoords: function(e) { e = e || window.event; if (e.changedTouches) return { x: e.changedTouches[0].clientX, y: e.changedTouches[0].clientY }; if(e.pageX || e.pageY) return { x: e.pageX, y: e.pageY }; return { x: e.clientX + document.body.scrollLeft - document.body.clientLeft, y: e.clientY + document.body.scrollTop - document.body.clientTop }; }, /** Given a target element and a mouse eent, get the mouse offset from that element. To do this we need the element's position and the mouse position */ getMouseOffset: function(target, e) { var mousePos, docPos; e = e || window.event; docPos = this.getPosition(target); mousePos = this.mouseCoords(e); return { x: mousePos.x - docPos.x, y: mousePos.y - docPos.y }; }, /** Get the position of an element by going up the DOM tree and adding up all the offsets */ getPosition: function(element) { var left = 0, top = 0; // Safari fix -- thanks to Luis Chato for this! // Safari 2 doesn't correctly grab the offsetTop of a table row // this is detailed here: // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/ // the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild. // note that firefox will return a text node as a first child, so designing a more thorough // solution may need to take that into account, for now this seems to work in firefox, safari, ie if (element.offsetHeight == 0) element = element.firstChild; // a table cell while (element.offsetParent) { left += element.offsetLeft; top += element.offsetTop; element = element.offsetParent; } left += element.offsetLeft; top += element.offsetTop; return { x: left, y: top }; }, autoScroll: function (mousePos) { var config = this.currentTable.tableDnDConfig, yOffset = window.pageYOffset, windowHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight; // Windows version // yOffset=document.body.scrollTop; if (document.all) if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') yOffset = document.documentElement.scrollTop; else if (typeof document.body != 'undefined') yOffset = document.body.scrollTop; mousePos.y - yOffset < config.scrollAmount && window.scrollBy(0, - config.scrollAmount) || windowHeight - (mousePos.y - yOffset) < config.scrollAmount && window.scrollBy(0, config.scrollAmount); }, moveVerticle: function (moving, currentRow) { if (0 != moving.vertical // If we're over a row then move the dragged row to there so that the user sees the // effect dynamically && currentRow && this.dragObject != currentRow && this.dragObject.parentNode == currentRow.parentNode) 0 > moving.vertical && this.dragObject.parentNode.insertBefore(this.dragObject, currentRow.nextSibling) || 0 < moving.vertical && this.dragObject.parentNode.insertBefore(this.dragObject, currentRow); }, moveHorizontal: function (moving, currentRow) { var config = this.currentTable.tableDnDConfig, currentLevel; if (!config.hierarchyLevel || 0 == moving.horizontal // We only care if moving left or right on the current row || !currentRow || this.dragObject != currentRow) return null; currentLevel = $(currentRow).data('level'); 0 < moving.horizontal && currentLevel > 0 && $(currentRow).find('td:first').children(':first').remove() && $(currentRow).data('level', --currentLevel); 0 > moving.horizontal && currentLevel < config.hierarchyLevel && $(currentRow).prev().data('level') >= currentLevel && $(currentRow).children(':first').prepend(config.indentArtifact) && $(currentRow).data('level', ++currentLevel); }, mousemove: function(e) { var dragObj = $($.tableDnD.dragObject), config = $.tableDnD.currentTable.tableDnDConfig, currentRow, mousePos, moving, x, y; e && e.preventDefault(); if (!$.tableDnD.dragObject) return false; // prevent touch device screen scrolling e.type == 'touchmove' && event.preventDefault(); // TODO verify this is event and not really e // update the style to show we're dragging config.onDragClass && dragObj.addClass(config.onDragClass) || dragObj.css(config.onDragStyle); mousePos = $.tableDnD.mouseCoords(e); x = mousePos.x - $.tableDnD.mouseOffset.x; y = mousePos.y - $.tableDnD.mouseOffset.y; // auto scroll the window $.tableDnD.autoScroll(mousePos); currentRow = $.tableDnD.findDropTargetRow(dragObj, y); moving = $.tableDnD.findDragDirection(x, y); $.tableDnD.moveVerticle(moving, currentRow); $.tableDnD.moveHorizontal(moving, currentRow); return false; }, findDragDirection: function (x,y) { var sensitivity = this.currentTable.tableDnDConfig.sensitivity, oldX = this.oldX, oldY = this.oldY, xMin = oldX - sensitivity, xMax = oldX + sensitivity, yMin = oldY - sensitivity, yMax = oldY + sensitivity, moving = { horizontal: x >= xMin && x <= xMax ? 0 : x > oldX ? -1 : 1, vertical : y >= yMin && y <= yMax ? 0 : y > oldY ? -1 : 1 }; // update the old value if (moving.horizontal != 0) this.oldX = x; if (moving.vertical != 0) this.oldY = y; return moving; }, /** We're only worried about the y position really, because we can only move rows up and down */ findDropTargetRow: function(draggedRow, y) { var rowHeight = 0, rows = this.currentTable.rows, config = this.currentTable.tableDnDConfig, rowY = 0, row = null; for (var i = 0; i < rows.length; i++) { row = rows[i]; rowY = this.getPosition(row).y; rowHeight = parseInt(row.offsetHeight) / 2; if (row.offsetHeight == 0) { rowY = this.getPosition(row.firstChild).y; rowHeight = parseInt(row.firstChild.offsetHeight) / 2; } // Because we always have to insert before, we need to offset the height a bit if (y > (rowY - rowHeight) && y < (rowY + rowHeight)) // that's the row we're over // If it's the same as the current row, ignore it if (draggedRow.is(row) || (config.onAllowDrop && !config.onAllowDrop(draggedRow, row)) // If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic) || $(row).hasClass("nodrop")) return null; else return row; } return null; }, processMouseup: function() { if (!this.currentTable || !this.dragObject) return null; var config = this.currentTable.tableDnDConfig, droppedRow = this.dragObject, parentLevel = 0, myLevel = 0; // Unbind the event handlers $(document) .unbind(moveEvent, this.mousemove) .unbind(endEvent, this.mouseup); config.hierarchyLevel && config.autoCleanRelations && $(this.currentTable.rows).first().find('td:first').children().each(function () { myLevel = $(this).parents('tr:first').data('level'); myLevel && $(this).parents('tr:first').data('level', --myLevel) && $(this).remove(); }) && config.hierarchyLevel > 1 && $(this.currentTable.rows).each(function () { myLevel = $(this).data('level'); if (myLevel > 1) { parentLevel = $(this).prev().data('level'); while (myLevel > parentLevel + 1) { $(this).find('td:first').children(':first').remove(); $(this).data('level', --myLevel); } } }); // If we have a dragObject, then we need to release it, // The row will already have been moved to the right place so we just reset stuff config.onDragClass && $(droppedRow).removeClass(config.onDragClass) || $(droppedRow).css(config.onDropStyle); this.dragObject = null; // Call the onDrop method if there is one config.onDrop && this.originalOrder != this.currentOrder() && $(droppedRow).hide().fadeIn('fast') && config.onDrop(this.currentTable, droppedRow); this.currentTable = null; // let go of the table too }, mouseup: function(e) { e && e.preventDefault(); $.tableDnD.processMouseup(); return false; }, jsonize: function(pretify) { var table = this.currentTable; if (pretify) return JSON.stringify( this.tableData(table), null, table.tableDnDConfig.jsonPretifySeparator ); return JSON.stringify(this.tableData(table)); }, serialize: function() { return $.param(this.tableData(this.currentTable)); }, serializeTable: function(table) { var result = ""; var paramName = table.tableDnDConfig.serializeParamName || table.id; var rows = table.rows; for (var i=0; i<rows.length; i++) { if (result.length > 0) result += "&"; var rowId = rows[i].id; if (rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) { rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0]; result += paramName + '[]=' + rowId; } } return result; }, serializeTables: function() { var result = []; $('table').each(function() { this.id && result.push($.param(this.tableData(this))); }); return result.join('&'); }, tableData: function (table) { var config = table.tableDnDConfig, previousIDs = [], currentLevel = 0, indentLevel = 0, rowID = null, data = {}, getSerializeRegexp, paramName, currentID, rows; if (!table) table = this.currentTable; if (!table || !table.id || !table.rows || !table.rows.length) return {error: { code: 500, message: "Not a valid table, no serializable unique id provided."}}; rows = config.autoCleanRelations && table.rows || $.makeArray(table.rows); paramName = config.serializeParamName || table.id; currentID = paramName; getSerializeRegexp = function (rowId) { if (rowId && config && config.serializeRegexp) return rowId.match(config.serializeRegexp)[0]; return rowId; }; data[currentID] = []; !config.autoCleanRelations && $(rows[0]).data('level') && rows.unshift({id: 'undefined'}); for (var i=0; i < rows.length; i++) { if (config.hierarchyLevel) { indentLevel = $(rows[i]).data('level') || 0; if (indentLevel == 0) { currentID = paramName; previousIDs = []; } else if (indentLevel > currentLevel) { previousIDs.push([currentID, currentLevel]); currentID = getSerializeRegexp(rows[i-1].id); } else if (indentLevel < currentLevel) { for (var h = 0; h < previousIDs.length; h++) { if (previousIDs[h][1] == indentLevel) currentID = previousIDs[h][0]; if (previousIDs[h][1] >= currentLevel) previousIDs[h][1] = 0; } } currentLevel = indentLevel; if (!$.isArray(data[currentID])) data[currentID] = []; rowID = getSerializeRegexp(rows[i].id); rowID && data[currentID].push(rowID); } else { rowID = getSerializeRegexp(rows[i].id); rowID && data[currentID].push(rowID); } } return data; } }; jQuery.fn.extend( { tableDnD : $.tableDnD.build, tableDnDUpdate : $.tableDnD.updateTables, tableDnDSerialize : $.proxy($.tableDnD.serialize, $.tableDnD), tableDnDSerializeAll : $.tableDnD.serializeTables, tableDnDData : $.proxy($.tableDnD.tableData, $.tableDnD) } ); }(jQuery, window, window.document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-tablednd.js
jquery-tablednd.js
!function ($) { "use strict"; // jshint ;_; /* MODAL MANAGER CLASS DEFINITION * ====================== */ var ModalManager = function (element, options) { this.init(element, options); }; ModalManager.prototype = { constructor: ModalManager, init: function (element, options) { this.$element = $(element); this.options = $.extend({}, $.fn.modalmanager.defaults, this.$element.data(), typeof options === 'object' && options); this.stack = []; this.backdropCount = 0; if (this.options.resize) { var resizeTimeout, that = this; $(window).on('resize.modal', function () { if (resizeTimeout) { clearTimeout(resizeTimeout); } resizeTimeout = setTimeout(function () { for (var i = 0; i < that.stack.length; i++) { if (that.stack[i].isShown) { that.stack[i].layout(); } } }, 10); }); } }, createModal: function (element, options) { $(element).modal($.extend({ manager: this }, options)); }, appendModal: function (modal) { this.stack.push(modal); var that = this; modal.$element.on('show.modalmanager', targetIsSelf(function (e) { var showModal = function () { modal.isShown = true; var transition = $.support.transition && modal.$element.hasClass('fade'); that.$element .toggleClass('modal-open', that.hasOpenModal()) .toggleClass('page-overflow', $(window).height() < that.$element.height()); modal.$parent = modal.$element.parent(); modal.$container = that.createContainer(modal); modal.$element.appendTo(modal.$container); that.backdrop(modal, function () { modal.$element.show(); if (transition) { //modal.$element[0].style.display = 'run-in'; modal.$element[0].offsetWidth; //modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' }); } modal.layout(); modal.$element .addClass('in') .attr('aria-hidden', false); var complete = function () { that.setFocus(); modal.$element.trigger('shown'); }; if (transition) { modal.$element.one($.support.transition.end, complete); } else { complete(); } }); }; if (modal.options.replace) { that.replace(showModal); } else { showModal(); } })); modal.$element.on('hidden.modalmanager', targetIsSelf(function (e) { that.backdrop(modal); // handle the case when a modal may have been removed from the dom before this callback executes if (!modal.$element.parent().length) { that.destroyModal(modal); } else if (modal.$backdrop) { var transition = $.support.transition && modal.$element.hasClass('fade'); // trigger a relayout due to firefox's buggy transition end event if (transition) { modal.$element[0].offsetWidth; } if ($.support.transition && modal.$element.hasClass('fade')) { modal.$backdrop.one($.support.transition.end, function () { modal.destroy(); }); } else { modal.destroy(); } } else { modal.destroy(); } })); modal.$element.on('destroyed.modalmanager', targetIsSelf(function (e) { that.destroyModal(modal); })); }, getOpenModals: function () { var openModals = []; for (var i = 0; i < this.stack.length; i++) { if (this.stack[i].isShown) { openModals.push(this.stack[i]); } } return openModals; }, hasOpenModal: function () { return this.getOpenModals().length > 0; }, setFocus: function () { var topModal; for (var i = 0; i < this.stack.length; i++) { if (this.stack[i].isShown) { topModal = this.stack[i]; } } if (!topModal) { return; } topModal.focus(); }, destroyModal: function (modal) { modal.$element.off('.modalmanager'); if (modal.$backdrop) { this.removeBackdrop(modal); } this.stack.splice(this.getIndexOfModal(modal), 1); var hasOpenModal = this.hasOpenModal(); this.$element.toggleClass('modal-open', hasOpenModal); if (!hasOpenModal) { this.$element.removeClass('page-overflow'); } this.removeContainer(modal); this.setFocus(); }, getModalAt: function (index) { return this.stack[index]; }, getIndexOfModal: function (modal) { for (var i = 0; i < this.stack.length; i++) { if (modal === this.stack[i]) { return i; } } }, replace: function (callback) { var topModal; for (var i = 0; i < this.stack.length; i++) { if (this.stack[i].isShown) { topModal = this.stack[i]; } } if (topModal) { this.$backdropHandle = topModal.$backdrop; topModal.$backdrop = null; if (callback) { topModal.$element.one('hidden', targetIsSelf($.proxy(callback, this))); } topModal.hide(); } else if (callback) { callback(); } }, removeBackdrop: function (modal) { modal.$backdrop.remove(); modal.$backdrop = null; }, createBackdrop: function (animate, tmpl) { var $backdrop; if (!this.$backdropHandle) { $backdrop = $(tmpl) .addClass(animate) .appendTo(this.$element); } else { $backdrop = this.$backdropHandle; $backdrop.off('.modalmanager'); this.$backdropHandle = null; if (this.isLoading) { this.removeSpinner(); } } return $backdrop; }, removeContainer: function (modal) { modal.$container.remove(); modal.$container = null; }, createContainer: function (modal) { var $container; $container = $('<div class="modal-scrollable">') .css('z-index', getzIndex('modal', this.getOpenModals().length)) .appendTo(this.$element); if (modal && modal.options.backdrop === 'hide') { $container.on('click.modal', targetIsSelf(function (e) { modal.hide(); })); } else if (modal && modal.options.backdrop === 'attention') { $container.on('click.modal', targetIsSelf(function (e) { modal.attention(); })); } return $container; }, backdrop: function (modal, callback) { var animate = modal.$element.hasClass('fade') ? 'fade' : '', showBackdrop = modal.options.backdrop && this.backdropCount < this.options.backdropLimit; if (modal.isShown && showBackdrop) { var doAnimate = $.support.transition && animate && !this.$backdropHandle; modal.$backdrop = this.createBackdrop(animate, modal.options.backdropTemplate); modal.$backdrop.css('z-index', getzIndex('backdrop', this.getOpenModals().length)); if (doAnimate) { modal.$backdrop[0].offsetWidth; } // force reflow modal.$backdrop.addClass('in'); this.backdropCount += 1; if (doAnimate) { modal.$backdrop.one($.support.transition.end, callback); } else { callback(); } } else if (!modal.isShown && modal.$backdrop) { modal.$backdrop.removeClass('in'); this.backdropCount -= 1; var that = this; if ($.support.transition && modal.$element.hasClass('fade')) { modal.$backdrop.one($.support.transition.end, function () { that.removeBackdrop(modal); }); } else { that.removeBackdrop(modal); } } else if (callback) { callback(); } }, removeSpinner: function () { if (this.$spinner) { this.$spinner.remove(); } this.$spinner = null; this.isLoading = false; }, removeLoading: function () { if (this.$backdropHandle) { this.$backdropHandle.remove(); } this.$backdropHandle = null; this.removeSpinner(); }, loading: function (callback) { callback = callback || function () {}; this.$element .toggleClass('modal-open', !this.isLoading || this.hasOpenModal()) .toggleClass('page-overflow', $(window).height() < this.$element.height()); if (!this.isLoading) { this.$backdropHandle = this.createBackdrop('fade', this.options.backdropTemplate); this.$backdropHandle[0].offsetWidth; // force reflow var openModals = this.getOpenModals(); this.$backdropHandle .css('z-index', getzIndex('backdrop', openModals.length + 1)) .addClass('in'); var $spinner = $(this.options.spinner) .css('z-index', getzIndex('modal', openModals.length + 1)) .appendTo(this.$element) .addClass('in'); this.$spinner = $(this.createContainer()) .append($spinner) .on('click.modalmanager', $.proxy(this.loading, this)); this.isLoading = true; if ($.support.transition) { this.$backdropHandle.one($.support.transition.end, callback); } else { callback(); } } else if (this.isLoading && this.$backdropHandle) { this.$backdropHandle.removeClass('in'); var that = this; if ($.support.transition) { this.$backdropHandle.one($.support.transition.end, function () { that.removeLoading(); }); } else { that.removeLoading(); } } else if (callback) { callback(this.isLoading); } } }; /* PRIVATE METHODS * ======================= */ // computes and caches the zindexes var getzIndex = (function () { var zIndexFactor, baseIndex = {}; return function (type, pos) { if (typeof zIndexFactor === 'undefined') { var $baseModal = $('<div class="modal hide" />').appendTo('body'), $baseBackdrop = $('<div class="modal-backdrop hide" />').appendTo('body'); baseIndex.modal = +$baseModal.css('z-index'); baseIndex.backdrop = +$baseBackdrop.css('z-index'); zIndexFactor = baseIndex.modal - baseIndex.backdrop; $baseModal.remove(); $baseBackdrop.remove(); $baseBackdrop = $baseModal = null; } return baseIndex[type] + (zIndexFactor * pos); }; }()); // make sure the event target is the modal itself in order to prevent // other components such as tabsfrom triggering the modal manager. // if Boostsrap namespaced events, this would not be needed. function targetIsSelf(callback) { return function (e) { if (e && this === e.target){ return callback.apply(this, arguments); } } } /* MODAL MANAGER PLUGIN DEFINITION * ======================= */ $.fn.modalmanager = function (option, args) { return this.each(function () { var $this = $(this), data = $this.data('modalmanager'); if (!data) { $this.data('modalmanager', (data = new ModalManager(this, option))); } if (typeof option === 'string') { data[option].apply(data, [].concat(args)); } }); }; $.fn.modalmanager.defaults = { backdropLimit: 999, resize: true, spinner: '<div class="loading-spinner fade" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>', backdropTemplate: '<div class="modal-backdrop" />' }; $.fn.modalmanager.Constructor = ModalManager; // ModalManager handles the modal-open class so we need // to remove conflicting bootstrap 3 event handlers $(function () { $(document).off('show.bs.modal').off('hidden.bs.modal'); }); }(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/bootstrap-modalmanager.js
bootstrap-modalmanager.js
(function(b){b.color={};b.color.make=function(d,e,g,f){var c={};c.r=d||0;c.g=e||0;c.b=g||0;c.a=f!=null?f:1;c.add=function(h,j){for(var k=0;k<h.length;++k){c[h.charAt(k)]+=j}return c.normalize()};c.scale=function(h,j){for(var k=0;k<h.length;++k){c[h.charAt(k)]*=j}return c.normalize()};c.toString=function(){if(c.a>=1){return"rgb("+[c.r,c.g,c.b].join(",")+")"}else{return"rgba("+[c.r,c.g,c.b,c.a].join(",")+")"}};c.normalize=function(){function h(k,j,l){return j<k?k:(j>l?l:j)}c.r=h(0,parseInt(c.r),255);c.g=h(0,parseInt(c.g),255);c.b=h(0,parseInt(c.b),255);c.a=h(0,c.a,1);return c};c.clone=function(){return b.color.make(c.r,c.b,c.g,c.a)};return c.normalize()};b.color.extract=function(d,e){var c;do{c=d.css(e).toLowerCase();if(c!=""&&c!="transparent"){break}d=d.parent()}while(!b.nodeName(d.get(0),"body"));if(c=="rgba(0, 0, 0, 0)"){c="transparent"}return b.color.parse(c)};b.color.parse=function(c){var d,f=b.color.make;if(d=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c)){return f(parseInt(d[1],10),parseInt(d[2],10),parseInt(d[3],10))}if(d=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(c)){return f(parseInt(d[1],10),parseInt(d[2],10),parseInt(d[3],10),parseFloat(d[4]))}if(d=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c)){return f(parseFloat(d[1])*2.55,parseFloat(d[2])*2.55,parseFloat(d[3])*2.55)}if(d=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(c)){return f(parseFloat(d[1])*2.55,parseFloat(d[2])*2.55,parseFloat(d[3])*2.55,parseFloat(d[4]))}if(d=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c)){return f(parseInt(d[1],16),parseInt(d[2],16),parseInt(d[3],16))}if(d=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c)){return f(parseInt(d[1]+d[1],16),parseInt(d[2]+d[2],16),parseInt(d[3]+d[3],16))}var e=b.trim(c).toLowerCase();if(e=="transparent"){return f(255,255,255,0)}else{d=a[e]||[0,0,0];return f(d[0],d[1],d[2])}};var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);(function(c){function b(aw,aj,J,af){var ai=(window.devicePixelRatio>1),Q=[],O={colors:["#931313","#638167","#65596B","#60747C","#B09B5B"],legend:{show:true,noColumns:0,labelFormatter:null,labelBoxBorderColor:"",container:null,position:"ne",margin:[-5,-32],backgroundColor:"",backgroundOpacity:1},xaxis:{show:null,position:"bottom",mode:null,color:null,tickColor:null,transform:null,inverseTransform:null,min:null,max:null,autoscaleMargin:null,ticks:null,tickFormatter:null,labelWidth:null,labelHeight:null,reserveSpace:null,tickLength:null,alignTicksWithAxis:null,tickDecimals:null,tickSize:null,minTickSize:null,monthNames:null,timeformat:null,twelveHourClock:false},yaxis:{autoscaleMargin:0.02,position:"left"},xaxes:[],yaxes:[],series:{points:{show:false,radius:3,lineWidth:2,fill:true,fillColor:"#ffffff",symbol:"circle"},lines:{lineWidth:2,fill:false,fillColor:null,steps:false},bars:{show:false,lineWidth:1,barWidth:1,fill:true,fillColor:{colors:[{opacity:0.7},{opacity:1}]},align:"left",horizontal:false},shadowSize:0},grid:{show:true,aboveData:false,color:"#545454",backgroundColor:null,borderColor:"#efefef",tickColor:"rgba(0,0,0,0.06)",labelMargin:10,axisMargin:8,borderWidth:0,minBorderMargin:10,markings:null,markingsColor:"#f4f4f4",markingsLineWidth:2,clickable:false,hoverable:false,autoHighlight:true,mouseActiveRadius:5},hooks:{}},aA=null,ad=null,y=null,H=null,A=null,p=[],ax=[],q={left:0,right:0,top:0,bottom:0},G=0,I=0,h=0,w=0,al={processOptions:[],processRawData:[],processDatapoints:[],drawSeries:[],draw:[],bindEvents:[],drawOverlay:[],shutdown:[]},ar=this;ar.setData=ak;ar.setupGrid=t;ar.draw=W;ar.getPlaceholder=function(){return aw};ar.getCanvas=function(){return aA};ar.getPlotOffset=function(){return q};ar.width=function(){return h};ar.height=function(){return w};ar.offset=function(){var aC=y.offset();aC.left+=q.left;aC.top+=q.top;return aC};ar.getData=function(){return Q};ar.getAxes=function(){var aD={},aC;c.each(p.concat(ax),function(aE,aF){if(aF){aD[aF.direction+(aF.n!=1?aF.n:"")+"axis"]=aF}});return aD};ar.getXAxes=function(){return p};ar.getYAxes=function(){return ax};ar.c2p=C;ar.p2c=at;ar.getOptions=function(){return O};ar.highlight=x;ar.unhighlight=T;ar.triggerRedrawOverlay=f;ar.pointOffset=function(aC){return{left:parseInt(p[aB(aC,"x")-1].p2c(+aC.x)+q.left),top:parseInt(ax[aB(aC,"y")-1].p2c(+aC.y)+q.top)}};ar.shutdown=ag;ar.resize=function(){B();g(aA);g(ad)};ar.hooks=al;F(ar);Z(J);X();ak(aj);t();W();ah();function ao(aE,aC){aC=[ar].concat(aC);for(var aD=0;aD<aE.length;++aD){aE[aD].apply(this,aC)}}function F(){for(var aC=0;aC<af.length;++aC){var aD=af[aC];aD.init(ar);if(aD.options){c.extend(true,O,aD.options)}}}function Z(aD){var aC;c.extend(true,O,aD);if(O.xaxis.color==null){O.xaxis.color=O.grid.color}if(O.yaxis.color==null){O.yaxis.color=O.grid.color}if(O.xaxis.tickColor==null){O.xaxis.tickColor=O.grid.tickColor}if(O.yaxis.tickColor==null){O.yaxis.tickColor=O.grid.tickColor}if(O.grid.borderColor==null){O.grid.borderColor=O.grid.color}if(O.grid.tickColor==null){O.grid.tickColor=c.color.parse(O.grid.color).scale("a",0.22).toString()}for(aC=0;aC<Math.max(1,O.xaxes.length);++aC){O.xaxes[aC]=c.extend(true,{},O.xaxis,O.xaxes[aC])}for(aC=0;aC<Math.max(1,O.yaxes.length);++aC){O.yaxes[aC]=c.extend(true,{},O.yaxis,O.yaxes[aC])}if(O.xaxis.noTicks&&O.xaxis.ticks==null){O.xaxis.ticks=O.xaxis.noTicks}if(O.yaxis.noTicks&&O.yaxis.ticks==null){O.yaxis.ticks=O.yaxis.noTicks}if(O.x2axis){O.xaxes[1]=c.extend(true,{},O.xaxis,O.x2axis);O.xaxes[1].position="top"}if(O.y2axis){O.yaxes[1]=c.extend(true,{},O.yaxis,O.y2axis);O.yaxes[1].position="right"}if(O.grid.coloredAreas){O.grid.markings=O.grid.coloredAreas}if(O.grid.coloredAreasColor){O.grid.markingsColor=O.grid.coloredAreasColor}if(O.lines){c.extend(true,O.series.lines,O.lines)}if(O.points){c.extend(true,O.series.points,O.points)}if(O.bars){c.extend(true,O.series.bars,O.bars)}if(O.shadowSize!=null){O.series.shadowSize=O.shadowSize}for(aC=0;aC<O.xaxes.length;++aC){V(p,aC+1).options=O.xaxes[aC]}for(aC=0;aC<O.yaxes.length;++aC){V(ax,aC+1).options=O.yaxes[aC]}for(var aE in al){if(O.hooks[aE]&&O.hooks[aE].length){al[aE]=al[aE].concat(O.hooks[aE])}}ao(al.processOptions,[O])}function ak(aC){Q=Y(aC);ay();z()}function Y(aF){var aD=[];for(var aC=0;aC<aF.length;++aC){var aE=c.extend(true,{},O.series);if(aF[aC].data!=null){aE.data=aF[aC].data;delete aF[aC].data;c.extend(true,aE,aF[aC]);aF[aC].data=aE.data}else{aE.data=aF[aC]}aD.push(aE)}return aD}function aB(aD,aE){var aC=aD[aE+"axis"];if(typeof aC=="object"){aC=aC.n}if(typeof aC!="number"){aC=1}return aC}function m(){return c.grep(p.concat(ax),function(aC){return aC})}function C(aF){var aD={},aC,aE;for(aC=0;aC<p.length;++aC){aE=p[aC];if(aE&&aE.used){aD["x"+aE.n]=aE.c2p(aF.left)}}for(aC=0;aC<ax.length;++aC){aE=ax[aC];if(aE&&aE.used){aD["y"+aE.n]=aE.c2p(aF.top)}}if(aD.x1!==undefined){aD.x=aD.x1}if(aD.y1!==undefined){aD.y=aD.y1}return aD}function at(aG){var aE={},aD,aF,aC;for(aD=0;aD<p.length;++aD){aF=p[aD];if(aF&&aF.used){aC="x"+aF.n;if(aG[aC]==null&&aF.n==1){aC="x"}if(aG[aC]!=null){aE.left=aF.p2c(aG[aC]);break}}}for(aD=0;aD<ax.length;++aD){aF=ax[aD];if(aF&&aF.used){aC="y"+aF.n;if(aG[aC]==null&&aF.n==1){aC="y"}if(aG[aC]!=null){aE.top=aF.p2c(aG[aC]);break}}}return aE}function V(aD,aC){if(!aD[aC-1]){aD[aC-1]={n:aC,direction:aD==p?"x":"y",options:c.extend(true,{},aD==p?O.xaxis:O.yaxis)}}return aD[aC-1]}function ay(){var aH;var aN=Q.length,aC=[],aF=[];for(aH=0;aH<Q.length;++aH){var aK=Q[aH].color;if(aK!=null){--aN;if(typeof aK=="number"){aF.push(aK)}else{aC.push(c.color.parse(Q[aH].color))}}}for(aH=0;aH<aF.length;++aH){aN=Math.max(aN,aF[aH]+1)}var aD=[],aG=0;aH=0;while(aD.length<aN){var aJ;if(O.colors.length==aH){aJ=c.color.make(100,100,100)}else{aJ=c.color.parse(O.colors[aH])}var aE=aG%2==1?-1:1;aJ.scale("rgb",1+aE*Math.ceil(aG/2)*0.2);aD.push(aJ);++aH;if(aH>=O.colors.length){aH=0;++aG}}var aI=0,aO;for(aH=0;aH<Q.length;++aH){aO=Q[aH];if(aO.color==null){aO.color=aD[aI].toString();++aI}else{if(typeof aO.color=="number"){aO.color=aD[aO.color].toString()}}if(aO.lines.show==null){var aM,aL=true;for(aM in aO){if(aO[aM]&&aO[aM].show){aL=false;break}}if(aL){aO.lines.show=true}}aO.xaxis=V(p,aB(aO,"x"));aO.yaxis=V(ax,aB(aO,"y"))}}function z(){var aP=Number.POSITIVE_INFINITY,aJ=Number.NEGATIVE_INFINITY,aC=Number.MAX_VALUE,aV,aT,aS,aO,aE,aK,aU,aQ,aI,aH,aD,a1,aY,aM;function aG(a4,a3,a2){if(a3<a4.datamin&&a3!=-aC){a4.datamin=a3}if(a2>a4.datamax&&a2!=aC){a4.datamax=a2}}c.each(m(),function(a2,a3){a3.datamin=aP;a3.datamax=aJ;a3.used=false});for(aV=0;aV<Q.length;++aV){aK=Q[aV];aK.datapoints={points:[]};ao(al.processRawData,[aK,aK.data,aK.datapoints])}for(aV=0;aV<Q.length;++aV){aK=Q[aV];var a0=aK.data,aX=aK.datapoints.format;if(!aX){aX=[];aX.push({x:true,number:true,required:true});aX.push({y:true,number:true,required:true});if(aK.bars.show||(aK.lines.show&&aK.lines.fill)){aX.push({y:true,number:true,required:false,defaultValue:0});if(aK.bars.horizontal){delete aX[aX.length-1].y;aX[aX.length-1].x=true}}aK.datapoints.format=aX}if(aK.datapoints.pointsize!=null){continue}aK.datapoints.pointsize=aX.length;aQ=aK.datapoints.pointsize;aU=aK.datapoints.points;insertSteps=aK.lines.show&&aK.lines.steps;aK.xaxis.used=aK.yaxis.used=true;for(aT=aS=0;aT<a0.length;++aT,aS+=aQ){aM=a0[aT];var aF=aM==null;if(!aF){for(aO=0;aO<aQ;++aO){a1=aM[aO];aY=aX[aO];if(aY){if(aY.number&&a1!=null){a1=+a1;if(isNaN(a1)){a1=null}else{if(a1==Infinity){a1=aC}else{if(a1==-Infinity){a1=-aC}}}}if(a1==null){if(aY.required){aF=true}if(aY.defaultValue!=null){a1=aY.defaultValue}}}aU[aS+aO]=a1}}if(aF){for(aO=0;aO<aQ;++aO){a1=aU[aS+aO];if(a1!=null){aY=aX[aO];if(aY.x){aG(aK.xaxis,a1,a1)}if(aY.y){aG(aK.yaxis,a1,a1)}}aU[aS+aO]=null}}else{if(insertSteps&&aS>0&&aU[aS-aQ]!=null&&aU[aS-aQ]!=aU[aS]&&aU[aS-aQ+1]!=aU[aS+1]){for(aO=0;aO<aQ;++aO){aU[aS+aQ+aO]=aU[aS+aO]}aU[aS+1]=aU[aS-aQ+1];aS+=aQ}}}}for(aV=0;aV<Q.length;++aV){aK=Q[aV];ao(al.processDatapoints,[aK,aK.datapoints])}for(aV=0;aV<Q.length;++aV){aK=Q[aV];aU=aK.datapoints.points,aQ=aK.datapoints.pointsize;var aL=aP,aR=aP,aN=aJ,aW=aJ;for(aT=0;aT<aU.length;aT+=aQ){if(aU[aT]==null){continue}for(aO=0;aO<aQ;++aO){a1=aU[aT+aO];aY=aX[aO];if(!aY||a1==aC||a1==-aC){continue}if(aY.x){if(a1<aL){aL=a1}if(a1>aN){aN=a1}}if(aY.y){if(a1<aR){aR=a1}if(a1>aW){aW=a1}}}}if(aK.bars.show){var aZ=aK.bars.align=="left"?0:-aK.bars.barWidth/2;if(aK.bars.horizontal){aR+=aZ;aW+=aZ+aK.bars.barWidth}else{aL+=aZ;aN+=aZ+aK.bars.barWidth}}aG(aK.xaxis,aL,aN);aG(aK.yaxis,aR,aW)}c.each(m(),function(a2,a3){if(a3.datamin==aP){a3.datamin=null}if(a3.datamax==aJ){a3.datamax=null}})}function j(aC,aD){var aE=document.createElement("canvas");aE.className=aD;aE.width=G;aE.height=I;if(!aC){c(aE).css({position:"absolute",left:0,top:0})}c(aE).appendTo(aw);if(ai){aE.width=G*2;aE.height=I*2;aE.style.width=""+G+"px";aE.style.height=""+I+"px"}if(!aE.getContext){aE=window.G_vmlCanvasManager.initElement(aE)}aE.getContext("2d").save();if(ai){aE.getContext("2d").scale(2,2)}return aE}function B(){G=aw.width();I=aw.height();if(G<=0||I<=0){throw"Invalid dimensions for plot, width = "+G+", height = "+I}}function g(aD){if(aD.width!=G){aD.width=G;if(ai){aD.width=G*2}aD.style.width=""+G+"px"}if(aD.height!=I){aD.height=I;if(ai){aD.height=I*2}aD.style.height=""+I+"px"}var aC=aD.getContext("2d");aC.restore();aC.save();if(ai){aC.scale(2,2)}}function X(){var aD,aC=aw.children("canvas.base"),aE=aw.children("canvas.overlay");if(aC.length==0||aE==0){aw.html("");aw.css({padding:0});if(aw.css("position")=="static"){aw.css("position","relative")}B();aA=j(true,"base");ad=j(false,"overlay");aD=false}else{aA=aC.get(0);ad=aE.get(0);aD=true}H=aA.getContext("2d");A=ad.getContext("2d");y=c([ad,aA]);if(aD){aw.data("plot").shutdown();ar.resize();A.clearRect(0,0,G,I);y.unbind();aw.children().not([aA,ad]).remove()}aw.data("plot",ar)}function ah(){if(O.grid.hoverable){y.mousemove(aa);y.mouseleave(l)}if(O.grid.clickable){y.click(R)}ao(al.bindEvents,[y])}function ag(){if(M){clearTimeout(M)}y.unbind("mousemove",aa);y.unbind("mouseleave",l);y.unbind("click",R);ao(al.shutdown,[y])}function r(aH){function aD(aI){return aI}var aG,aC,aE=aH.options.transform||aD,aF=aH.options.inverseTransform;if(aH.direction=="x"){aG=aH.scale=h/Math.abs(aE(aH.max)-aE(aH.min));aC=Math.min(aE(aH.max),aE(aH.min))}else{aG=aH.scale=w/Math.abs(aE(aH.max)-aE(aH.min));aG=-aG;aC=Math.max(aE(aH.max),aE(aH.min))}if(aE==aD){aH.p2c=function(aI){return(aI-aC)*aG}}else{aH.p2c=function(aI){return(aE(aI)-aC)*aG}}if(!aF){aH.c2p=function(aI){return aC+aI/aG}}else{aH.c2p=function(aI){return aF(aC+aI/aG)}}}function L(aE){var aC=aE.options,aG,aK=aE.ticks||[],aJ=[],aF,aL=aC.labelWidth,aH=aC.labelHeight,aD;function aI(aN,aM){return c('<div style="position:absolute;top:-10000px;'+aM+'font-size:smaller"><div class="'+aE.direction+"Axis "+aE.direction+aE.n+'Axis">'+aN.join("")+"</div></div>").appendTo(aw)}if(aE.direction=="x"){if(aL==null){aL=Math.floor(G/(aK.length>0?aK.length:1))}if(aH==null){aJ=[];for(aG=0;aG<aK.length;++aG){aF=aK[aG].label;if(aF){aJ.push('<div class="tickLabel" style="float:left;width:'+aL+'px">'+aF+"</div>")}}if(aJ.length>0){aJ.push('<div style="clear:left"></div>');aD=aI(aJ,"width:10000px;");aH=aD.height();aD.remove()}}}else{if(aL==null||aH==null){for(aG=0;aG<aK.length;++aG){aF=aK[aG].label;if(aF){aJ.push('<div class="tickLabel">'+aF+"</div>")}}if(aJ.length>0){aD=aI(aJ,"");if(aL==null){aL=aD.children().width()}if(aH==null){aH=aD.find("div.tickLabel").height()}aD.remove()}}}if(aL==null){aL=0}if(aH==null){aH=0}aE.labelWidth=aL;aE.labelHeight=aH}function av(aE){var aD=aE.labelWidth,aM=aE.labelHeight,aI=aE.options.position,aG=aE.options.tickLength,aH=O.grid.axisMargin,aK=O.grid.labelMargin,aL=aE.direction=="x"?p:ax,aF;var aC=c.grep(aL,function(aO){return aO&&aO.options.position==aI&&aO.reserveSpace});if(c.inArray(aE,aC)==aC.length-1){aH=0}if(aG==null){aG="full"}var aJ=c.grep(aL,function(aO){return aO&&aO.reserveSpace});var aN=c.inArray(aE,aJ)==0;if(!aN&&aG=="full"){aG=5}if(!isNaN(+aG)){aK+=+aG}if(aE.direction=="x"){aM+=aK;if(aI=="bottom"){q.bottom+=aM+aH;aE.box={top:I-q.bottom,height:aM}}else{aE.box={top:q.top+aH,height:aM};q.top+=aM+aH}}else{aD+=aK;if(aI=="left"){aE.box={left:q.left+aH,width:aD};q.left+=aD+aH}else{q.right+=aD+aH;aE.box={left:G-q.right,width:aD}}}aE.position=aI;aE.tickLength=aG;aE.box.padding=aK;aE.innermost=aN}function U(aC){if(aC.direction=="x"){aC.box.left=q.left;aC.box.width=h}else{aC.box.top=q.top;aC.box.height=w}}function t(){var aD,aF=m();c.each(aF,function(aG,aH){aH.show=aH.options.show;if(aH.show==null){aH.show=aH.used}aH.reserveSpace=aH.show||aH.options.reserveSpace;n(aH)});allocatedAxes=c.grep(aF,function(aG){return aG.reserveSpace});q.left=q.right=q.top=q.bottom=0;if(O.grid.show){c.each(allocatedAxes,function(aG,aH){S(aH);P(aH);aq(aH,aH.ticks);L(aH)});for(aD=allocatedAxes.length-1;aD>=0;--aD){av(allocatedAxes[aD])}var aE=O.grid.minBorderMargin;if(aE==null){aE=0;for(aD=0;aD<Q.length;++aD){aE=Math.max(aE,Q[aD].points.radius+Q[aD].points.lineWidth/2)}}for(var aC in q){q[aC]+=O.grid.borderWidth;q[aC]=Math.max(aE,q[aC])}}h=G-q.left-q.right;w=I-q.bottom-q.top;c.each(aF,function(aG,aH){r(aH)});if(O.grid.show){c.each(allocatedAxes,function(aG,aH){U(aH)});k()}o()}function n(aF){var aG=aF.options,aE=+(aG.min!=null?aG.min:aF.datamin),aC=+(aG.max!=null?aG.max:aF.datamax),aI=aC-aE;if(aI==0){var aD=aC==0?1:0.01;if(aG.min==null){aE-=aD}if(aG.max==null||aG.min!=null){aC+=aD}}else{var aH=aG.autoscaleMargin;if(aH!=null){if(aG.min==null){aE-=aI*aH;if(aE<0&&aF.datamin!=null&&aF.datamin>=0){aE=0}}if(aG.max==null){aC+=aI*aH;if(aC>0&&aF.datamax!=null&&aF.datamax<=0){aC=0}}}}aF.min=aE;aF.max=aC}function S(aH){var aN=aH.options;var aI;if(typeof aN.ticks=="number"&&aN.ticks>0){aI=aN.ticks}else{aI=0.3*Math.sqrt(aH.direction=="x"?G:I)}var aU=(aH.max-aH.min)/aI,aP,aC,aO,aS,aT,aR,aJ;if(aN.mode=="time"){var aK={second:1000,minute:60*1000,hour:60*60*1000,day:24*60*60*1000,month:30*24*60*60*1000,year:365.2425*24*60*60*1000};var aL=[[1,"second"],[2,"second"],[5,"second"],[10,"second"],[30,"second"],[1,"minute"],[2,"minute"],[5,"minute"],[10,"minute"],[30,"minute"],[1,"hour"],[2,"hour"],[4,"hour"],[8,"hour"],[12,"hour"],[1,"day"],[2,"day"],[3,"day"],[0.25,"month"],[0.5,"month"],[1,"month"],[2,"month"],[3,"month"],[6,"month"],[1,"year"]];var aD=0;if(aN.minTickSize!=null){if(typeof aN.tickSize=="number"){aD=aN.tickSize}else{aD=aN.minTickSize[0]*aK[aN.minTickSize[1]]}}for(var aT=0;aT<aL.length-1;++aT){if(aU<(aL[aT][0]*aK[aL[aT][1]]+aL[aT+1][0]*aK[aL[aT+1][1]])/2&&aL[aT][0]*aK[aL[aT][1]]>=aD){break}}aP=aL[aT][0];aO=aL[aT][1];if(aO=="year"){aR=Math.pow(10,Math.floor(Math.log(aU/aK.year)/Math.LN10));aJ=(aU/aK.year)/aR;if(aJ<1.5){aP=1}else{if(aJ<3){aP=2}else{if(aJ<7.5){aP=5}else{aP=10}}}aP*=aR}aH.tickSize=aN.tickSize||[aP,aO];aC=function(aY){var a3=[],a1=aY.tickSize[0],a4=aY.tickSize[1],a2=new Date(aY.min);var aX=a1*aK[a4];if(a4=="second"){a2.setUTCSeconds(a(a2.getUTCSeconds(),a1))}if(a4=="minute"){a2.setUTCMinutes(a(a2.getUTCMinutes(),a1))}if(a4=="hour"){a2.setUTCHours(a(a2.getUTCHours(),a1))}if(a4=="month"){a2.setUTCMonth(a(a2.getUTCMonth(),a1))}if(a4=="year"){a2.setUTCFullYear(a(a2.getUTCFullYear(),a1))}a2.setUTCMilliseconds(0);if(aX>=aK.minute){a2.setUTCSeconds(0)}if(aX>=aK.hour){a2.setUTCMinutes(0)}if(aX>=aK.day){a2.setUTCHours(0)}if(aX>=aK.day*4){a2.setUTCDate(1)}if(aX>=aK.year){a2.setUTCMonth(0)}var a6=0,a5=Number.NaN,aZ;do{aZ=a5;a5=a2.getTime();a3.push(a5);if(a4=="month"){if(a1<1){a2.setUTCDate(1);var aW=a2.getTime();a2.setUTCMonth(a2.getUTCMonth()+1);var a0=a2.getTime();a2.setTime(a5+a6*aK.hour+(a0-aW)*a1);a6=a2.getUTCHours();a2.setUTCHours(0)}else{a2.setUTCMonth(a2.getUTCMonth()+a1)}}else{if(a4=="year"){a2.setUTCFullYear(a2.getUTCFullYear()+a1)}else{a2.setTime(a5+aX)}}}while(a5<aY.max&&a5!=aZ);return a3};aS=function(aW,aZ){var a1=new Date(aW);if(aN.timeformat!=null){return c.plot.formatDate(a1,aN.timeformat,aN.monthNames)}var aX=aZ.tickSize[0]*aK[aZ.tickSize[1]];var aY=aZ.max-aZ.min;var a0=(aN.twelveHourClock)?" %p":"";if(aX<aK.minute){fmt="%h:%M:%S"+a0}else{if(aX<aK.day){if(aY<2*aK.day){fmt="%h:%M"+a0}else{fmt="%b %d %h:%M"+a0}}else{if(aX<aK.month){fmt="%b %d"}else{if(aX<aK.year){if(aY<aK.year){fmt="%b"}else{fmt="%b %y"}}else{fmt="%y"}}}}return c.plot.formatDate(a1,fmt,aN.monthNames)}}else{var aV=aN.tickDecimals;var aQ=-Math.floor(Math.log(aU)/Math.LN10);if(aV!=null&&aQ>aV){aQ=aV}aR=Math.pow(10,-aQ);aJ=aU/aR;if(aJ<1.5){aP=1}else{if(aJ<3){aP=2;if(aJ>2.25&&(aV==null||aQ+1<=aV)){aP=2.5;++aQ}}else{if(aJ<7.5){aP=5}else{aP=10}}}aP*=aR;if(aN.minTickSize!=null&&aP<aN.minTickSize){aP=aN.minTickSize}aH.tickDecimals=Math.max(0,aV!=null?aV:aQ);aH.tickSize=aN.tickSize||aP;aC=function(aY){var a0=[];var a1=a(aY.min,aY.tickSize),aX=0,aW=Number.NaN,aZ;do{aZ=aW;aW=a1+aX*aY.tickSize;a0.push(aW);++aX}while(aW<aY.max&&aW!=aZ);return a0};aS=function(aW,aX){return aW.toFixed(aX.tickDecimals)}}if(aN.alignTicksWithAxis!=null){var aG=(aH.direction=="x"?p:ax)[aN.alignTicksWithAxis-1];if(aG&&aG.used&&aG!=aH){var aM=aC(aH);if(aM.length>0){if(aN.min==null){aH.min=Math.min(aH.min,aM[0])}if(aN.max==null&&aM.length>1){aH.max=Math.max(aH.max,aM[aM.length-1])}}aC=function(aY){var aZ=[],aW,aX;for(aX=0;aX<aG.ticks.length;++aX){aW=(aG.ticks[aX].v-aG.min)/(aG.max-aG.min);aW=aY.min+aW*(aY.max-aY.min);aZ.push(aW)}return aZ};if(aH.mode!="time"&&aN.tickDecimals==null){var aF=Math.max(0,-Math.floor(Math.log(aU)/Math.LN10)+1),aE=aC(aH);if(!(aE.length>1&&/\..*0$/.test((aE[1]-aE[0]).toFixed(aF)))){aH.tickDecimals=aF}}}}aH.tickGenerator=aC;if(c.isFunction(aN.tickFormatter)){aH.tickFormatter=function(aW,aX){return""+aN.tickFormatter(aW,aX)}}else{aH.tickFormatter=aS}}function P(aG){var aI=aG.options.ticks,aH=[];if(aI==null||(typeof aI=="number"&&aI>0)){aH=aG.tickGenerator(aG)}else{if(aI){if(c.isFunction(aI)){aH=aI({min:aG.min,max:aG.max})}else{aH=aI}}}var aF,aC;aG.ticks=[];for(aF=0;aF<aH.length;++aF){var aD=null;var aE=aH[aF];if(typeof aE=="object"){aC=+aE[0];if(aE.length>1){aD=aE[1]}}else{aC=+aE}if(aD==null){aD=aG.tickFormatter(aC,aG)}if(!isNaN(aC)){aG.ticks.push({v:aC,label:aD})}}}function aq(aC,aD){if(aC.options.autoscaleMargin&&aD.length>0){if(aC.options.min==null){aC.min=Math.min(aC.min,aD[0].v)}if(aC.options.max==null&&aD.length>1){aC.max=Math.max(aC.max,aD[aD.length-1].v)}}}function W(){H.clearRect(0,0,G,I);var aD=O.grid;if(aD.show&&aD.backgroundColor){N()}if(aD.show&&!aD.aboveData){ac()}for(var aC=0;aC<Q.length;++aC){ao(al.drawSeries,[H,Q[aC]]);d(Q[aC])}ao(al.draw,[H]);if(aD.show&&aD.aboveData){ac()}}function D(aC,aJ){var aF,aI,aH,aE,aG=m();for(i=0;i<aG.length;++i){aF=aG[i];if(aF.direction==aJ){aE=aJ+aF.n+"axis";if(!aC[aE]&&aF.n==1){aE=aJ+"axis"}if(aC[aE]){aI=aC[aE].from;aH=aC[aE].to;break}}}if(!aC[aE]){aF=aJ=="x"?p[0]:ax[0];aI=aC[aJ+"1"];aH=aC[aJ+"2"]}if(aI!=null&&aH!=null&&aI>aH){var aD=aI;aI=aH;aH=aD}return{from:aI,to:aH,axis:aF}}function N(){H.save();H.translate(q.left,q.top);H.fillStyle=an(O.grid.backgroundColor,w,0,"rgba(255, 255, 255, 0)");H.fillRect(0,0,h,w);H.restore()}function ac(){var aG;H.save();H.translate(q.left,q.top);var aI=O.grid.markings;if(aI){if(c.isFunction(aI)){var aL=ar.getAxes();aL.xmin=aL.xaxis.min;aL.xmax=aL.xaxis.max;aL.ymin=aL.yaxis.min;aL.ymax=aL.yaxis.max;aI=aI(aL)}for(aG=0;aG<aI.length;++aG){var aE=aI[aG],aD=D(aE,"x"),aJ=D(aE,"y");if(aD.from==null){aD.from=aD.axis.min}if(aD.to==null){aD.to=aD.axis.max}if(aJ.from==null){aJ.from=aJ.axis.min}if(aJ.to==null){aJ.to=aJ.axis.max}if(aD.to<aD.axis.min||aD.from>aD.axis.max||aJ.to<aJ.axis.min||aJ.from>aJ.axis.max){continue}aD.from=Math.max(aD.from,aD.axis.min);aD.to=Math.min(aD.to,aD.axis.max);aJ.from=Math.max(aJ.from,aJ.axis.min);aJ.to=Math.min(aJ.to,aJ.axis.max);if(aD.from==aD.to&&aJ.from==aJ.to){continue}aD.from=aD.axis.p2c(aD.from);aD.to=aD.axis.p2c(aD.to);aJ.from=aJ.axis.p2c(aJ.from);aJ.to=aJ.axis.p2c(aJ.to);if(aD.from==aD.to||aJ.from==aJ.to){H.beginPath();H.strokeStyle=aE.color||O.grid.markingsColor;H.lineWidth=aE.lineWidth||O.grid.markingsLineWidth;H.moveTo(aD.from,aJ.from);H.lineTo(aD.to,aJ.to);H.stroke()}else{H.fillStyle=aE.color||O.grid.markingsColor;H.fillRect(aD.from,aJ.to,aD.to-aD.from,aJ.from-aJ.to)}}}var aL=m(),aN=O.grid.borderWidth;for(var aF=0;aF<aL.length;++aF){var aC=aL[aF],aH=aC.box,aR=aC.tickLength,aO,aM,aQ,aK;if(!aC.show||aC.ticks.length==0){continue}H.strokeStyle=aC.options.tickColor||c.color.parse(aC.options.color).scale("a",0.22).toString();H.lineWidth=1;if(aC.direction=="x"){aO=0;if(aR=="full"){aM=(aC.position=="top"?0:w)}else{aM=aH.top-q.top+(aC.position=="top"?aH.height:0)}}else{aM=0;if(aR=="full"){aO=(aC.position=="left"?0:h)}else{aO=aH.left-q.left+(aC.position=="left"?aH.width:0)}}if(!aC.innermost){H.beginPath();aQ=aK=0;if(aC.direction=="x"){aQ=h}else{aK=w}if(H.lineWidth==1){aO=Math.floor(aO)+0.5;aM=Math.floor(aM)+0.5}H.moveTo(aO,aM);H.lineTo(aO+aQ,aM+aK);H.stroke()}H.beginPath();for(aG=0;aG<aC.ticks.length;++aG){var aP=aC.ticks[aG].v;aQ=aK=0;if(aP<aC.min||aP>aC.max||(aR=="full"&&aN>0&&(aP==aC.min||aP==aC.max))){continue}if(aC.direction=="x"){aO=aC.p2c(aP);aK=aR=="full"?-w:aR;if(aC.position=="top"){aK=-aK}}else{aM=aC.p2c(aP);aQ=aR=="full"?-h:aR;if(aC.position=="left"){aQ=-aQ}}if(H.lineWidth==1){if(aC.direction=="x"){aO=Math.floor(aO)+0.5}else{aM=Math.floor(aM)+0.5}}H.moveTo(aO,aM);H.lineTo(aO+aQ,aM+aK)}H.stroke()}if(aN){H.lineWidth=aN;H.strokeStyle=O.grid.borderColor;H.strokeRect(-aN/2,-aN/2,h+aN,w+aN)}H.restore()}function k(){aw.find(".tickLabels").remove();var aH=['<div class="tickLabels" style="font-size:smaller">'];var aK=m();for(var aE=0;aE<aK.length;++aE){var aD=aK[aE],aG=aD.box;if(!aD.show){continue}aH.push('<div class="'+aD.direction+"Axis "+aD.direction+aD.n+'Axis" style="color:'+aD.options.color+'">');for(var aF=0;aF<aD.ticks.length;++aF){var aI=aD.ticks[aF];if(!aI.label||aI.v<aD.min||aI.v>aD.max){continue}var aL={},aJ;if(aD.direction=="x"){aJ="center";aL.left=Math.round(q.left+aD.p2c(aI.v)-aD.labelWidth/2);if(aD.position=="bottom"){aL.top=aG.top+aG.padding}else{aL.bottom=I-(aG.top+aG.height-aG.padding)}}else{aL.top=Math.round(q.top+aD.p2c(aI.v)-aD.labelHeight/2);if(aD.position=="left"){aL.right=G-(aG.left+aG.width-aG.padding);aJ="right"}else{aL.left=aG.left+aG.padding;aJ="left"}}aL.width=aD.labelWidth;var aC=["position:absolute","text-align:"+aJ];for(var aM in aL){aC.push(aM+":"+aL[aM]+"px")}aH.push('<div class="tickLabel" style="'+aC.join(";")+'">'+aI.label+"</div>")}aH.push("</div>")}aH.push("</div>");aw.append(aH.join(""))}function d(aC){if(aC.lines.show){au(aC)}if(aC.bars.show){e(aC)}if(aC.points.show){ap(aC)}}function au(aF){function aE(aQ,aR,aJ,aV,aU){var aW=aQ.points,aK=aQ.pointsize,aO=null,aN=null;H.beginPath();for(var aP=aK;aP<aW.length;aP+=aK){var aM=aW[aP-aK],aT=aW[aP-aK+1],aL=aW[aP],aS=aW[aP+1];if(aM==null||aL==null){continue}if(aT<=aS&&aT<aU.min){if(aS<aU.min){continue}aM=(aU.min-aT)/(aS-aT)*(aL-aM)+aM;aT=aU.min}else{if(aS<=aT&&aS<aU.min){if(aT<aU.min){continue}aL=(aU.min-aT)/(aS-aT)*(aL-aM)+aM;aS=aU.min}}if(aT>=aS&&aT>aU.max){if(aS>aU.max){continue}aM=(aU.max-aT)/(aS-aT)*(aL-aM)+aM;aT=aU.max}else{if(aS>=aT&&aS>aU.max){if(aT>aU.max){continue}aL=(aU.max-aT)/(aS-aT)*(aL-aM)+aM;aS=aU.max}}if(aM<=aL&&aM<aV.min){if(aL<aV.min){continue}aT=(aV.min-aM)/(aL-aM)*(aS-aT)+aT;aM=aV.min}else{if(aL<=aM&&aL<aV.min){if(aM<aV.min){continue}aS=(aV.min-aM)/(aL-aM)*(aS-aT)+aT;aL=aV.min}}if(aM>=aL&&aM>aV.max){if(aL>aV.max){continue}aT=(aV.max-aM)/(aL-aM)*(aS-aT)+aT;aM=aV.max}else{if(aL>=aM&&aL>aV.max){if(aM>aV.max){continue}aS=(aV.max-aM)/(aL-aM)*(aS-aT)+aT;aL=aV.max}}if(aM!=aO||aT!=aN){H.moveTo(aV.p2c(aM)+aR,aU.p2c(aT)+aJ)}aO=aL;aN=aS;H.lineTo(aV.p2c(aL)+aR,aU.p2c(aS)+aJ)}H.stroke()}function aG(aJ,aR,aQ){var aX=aJ.points,aW=aJ.pointsize,aO=Math.min(Math.max(0,aQ.min),aQ.max),aY=0,aV,aU=false,aN=1,aM=0,aS=0;while(true){if(aW>0&&aY>aX.length+aW){break}aY+=aW;var a0=aX[aY-aW],aL=aX[aY-aW+aN],aZ=aX[aY],aK=aX[aY+aN];if(aU){if(aW>0&&a0!=null&&aZ==null){aS=aY;aW=-aW;aN=2;continue}if(aW<0&&aY==aM+aW){H.fill();aU=false;aW=-aW;aN=1;aY=aM=aS+aW;continue}}if(a0==null||aZ==null){continue}if(a0<=aZ&&a0<aR.min){if(aZ<aR.min){continue}aL=(aR.min-a0)/(aZ-a0)*(aK-aL)+aL;a0=aR.min}else{if(aZ<=a0&&aZ<aR.min){if(a0<aR.min){continue}aK=(aR.min-a0)/(aZ-a0)*(aK-aL)+aL;aZ=aR.min}}if(a0>=aZ&&a0>aR.max){if(aZ>aR.max){continue}aL=(aR.max-a0)/(aZ-a0)*(aK-aL)+aL;a0=aR.max}else{if(aZ>=a0&&aZ>aR.max){if(a0>aR.max){continue}aK=(aR.max-a0)/(aZ-a0)*(aK-aL)+aL;aZ=aR.max}}if(!aU){H.beginPath();H.moveTo(aR.p2c(a0),aQ.p2c(aO));aU=true}if(aL>=aQ.max&&aK>=aQ.max){H.lineTo(aR.p2c(a0),aQ.p2c(aQ.max));H.lineTo(aR.p2c(aZ),aQ.p2c(aQ.max));continue}else{if(aL<=aQ.min&&aK<=aQ.min){H.lineTo(aR.p2c(a0),aQ.p2c(aQ.min));H.lineTo(aR.p2c(aZ),aQ.p2c(aQ.min));continue}}var aP=a0,aT=aZ;if(aL<=aK&&aL<aQ.min&&aK>=aQ.min){a0=(aQ.min-aL)/(aK-aL)*(aZ-a0)+a0;aL=aQ.min}else{if(aK<=aL&&aK<aQ.min&&aL>=aQ.min){aZ=(aQ.min-aL)/(aK-aL)*(aZ-a0)+a0;aK=aQ.min}}if(aL>=aK&&aL>aQ.max&&aK<=aQ.max){a0=(aQ.max-aL)/(aK-aL)*(aZ-a0)+a0;aL=aQ.max}else{if(aK>=aL&&aK>aQ.max&&aL<=aQ.max){aZ=(aQ.max-aL)/(aK-aL)*(aZ-a0)+a0;aK=aQ.max}}if(a0!=aP){H.lineTo(aR.p2c(aP),aQ.p2c(aL))}H.lineTo(aR.p2c(a0),aQ.p2c(aL));H.lineTo(aR.p2c(aZ),aQ.p2c(aK));if(aZ!=aT){H.lineTo(aR.p2c(aZ),aQ.p2c(aK));H.lineTo(aR.p2c(aT),aQ.p2c(aK))}}}H.save();H.translate(q.left,q.top);H.lineJoin="round";var aH=aF.lines.lineWidth,aC=aF.shadowSize;if(aH>0&&aC>0){H.lineWidth=aC;H.strokeStyle="rgba(0,0,0,0.1)";var aI=Math.PI/18;aE(aF.datapoints,Math.sin(aI)*(aH/2+aC/2),Math.cos(aI)*(aH/2+aC/2),aF.xaxis,aF.yaxis);H.lineWidth=aC/2;aE(aF.datapoints,Math.sin(aI)*(aH/2+aC/4),Math.cos(aI)*(aH/2+aC/4),aF.xaxis,aF.yaxis)}H.lineWidth=aH;H.strokeStyle=aF.color;var aD=ae(aF.lines,aF.color,0,w);if(aD){H.fillStyle=aD;aG(aF.datapoints,aF.xaxis,aF.yaxis)}if(aH>0){aE(aF.datapoints,0,0,aF.xaxis,aF.yaxis)}H.restore()}function ap(aF){function aI(aO,aN,aV,aL,aT,aU,aR,aK){var aS=aO.points,aJ=aO.pointsize;for(var aM=0;aM<aS.length;aM+=aJ){var aQ=aS[aM],aP=aS[aM+1];if(aQ==null||aQ<aU.min||aQ>aU.max||aP<aR.min||aP>aR.max){continue}H.beginPath();aQ=aU.p2c(aQ);aP=aR.p2c(aP)+aL;if(aK=="circle"){H.arc(aQ,aP,aN,0,aT?Math.PI:Math.PI*2,false)}else{aK(H,aQ,aP,aN,aT)}H.closePath();if(aV){H.fillStyle=aV;H.fill()}H.stroke()}}H.save();H.translate(q.left,q.top);var aH=aF.points.lineWidth,aD=aF.shadowSize,aC=aF.points.radius,aG=aF.points.symbol;if(aH>0&&aD>0){var aE=aD/2;H.lineWidth=aE;H.strokeStyle="rgba(0,0,0,0.1)";aI(aF.datapoints,aC,null,aE+aE/2,true,aF.xaxis,aF.yaxis,aG);H.strokeStyle="rgba(0,0,0,0.2)";aI(aF.datapoints,aC,null,aE/2,true,aF.xaxis,aF.yaxis,aG)}H.lineWidth=aH;H.strokeStyle=aF.color;aI(aF.datapoints,aC,ae(aF.points,aF.color),0,false,aF.xaxis,aF.yaxis,aG);H.restore()}function E(aO,aN,aW,aJ,aR,aG,aE,aM,aL,aV,aS,aD){var aF,aU,aK,aQ,aH,aC,aP,aI,aT;if(aS){aI=aC=aP=true;aH=false;aF=aW;aU=aO;aQ=aN+aJ;aK=aN+aR;if(aU<aF){aT=aU;aU=aF;aF=aT;aH=true;aC=false}}else{aH=aC=aP=true;aI=false;aF=aO+aJ;aU=aO+aR;aK=aW;aQ=aN;if(aQ<aK){aT=aQ;aQ=aK;aK=aT;aI=true;aP=false}}if(aU<aM.min||aF>aM.max||aQ<aL.min||aK>aL.max){return}if(aF<aM.min){aF=aM.min;aH=false}if(aU>aM.max){aU=aM.max;aC=false}if(aK<aL.min){aK=aL.min;aI=false}if(aQ>aL.max){aQ=aL.max;aP=false}aF=aM.p2c(aF);aK=aL.p2c(aK);aU=aM.p2c(aU);aQ=aL.p2c(aQ);if(aE){aV.beginPath();aV.moveTo(aF,aK);aV.lineTo(aF,aQ);aV.lineTo(aU,aQ);aV.lineTo(aU,aK);aV.fillStyle=aE(aK,aQ);aV.fill()}if(aD>0&&(aH||aC||aP||aI)){aV.beginPath();aV.moveTo(aF,aK+aG);if(aH){aV.lineTo(aF,aQ+aG)}else{aV.moveTo(aF,aQ+aG)}if(aP){aV.lineTo(aU,aQ+aG)}else{aV.moveTo(aU,aQ+aG)}if(aC){aV.lineTo(aU,aK+aG)}else{aV.moveTo(aU,aK+aG)}if(aI){aV.lineTo(aF,aK+aG)}else{aV.moveTo(aF,aK+aG)}aV.stroke()}}function e(aE){function aD(aK,aJ,aM,aH,aL,aO,aN){var aP=aK.points,aG=aK.pointsize;for(var aI=0;aI<aP.length;aI+=aG){if(aP[aI]==null){continue}E(aP[aI],aP[aI+1],aP[aI+2],aJ,aM,aH,aL,aO,aN,H,aE.bars.horizontal,aE.bars.lineWidth)}}H.save();H.translate(q.left,q.top);H.lineWidth=aE.bars.lineWidth;H.strokeStyle=aE.color;var aC=aE.bars.align=="left"?0:-aE.bars.barWidth/2;var aF=aE.bars.fill?function(aG,aH){return ae(aE.bars,aE.color,aG,aH)}:null;aD(aE.datapoints,aC,aC+aE.bars.barWidth,0,aF,aE.xaxis,aE.yaxis);H.restore()}function ae(aE,aC,aD,aG){var aF=aE.fill;if(!aF){return null}if(aE.fillColor){return an(aE.fillColor,aD,aG,aC)}var aH=c.color.parse(aC);aH.a=typeof aF=="number"?aF:0.4;aH.normalize();return aH.toString()}function o(){aw.find(".legend").remove();if(!O.legend.show){return}var aI=[],aG=false,aO=O.legend.labelFormatter,aN,aK;for(var aF=0;aF<Q.length;++aF){aN=Q[aF];aK=aN.label;if(!aK){continue}if(aF%O.legend.noColumns==0){if(aG){aI.push("</tr>")}aI.push("<tr>");aG=true}if(aO){aK=aO(aK,aN)}aI.push('<td class="legendColorBox"><div style="'+O.legend.labelBoxBorderColor+'"><div style="border:2px solid '+aN.color+';overflow:hidden"></div></div></td><td class="legendLabel"><span>'+aK+"</span></td>")}if(aG){aI.push("</tr>")}if(aI.length==0){return}var aM='<table style="font-size: 11px; color:'+O.grid.color+'">'+aI.join("")+"</table>";if(O.legend.container!=null){c(O.legend.container).html(aM)}else{var aJ="",aD=O.legend.position,aE=O.legend.margin;if(aE[0]==null){aE=[aE,aE]}if(aD.charAt(0)=="n"){aJ+="top:"+(aE[1]+q.top)+"px;"}else{if(aD.charAt(0)=="s"){aJ+="bottom:"+(aE[1]+q.bottom)+"px;"}}if(aD.charAt(1)=="e"){aJ+="right:"+(aE[0]+q.right)+"px;"}else{if(aD.charAt(1)=="w"){aJ+="left:"+(aE[0]+q.left)+"px;"}}var aL=c('<div class="legend">'+aM.replace('style="','style="position:absolute;'+aJ+";")+"</div>").appendTo(aw);if(O.legend.backgroundOpacity!=0){var aH=O.legend.backgroundColor;if(aH==null){aH=O.grid.backgroundColor;if(aH&&typeof aH=="string"){aH=c.color.parse(aH)}else{aH=c.color.extract(aL,"background-color")}aH.a=1;aH=aH.toString()}var aC=aL.children();c('<div style="position:absolute;width:'+aC.width()+"px;height:"+aC.height()+"px;"+aJ+"background-color:"+aH+';"> </div>').prependTo(aL).css("opacity",O.legend.backgroundOpacity)}}}var ab=[],M=null;function K(aJ,aH,aE){var aP=O.grid.mouseActiveRadius,a1=aP*aP+1,aZ=null,aS=false,aX,aV;for(aX=Q.length-1;aX>=0;--aX){if(!aE(Q[aX])){continue}var aQ=Q[aX],aI=aQ.xaxis,aG=aQ.yaxis,aW=aQ.datapoints.points,aU=aQ.datapoints.pointsize,aR=aI.c2p(aJ),aO=aG.c2p(aH),aD=aP/aI.scale,aC=aP/aG.scale;if(aI.options.inverseTransform){aD=Number.MAX_VALUE}if(aG.options.inverseTransform){aC=Number.MAX_VALUE}if(aQ.lines.show||aQ.points.show){for(aV=0;aV<aW.length;aV+=aU){var aL=aW[aV],aK=aW[aV+1];if(aL==null){continue}if(aL-aR>aD||aL-aR<-aD||aK-aO>aC||aK-aO<-aC){continue}var aN=Math.abs(aI.p2c(aL)-aJ),aM=Math.abs(aG.p2c(aK)-aH),aT=aN*aN+aM*aM;if(aT<a1){a1=aT;aZ=[aX,aV/aU]}}}if(aQ.bars.show&&!aZ){var aF=aQ.bars.align=="left"?0:-aQ.bars.barWidth/2,aY=aF+aQ.bars.barWidth;for(aV=0;aV<aW.length;aV+=aU){var aL=aW[aV],aK=aW[aV+1],a0=aW[aV+2];if(aL==null){continue}if(Q[aX].bars.horizontal?(aR<=Math.max(a0,aL)&&aR>=Math.min(a0,aL)&&aO>=aK+aF&&aO<=aK+aY):(aR>=aL+aF&&aR<=aL+aY&&aO>=Math.min(a0,aK)&&aO<=Math.max(a0,aK))){aZ=[aX,aV/aU]}}}}if(aZ){aX=aZ[0];aV=aZ[1];aU=Q[aX].datapoints.pointsize;return{datapoint:Q[aX].datapoints.points.slice(aV*aU,(aV+1)*aU),dataIndex:aV,series:Q[aX],seriesIndex:aX}}return null}function aa(aC){if(O.grid.hoverable){u("plothover",aC,function(aD){return aD.hoverable!=false})}}function l(aC){if(O.grid.hoverable){u("plothover",aC,function(aD){return false})}}function R(aC){u("plotclick",aC,function(aD){return aD.clickable!=false})}function u(aD,aC,aE){var aF=y.offset(),aI=aC.pageX-aF.left-q.left,aG=aC.pageY-aF.top-q.top,aK=C({left:aI,top:aG});aK.pageX=aC.pageX;aK.pageY=aC.pageY;var aL=K(aI,aG,aE);if(aL){aL.pageX=parseInt(aL.series.xaxis.p2c(aL.datapoint[0])+aF.left+q.left);aL.pageY=parseInt(aL.series.yaxis.p2c(aL.datapoint[1])+aF.top+q.top)}if(O.grid.autoHighlight){for(var aH=0;aH<ab.length;++aH){var aJ=ab[aH];if(aJ.auto==aD&&!(aL&&aJ.series==aL.series&&aJ.point[0]==aL.datapoint[0]&&aJ.point[1]==aL.datapoint[1])){T(aJ.series,aJ.point)}}if(aL){x(aL.series,aL.datapoint,aD)}}aw.trigger(aD,[aK,aL])}function f(){if(!M){M=setTimeout(s,30)}}function s(){M=null;A.save();A.clearRect(0,0,G,I);A.translate(q.left,q.top);var aD,aC;for(aD=0;aD<ab.length;++aD){aC=ab[aD];if(aC.series.bars.show){v(aC.series,aC.point)}else{az(aC.series,aC.point)}}A.restore();ao(al.drawOverlay,[A])}function x(aE,aC,aG){if(typeof aE=="number"){aE=Q[aE]}if(typeof aC=="number"){var aF=aE.datapoints.pointsize;aC=aE.datapoints.points.slice(aF*aC,aF*(aC+1))}var aD=am(aE,aC);if(aD==-1){ab.push({series:aE,point:aC,auto:aG});f()}else{if(!aG){ab[aD].auto=false}}}function T(aE,aC){if(aE==null&&aC==null){ab=[];f()}if(typeof aE=="number"){aE=Q[aE]}if(typeof aC=="number"){aC=aE.data[aC]}var aD=am(aE,aC);if(aD!=-1){ab.splice(aD,1);f()}}function am(aE,aF){for(var aC=0;aC<ab.length;++aC){var aD=ab[aC];if(aD.series==aE&&aD.point[0]==aF[0]&&aD.point[1]==aF[1]){return aC}}return -1}function az(aF,aE){var aD=aE[0],aJ=aE[1],aI=aF.xaxis,aH=aF.yaxis;if(aD<aI.min||aD>aI.max||aJ<aH.min||aJ>aH.max){return}var aG=aF.points.radius+aF.points.lineWidth/2;A.lineWidth=aG;A.strokeStyle=c.color.parse(aF.color).scale("a",0.5).toString();var aC=1.5*aG,aD=aI.p2c(aD),aJ=aH.p2c(aJ);A.beginPath();if(aF.points.symbol=="circle"){A.arc(aD,aJ,aC,0,2*Math.PI,false)}else{aF.points.symbol(A,aD,aJ,aC,false)}A.closePath();A.stroke()}function v(aF,aC){A.lineWidth=aF.bars.lineWidth;A.strokeStyle=c.color.parse(aF.color).scale("a",0.5).toString();var aE=c.color.parse(aF.color).scale("a",0.5).toString();var aD=aF.bars.align=="left"?0:-aF.bars.barWidth/2;E(aC[0],aC[1],aC[2]||0,aD,aD+aF.bars.barWidth,0,function(){return aE},aF.xaxis,aF.yaxis,A,aF.bars.horizontal,aF.bars.lineWidth)}function an(aK,aC,aI,aD){if(typeof aK=="string"){return aK}else{var aJ=H.createLinearGradient(0,aI,0,aC);for(var aF=0,aE=aK.colors.length;aF<aE;++aF){var aG=aK.colors[aF];if(typeof aG!="string"){var aH=c.color.parse(aD);if(aG.brightness!=null){aH=aH.scale("rgb",aG.brightness)}if(aG.opacity!=null){aH.a*=aG.opacity}aG=aH.toString()}aJ.addColorStop(aF/(aE-1),aG)}return aJ}}}c.plot=function(g,e,d){var f=new b(c(g),e,d,c.plot.plugins);return f};c.plot.version="0.7";c.plot.plugins=[];c.plot.formatDate=function(l,f,h){var o=function(d){d=""+d;return d.length==1?"0"+d:d};var e=[];var p=false,j=false;var n=l.getUTCHours();var k=n<12;if(h==null){h=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]}if(f.search(/%p|%P/)!=-1){if(n>12){n=n-12}else{if(n==0){n=12}}}for(var g=0;g<f.length;++g){var m=f.charAt(g);if(p){switch(m){case"h":m=""+n;break;case"H":m=o(n);break;case"M":m=o(l.getUTCMinutes());break;case"S":m=o(l.getUTCSeconds());break;case"d":m=""+l.getUTCDate();break;case"m":m=""+(l.getUTCMonth()+1);break;case"y":m=""+l.getUTCFullYear();break;case"b":m=""+h[l.getUTCMonth()];break;case"p":m=(k)?("am"):("pm");break;case"P":m=(k)?("AM"):("PM");break;case"0":m="";j=true;break}if(m&&j){m=o(m);j=false}e.push(m);if(!j){p=false}}else{if(m=="%"){p=true}else{e.push(m)}}}return e.join("")};function a(e,d){return d*Math.floor(e/d)}})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-plot-0.7.min.js
jquery-plot-0.7.min.js
(function(f){var c={};c.fileapi=f("<input type='file'/>").get(0).files!==undefined;c.formdata=window.FormData!==undefined;var e=!!f.fn.prop;f.fn.attr2=function(){if(!e){return this.attr.apply(this,arguments)}var g=this.prop.apply(this,arguments);if((g&&g.jquery)||typeof g==="string"){return g}return this.attr.apply(this,arguments)};f.fn.ajaxSubmit=function(j){if(!this.length){d("ajaxSubmit: skipping submit process - no element selected");return this}var i,C,m,o=this;if(typeof j=="function"){j={success:j}}else{if(j===undefined){j={}}}i=j.type||this.attr2("method");C=j.url||this.attr2("action");m=(typeof C==="string")?f.trim(C):"";m=m||window.location.href||"";if(m){m=(m.match(/^([^#]+)/)||[])[1]}j=f.extend(true,{url:m,success:f.ajaxSettings.success,type:i||f.ajaxSettings.type,iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank"},j);var u={};this.trigger("form-pre-serialize",[this,j,u]);if(u.veto){d("ajaxSubmit: submit vetoed via form-pre-serialize trigger");return this}if(j.beforeSerialize&&j.beforeSerialize(this,j)===false){d("ajaxSubmit: submit aborted via beforeSerialize callback");return this}var n=j.traditional;if(n===undefined){n=f.ajaxSettings.traditional}var s=[];var E,F=this.formToArray(j.semantic,s);if(j.data){j.extraData=j.data;E=f.param(j.data,n)}if(j.beforeSubmit&&j.beforeSubmit(F,this,j)===false){d("ajaxSubmit: submit aborted via beforeSubmit callback");return this}this.trigger("form-submit-validate",[F,this,j,u]);if(u.veto){d("ajaxSubmit: submit vetoed via form-submit-validate trigger");return this}var y=f.param(F,n);if(E){y=(y?(y+"&"+E):E)}if(j.type.toUpperCase()=="GET"){j.url+=(j.url.indexOf("?")>=0?"&":"?")+y;j.data=null}else{j.data=y}var H=[];if(j.resetForm){H.push(function(){o.resetForm()})}if(j.clearForm){H.push(function(){o.clearForm(j.includeHidden)})}if(!j.dataType&&j.target){var l=j.success||function(){};H.push(function(q){var k=j.replaceTarget?"replaceWith":"html";f(j.target)[k](q).each(l,arguments)})}else{if(j.success){H.push(j.success)}}j.success=function(K,q,L){var J=j.context||this;for(var I=0,k=H.length;I<k;I++){H[I].apply(J,[K,q,L||o,o])}};if(j.error){var z=j.error;j.error=function(J,k,q){var I=j.context||this;z.apply(I,[J,k,q,o])}}if(j.complete){var h=j.complete;j.complete=function(I,k){var q=j.context||this;h.apply(q,[I,k,o])}}var D=f("input[type=file]:enabled",this).filter(function(){return f(this).val()!==""});var p=D.length>0;var B="multipart/form-data";var x=(o.attr("enctype")==B||o.attr("encoding")==B);var w=c.fileapi&&c.formdata;d("fileAPI :"+w);var r=(p||x)&&!w;var v;if(j.iframe!==false&&(j.iframe||r)){if(j.closeKeepAlive){f.get(j.closeKeepAlive,function(){v=G(F)})}else{v=G(F)}}else{if((p||x)&&w){v=t(F)}else{v=f.ajax(j)}}o.removeData("jqxhr").data("jqxhr",v);for(var A=0;A<s.length;A++){s[A]=null}this.trigger("form-submit-notify",[this,j]);return this;function g(K){var L=f.param(K,j.traditional).split("&");var q=L.length;var k=[];var J,I;for(J=0;J<q;J++){L[J]=L[J].replace(/\+/g," ");I=L[J].split("=");k.push([decodeURIComponent(I[0]),decodeURIComponent(I[1])])}return k}function t(q){var k=new FormData();for(var I=0;I<q.length;I++){k.append(q[I].name,q[I].value)}if(j.extraData){var L=g(j.extraData);for(I=0;I<L.length;I++){if(L[I]){k.append(L[I][0],L[I][1])}}}j.data=null;var K=f.extend(true,{},f.ajaxSettings,j,{contentType:false,processData:false,cache:false,type:i||"POST"});if(j.uploadProgress){K.xhr=function(){var M=f.ajaxSettings.xhr();if(M.upload){M.upload.addEventListener("progress",function(Q){var P=0;var N=Q.loaded||Q.position;var O=Q.total;if(Q.lengthComputable){P=Math.ceil(N/O*100)}j.uploadProgress(Q,N,O,P)},false)}return M}}K.data=null;var J=K.beforeSend;K.beforeSend=function(N,M){if(j.formData){M.data=j.formData}else{M.data=k}if(J){J.call(this,N,M)}};return f.ajax(K)}function G(af){var L=o[0],K,ab,V,ad,Y,N,Q,O,P,Z,ac,T;var ai=f.Deferred();ai.abort=function(aj){O.abort(aj)};if(af){for(ab=0;ab<s.length;ab++){K=f(s[ab]);if(e){K.prop("disabled",false)}else{K.removeAttr("disabled")}}}V=f.extend(true,{},f.ajaxSettings,j);V.context=V.context||V;Y="jqFormIO"+(new Date().getTime());if(V.iframeTarget){N=f(V.iframeTarget);Z=N.attr2("name");if(!Z){N.attr2("name",Y)}else{Y=Z}}else{N=f('<iframe name="'+Y+'" src="'+V.iframeSrc+'" />');N.css({position:"absolute",top:"-1000px",left:"-1000px"})}Q=N[0];O={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(aj){var ak=(aj==="timeout"?"timeout":"aborted");d("aborting upload... "+ak);this.aborted=1;try{if(Q.contentWindow.document.execCommand){Q.contentWindow.document.execCommand("Stop")}}catch(al){}N.attr("src",V.iframeSrc);O.error=ak;if(V.error){V.error.call(V.context,O,ak,aj)}if(ad){f.event.trigger("ajaxError",[O,V,ak])}if(V.complete){V.complete.call(V.context,O,ak)}}};ad=V.global;if(ad&&0===f.active++){f.event.trigger("ajaxStart")}if(ad){f.event.trigger("ajaxSend",[O,V])}if(V.beforeSend&&V.beforeSend.call(V.context,O,V)===false){if(V.global){f.active--}ai.reject();return ai}if(O.aborted){ai.reject();return ai}P=L.clk;if(P){Z=P.name;if(Z&&!P.disabled){V.extraData=V.extraData||{};V.extraData[Z]=P.value;if(P.type=="image"){V.extraData[Z+".x"]=L.clk_x;V.extraData[Z+".y"]=L.clk_y}}}var U=1;var R=2;function S(al){var ak=null;try{if(al.contentWindow){ak=al.contentWindow.document}}catch(aj){d("cannot get iframe.contentWindow document: "+aj)}if(ak){return ak}try{ak=al.contentDocument?al.contentDocument:al.document}catch(aj){d("cannot get iframe.contentDocument: "+aj);ak=al.document}return ak}var J=f("meta[name=csrf-token]").attr("content");var I=f("meta[name=csrf-param]").attr("content");if(I&&J){V.extraData=V.extraData||{};V.extraData[I]=J}function aa(){var ar=o.attr2("target"),an=o.attr2("action"),al="multipart/form-data",ao=o.attr("enctype")||o.attr("encoding")||al;L.setAttribute("target",Y);if(!i||/post/i.test(i)){L.setAttribute("method","POST")}if(an!=V.url){L.setAttribute("action",V.url)}if(!V.skipEncodingOverride&&(!i||/post/i.test(i))){o.attr({encoding:"multipart/form-data",enctype:"multipart/form-data"})}if(V.timeout){T=setTimeout(function(){ac=true;X(U)},V.timeout)}function ap(){try{var at=S(Q).readyState;d("state = "+at);if(at&&at.toLowerCase()=="uninitialized"){setTimeout(ap,50)}}catch(au){d("Server abort: ",au," (",au.name,")");X(R);if(T){clearTimeout(T)}T=undefined}}var aq=[];try{if(V.extraData){for(var ak in V.extraData){if(V.extraData.hasOwnProperty(ak)){if(f.isPlainObject(V.extraData[ak])&&V.extraData[ak].hasOwnProperty("name")&&V.extraData[ak].hasOwnProperty("value")){aq.push(f('<input type="hidden" name="'+V.extraData[ak].name+'">').val(V.extraData[ak].value).appendTo(L)[0])}else{aq.push(f('<input type="hidden" name="'+ak+'">').val(V.extraData[ak]).appendTo(L)[0])}}}}if(!V.iframeTarget){N.appendTo("body")}if(Q.attachEvent){Q.attachEvent("onload",X)}else{Q.addEventListener("load",X,false)}setTimeout(ap,15);try{L.submit()}catch(am){var aj=document.createElement("form").submit;aj.apply(L)}}finally{L.setAttribute("action",an);L.setAttribute("enctype",ao);if(ar){L.setAttribute("target",ar)}else{o.removeAttr("target")}f(aq).remove()}}if(V.forceSync){aa()}else{setTimeout(aa,10)}var ag,ah,ae=50,M;function X(ap){if(O.aborted||M){return}ah=S(Q);if(!ah){d("cannot access response document");ap=R}if(ap===U&&O){O.abort("timeout");ai.reject(O,"timeout");return}else{if(ap==R&&O){O.abort("server abort");ai.reject(O,"error","server abort");return}}if(!ah||ah.location.href==V.iframeSrc){if(!ac){return}}if(Q.detachEvent){Q.detachEvent("onload",X)}else{Q.removeEventListener("load",X,false)}var an="success",ar;try{if(ac){throw"timeout"}var am=V.dataType=="xml"||ah.XMLDocument||f.isXMLDoc(ah);d("isXml="+am);if(!am&&window.opera&&(ah.body===null||!ah.body.innerHTML)){if(--ae){d("requeing onLoad callback, DOM not available");setTimeout(X,250);return}}var at=ah.body?ah.body:ah.documentElement;O.responseText=at?at.innerHTML:null;O.responseXML=ah.XMLDocument?ah.XMLDocument:ah;if(am){V.dataType="xml"}O.getResponseHeader=function(aw){var av={"content-type":V.dataType};return av[aw.toLowerCase()]};if(at){O.status=Number(at.getAttribute("status"))||O.status;O.statusText=at.getAttribute("statusText")||O.statusText}var aj=(V.dataType||"").toLowerCase();var aq=/(json|script|text)/.test(aj);if(aq||V.textarea){var ao=ah.getElementsByTagName("textarea")[0];if(ao){O.responseText=ao.value;O.status=Number(ao.getAttribute("status"))||O.status;O.statusText=ao.getAttribute("statusText")||O.statusText}else{if(aq){var ak=ah.getElementsByTagName("pre")[0];var au=ah.getElementsByTagName("body")[0];if(ak){O.responseText=ak.textContent?ak.textContent:ak.innerText}else{if(au){O.responseText=au.textContent?au.textContent:au.innerText}}}}}else{if(aj=="xml"&&!O.responseXML&&O.responseText){O.responseXML=W(O.responseText)}}try{ag=k(O,aj,V)}catch(al){an="parsererror";O.error=ar=(al||an)}}catch(al){d("error caught: ",al);an="error";O.error=ar=(al||an)}if(O.aborted){d("upload aborted");an=null}if(O.status){an=(O.status>=200&&O.status<300||O.status===304)?"success":"error"}if(an==="success"){if(V.success){V.success.call(V.context,ag,"success",O)}ai.resolve(O.responseText,"success",O);if(ad){f.event.trigger("ajaxSuccess",[O,V])}}else{if(an){if(ar===undefined){ar=O.statusText}if(V.error){V.error.call(V.context,O,an,ar)}ai.reject(O,"error",ar);if(ad){f.event.trigger("ajaxError",[O,V,ar])}}}if(ad){f.event.trigger("ajaxComplete",[O,V])}if(ad&&!--f.active){f.event.trigger("ajaxStop")}if(V.complete){V.complete.call(V.context,O,an)}M=true;if(V.timeout){clearTimeout(T)}setTimeout(function(){if(!V.iframeTarget){N.remove()}else{N.attr("src",V.iframeSrc)}O.responseXML=null},100)}var W=f.parseXML||function(aj,ak){if(window.ActiveXObject){ak=new ActiveXObject("Microsoft.XMLDOM");ak.async="false";ak.loadXML(aj)}else{ak=(new DOMParser()).parseFromString(aj,"text/xml")}return(ak&&ak.documentElement&&ak.documentElement.nodeName!="parsererror")?ak:null};var q=f.parseJSON||function(aj){return window["eval"]("("+aj+")")};var k=function(ao,am,al){var ak=ao.getResponseHeader("content-type")||"",aj=am==="xml"||!am&&ak.indexOf("xml")>=0,an=aj?ao.responseXML:ao.responseText;if(aj&&an.documentElement.nodeName==="parsererror"){if(f.error){f.error("parsererror")}}if(al&&al.dataFilter){an=al.dataFilter(an,am)}if(typeof an==="string"){if(am==="json"||!am&&ak.indexOf("json")>=0){an=q(an)}else{if(am==="script"||!am&&ak.indexOf("javascript")>=0){f.globalEval(an)}}}return an};return ai}};f.fn.ajaxForm=function(g){g=g||{};g.delegation=g.delegation&&f.isFunction(f.fn.on);if(!g.delegation&&this.length===0){var h={s:this.selector,c:this.context};if(!f.isReady&&h.s){d("DOM not ready, queuing ajaxForm");f(function(){f(h.s,h.c).ajaxForm(g)});return this}d("terminating; zero elements found by selector"+(f.isReady?"":" (DOM not ready)"));return this}if(g.delegation){f(document).off("submit.form-plugin",this.selector,b).off("click.form-plugin",this.selector,a).on("submit.form-plugin",this.selector,g,b).on("click.form-plugin",this.selector,g,a);return this}return this.ajaxFormUnbind().bind("submit.form-plugin",g,b).bind("click.form-plugin",g,a)};function b(h){var g=h.data;if(!h.isDefaultPrevented()){h.preventDefault();f(h.target).ajaxSubmit(g)}}function a(k){var j=k.target;var h=f(j);if(!(h.is("[type=submit],[type=image]"))){var g=h.closest("[type=submit]");if(g.length===0){return}j=g[0]}var i=this;i.clk=j;if(j.type=="image"){if(k.offsetX!==undefined){i.clk_x=k.offsetX;i.clk_y=k.offsetY}else{if(typeof f.fn.offset=="function"){var l=h.offset();i.clk_x=k.pageX-l.left;i.clk_y=k.pageY-l.top}else{i.clk_x=k.pageX-j.offsetLeft;i.clk_y=k.pageY-j.offsetTop}}}setTimeout(function(){i.clk=i.clk_x=i.clk_y=null},100)}f.fn.ajaxFormUnbind=function(){return this.unbind("submit.form-plugin click.form-plugin")};f.fn.formToArray=function(x,g){var w=[];if(this.length===0){return w}var l=this[0];var z=this.attr("id");var q=x?l.getElementsByTagName("*"):l.elements;var A;if(q&&!/MSIE 8/.test(navigator.userAgent)){q=f(q).get()}if(z){A=f(":input[form="+z+"]").get();if(A.length){q=(q||[]).concat(A)}}if(!q||!q.length){return w}var r,p,o,y,m,t,k;for(r=0,t=q.length;r<t;r++){m=q[r];o=m.name;if(!o||m.disabled){continue}if(x&&l.clk&&m.type=="image"){if(l.clk==m){w.push({name:o,value:f(m).val(),type:m.type});w.push({name:o+".x",value:l.clk_x},{name:o+".y",value:l.clk_y})}continue}y=f.fieldValue(m,true);if(y&&y.constructor==Array){if(g){g.push(m)}for(p=0,k=y.length;p<k;p++){w.push({name:o,value:y[p]})}}else{if(c.fileapi&&m.type=="file"){if(g){g.push(m)}var h=m.files;if(h.length){for(p=0;p<h.length;p++){w.push({name:o,value:h[p],type:m.type})}}else{w.push({name:o,value:"",type:m.type})}}else{if(y!==null&&typeof y!="undefined"){if(g){g.push(m)}w.push({name:o,value:y,type:m.type,required:m.required})}}}}if(!x&&l.clk){var s=f(l.clk),u=s[0];o=u.name;if(o&&!u.disabled&&u.type=="image"){w.push({name:o,value:s.val()});w.push({name:o+".x",value:l.clk_x},{name:o+".y",value:l.clk_y})}}return w};f.fn.formSerialize=function(g){return f.param(this.formToArray(g))};f.fn.fieldSerialize=function(h){var g=[];this.each(function(){var m=this.name;if(!m){return}var k=f.fieldValue(this,h);if(k&&k.constructor==Array){for(var l=0,j=k.length;l<j;l++){g.push({name:m,value:k[l]})}}else{if(k!==null&&typeof k!="undefined"){g.push({name:this.name,value:k})}}});return f.param(g)};f.fn.fieldValue=function(m){for(var l=[],j=0,g=this.length;j<g;j++){var k=this[j];var h=f.fieldValue(k,m);if(h===null||typeof h=="undefined"||(h.constructor==Array&&!h.length)){continue}if(h.constructor==Array){f.merge(l,h)}else{l.push(h)}}return l};f.fieldValue=function(g,o){var j=g.name,u=g.type,w=g.tagName.toLowerCase();if(o===undefined){o=true}if(o&&(!j||g.disabled||u=="reset"||u=="button"||(u=="checkbox"||u=="radio")&&!g.checked||(u=="submit"||u=="image")&&g.form&&g.form.clk!=g||w=="select"&&g.selectedIndex==-1)){return null}if(w=="select"){var p=g.selectedIndex;if(p<0){return null}var r=[],h=g.options;var l=(u=="select-one");var q=(l?p+1:h.length);for(var k=(l?p:0);k<q;k++){var m=h[k];if(m.selected){var s=m.value;if(!s){s=(m.attributes&&m.attributes.value&&!(m.attributes.value.specified))?m.text:m.value}if(l){return s}r.push(s)}}return r}return f(g).val()};f.fn.clearForm=function(g){return this.each(function(){f("input,select,textarea",this).clearFields(g)})};f.fn.clearFields=f.fn.clearInputs=function(g){var h=/^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;return this.each(function(){var j=this.type,i=this.tagName.toLowerCase();if(h.test(j)||i=="textarea"){this.value=""}else{if(j=="checkbox"||j=="radio"){this.checked=false}else{if(i=="select"){this.selectedIndex=-1}else{if(j=="file"){if(/MSIE/.test(navigator.userAgent)){f(this).replaceWith(f(this).clone(true))}else{f(this).val("")}}else{if(g){if((g===true&&/hidden/.test(j))||(typeof g=="string"&&f(this).is(g))){this.value=""}}}}}}})};f.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=="function"||(typeof this.reset=="object"&&!this.reset.nodeType)){this.reset()}})};f.fn.enable=function(g){if(g===undefined){g=true}return this.each(function(){this.disabled=!g})};f.fn.selected=function(g){if(g===undefined){g=true}return this.each(function(){var h=this.type;if(h=="checkbox"||h=="radio"){this.checked=g}else{if(this.tagName.toLowerCase()=="option"){var i=f(this).parent("select");if(g&&i[0]&&i[0].type=="select-one"){i.find("option").selected(false)}this.selected=g}}})};f.fn.ajaxSubmit.debug=false;function d(){if(!f.fn.ajaxSubmit.debug){return}var g="[jquery.form] "+Array.prototype.join.call(arguments,"");if(window.console&&window.console.log){window.console.log(g)}else{if(window.opera&&window.opera.postError){window.opera.postError(g)}}}})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-form-3.49.min.js
jquery-form-3.49.min.js
(function(a){a.extend(a.fn,{validate:function(b){if(!this.length){if(b&&b.debug&&window.console){console.warn("Nothing selected, can't validate, returning nothing.")}return}var c=a.data(this[0],"validator");if(c){return c}this.attr("novalidate","novalidate");c=new a.validator(b,this[0]);a.data(this[0],"validator",c);if(c.settings.onsubmit){this.validateDelegate(":submit","click",function(d){if(c.settings.submitHandler){c.submitButton=d.target}if(a(d.target).hasClass("cancel")){c.cancelSubmit=true}if(a(d.target).attr("formnovalidate")!==undefined){c.cancelSubmit=true}});this.submit(function(d){if(c.settings.debug){d.preventDefault()}function e(){var f;if(c.settings.submitHandler){if(c.submitButton){f=a("<input type='hidden'/>").attr("name",c.submitButton.name).val(a(c.submitButton).val()).appendTo(c.currentForm)}c.settings.submitHandler.call(c,c.currentForm,d);if(c.submitButton){f.remove()}return false}return true}if(c.cancelSubmit){c.cancelSubmit=false;return e()}if(c.form()){if(c.pendingRequest){c.formSubmitted=true;return false}return e()}else{c.focusInvalid();return false}})}return c},valid:function(){if(a(this[0]).is("form")){return this.validate().form()}else{var c=true;var b=a(this[0].form).validate();this.each(function(){c=c&&b.element(this)});return c}},removeAttrs:function(d){var b={},c=this;a.each(d.split(/\s/),function(e,f){b[f]=c.attr(f);c.removeAttr(f)});return b},rules:function(e,b){var g=this[0];if(e){var d=a.data(g.form,"validator").settings;var i=d.rules;var j=a.validator.staticRules(g);switch(e){case"add":a.extend(j,a.validator.normalizeRule(b));delete j.messages;i[g.name]=j;if(b.messages){d.messages[g.name]=a.extend(d.messages[g.name],b.messages)}break;case"remove":if(!b){delete i[g.name];return j}var h={};a.each(b.split(/\s/),function(k,l){h[l]=j[l];delete j[l]});return h}}var f=a.validator.normalizeRules(a.extend({},a.validator.classRules(g),a.validator.attributeRules(g),a.validator.dataRules(g),a.validator.staticRules(g)),g);if(f.required){var c=f.required;delete f.required;f=a.extend({required:c},f)}return f}});a.extend(a.expr[":"],{blank:function(b){return !a.trim(""+a(b).val())},filled:function(b){return !!a.trim(""+a(b).val())},unchecked:function(b){return !a(b).prop("checked")}});a.validator=function(b,c){this.settings=a.extend(true,{},a.validator.defaults,b);this.currentForm=c;this.init()};a.validator.format=function(b,c){if(arguments.length===1){return function(){var d=a.makeArray(arguments);d.unshift(b);return a.validator.format.apply(this,d)}}if(arguments.length>2&&c.constructor!==Array){c=a.makeArray(arguments).slice(1)}if(c.constructor!==Array){c=[c]}a.each(c,function(d,e){b=b.replace(new RegExp("\\{"+d+"\\}","g"),function(){return e})});return b};a.extend(a.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:a([]),errorLabelContainer:a([]),onsubmit:true,ignore:":hidden",ignoreTitle:false,onfocusin:function(b,c){this.lastActive=b;if(this.settings.focusCleanup&&!this.blockFocusCleanup){if(this.settings.unhighlight){this.settings.unhighlight.call(this,b,this.settings.errorClass,this.settings.validClass)}this.addWrapper(this.errorsFor(b)).hide()}},onfocusout:function(b,c){if(!this.checkable(b)&&(b.name in this.submitted||!this.optional(b))){this.element(b)}},onkeyup:function(b,c){if(c.which===9&&this.elementValue(b)===""){return}else{if(b.name in this.submitted||b===this.lastElement){this.element(b)}}},onclick:function(b,c){if(b.name in this.submitted){this.element(b)}else{if(b.parentNode.name in this.submitted){this.element(b.parentNode)}}},highlight:function(d,b,c){if(d.type==="radio"){this.findByName(d.name).addClass(b).removeClass(c)}else{a(d).addClass(b).removeClass(c)}},unhighlight:function(d,b,c){if(d.type==="radio"){this.findByName(d.name).removeClass(b).addClass(c)}else{a(d).removeClass(b).addClass(c)}}},setDefaults:function(b){a.extend(a.validator.defaults,b)},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.",maxlength:a.validator.format("Please enter no more than {0} characters."),minlength:a.validator.format("Please enter at least {0} characters."),rangelength:a.validator.format("Please enter a value between {0} and {1} characters long."),range:a.validator.format("Please enter a value between {0} and {1}."),max:a.validator.format("Please enter a value less than or equal to {0}."),min:a.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){this.labelContainer=a(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||a(this.currentForm);this.containers=a(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var b=(this.groups={});a.each(this.settings.groups,function(e,f){if(typeof f==="string"){f=f.split(/\s/)}a.each(f,function(h,g){b[g]=e})});var d=this.settings.rules;a.each(d,function(e,f){d[e]=a.validator.normalizeRule(f)});function c(g){var f=a.data(this[0].form,"validator"),e="on"+g.type.replace(/^validate/,"");if(f.settings[e]){f.settings[e].call(f,this[0],g)}}a(this.currentForm).validateDelegate(":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'] ,[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'] ","focusin focusout keyup",c).validateDelegate("[type='radio'], [type='checkbox'], select, option","click",c);if(this.settings.invalidHandler){a(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)}},form:function(){this.checkForm();a.extend(this.submitted,this.errorMap);this.invalid=a.extend({},this.errorMap);if(!this.valid()){a(this.currentForm).triggerHandler("invalid-form",[this])}this.showErrors();return this.valid()},checkForm:function(){this.prepareForm();for(var b=0,c=(this.currentElements=this.elements());c[b];b++){this.check(c[b])}return this.valid()},element:function(c){c=this.validationTargetFor(this.clean(c));this.lastElement=c;this.prepareElement(c);this.currentElements=a(c);var b=this.check(c)!==false;if(b){delete this.invalid[c.name]}else{this.invalid[c.name]=true}if(!this.numberOfInvalids()){this.toHide=this.toHide.add(this.containers)}this.showErrors();return b},showErrors:function(c){if(c){a.extend(this.errorMap,c);this.errorList=[];for(var b in c){this.errorList.push({message:c[b],element:this.findByName(b)[0]})}this.successList=a.grep(this.successList,function(d){return !(d.name in c)})}if(this.settings.showErrors){this.settings.showErrors.call(this,this.errorMap,this.errorList)}else{this.defaultShowErrors()}},resetForm:function(){if(a.fn.resetForm){a(this.currentForm).resetForm()}this.submitted={};this.lastElement=null;this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass).removeData("previousValue")},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(d){var c=0;for(var b in d){c++}return c},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{a(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(b){}}},findLastActive:function(){var b=this.lastActive;return b&&a.grep(this.errorList,function(c){return c.element.name===b.name}).length===1&&b},elements:function(){var c=this,b={};return a(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){if(!this.name&&c.settings.debug&&window.console){console.error("%o has no name assigned",this)}if(this.name in b||!c.objectLength(a(this).rules())){return false}b[this.name]=true;return true})},clean:function(b){return a(b)[0]},errors:function(){var b=this.settings.errorClass.replace(" ",".");return a(this.settings.errorElement+"."+b,this.errorContext)},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=a([]);this.toHide=a([]);this.currentElements=a([])},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers)},prepareElement:function(b){this.reset();this.toHide=this.errorsFor(b)},elementValue:function(b){var c=a(b).attr("type"),d=a(b).val();if(c==="radio"||c==="checkbox"){return a("input[name='"+a(b).attr("name")+"']:checked").val()}if(typeof d==="string"){return d.replace(/\r/g,"")}return d},check:function(c){c=this.validationTargetFor(this.clean(c));var i=a(c).rules();var d=false;var h=this.elementValue(c);var b;for(var j in i){var g={method:j,parameters:i[j]};try{b=a.validator.methods[j].call(this,h,c,g.parameters);if(b==="dependency-mismatch"){d=true;continue}d=false;if(b==="pending"){this.toHide=this.toHide.not(this.errorsFor(c));return}if(!b){this.formatAndAdd(c,g);return false}}catch(f){if(this.settings.debug&&window.console){console.log("Exception occurred when checking element "+c.id+", check the '"+g.method+"' method.",f)}throw f}}if(d){return}if(this.objectLength(i)){this.successList.push(c)}return true},customDataMessage:function(b,c){return a(b).data("msg-"+c.toLowerCase())||(b.attributes&&a(b).attr("data-msg-"+c.toLowerCase()))},customMessage:function(c,d){var b=this.settings.messages[c];return b&&(b.constructor===String?b:b[d])},findDefined:function(){for(var b=0;b<arguments.length;b++){if(arguments[b]!==undefined){return arguments[b]}}return undefined},defaultMessage:function(b,c){return this.findDefined(this.customMessage(b.name,c),this.customDataMessage(b,c),!this.settings.ignoreTitle&&b.title||undefined,a.validator.messages[c],"<strong>Warning: No message defined for "+b.name+"</strong>")},formatAndAdd:function(c,e){var d=this.defaultMessage(c,e.method),b=/\$?\{(\d+)\}/g;if(typeof d==="function"){d=d.call(this,e.parameters,c)}else{if(b.test(d)){d=a.validator.format(d.replace(b,"{$1}"),e.parameters)}}this.errorList.push({message:d,element:c});this.errorMap[c.name]=d;this.submitted[c.name]=d},addWrapper:function(b){if(this.settings.wrapper){b=b.add(b.parent(this.settings.wrapper))}return b},defaultShowErrors:function(){var c,d;for(c=0;this.errorList[c];c++){var b=this.errorList[c];if(this.settings.highlight){this.settings.highlight.call(this,b.element,this.settings.errorClass,this.settings.validClass)}this.showLabel(b.element,b.message)}if(this.errorList.length){this.toShow=this.toShow.add(this.containers)}if(this.settings.success){for(c=0;this.successList[c];c++){this.showLabel(this.successList[c])}}if(this.settings.unhighlight){for(c=0,d=this.validElements();d[c];c++){this.settings.unhighlight.call(this,d[c],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 a(this.errorList).map(function(){return this.element})},showLabel:function(c,d){var b=this.errorsFor(c);if(b.length){b.removeClass(this.settings.validClass).addClass(this.settings.errorClass);b.html(d)}else{b=a("<"+this.settings.errorElement+">").attr("for",this.idOrName(c)).addClass(this.settings.errorClass).html(d||"");if(this.settings.wrapper){b=b.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()}if(!this.labelContainer.append(b).length){if(this.settings.errorPlacement){this.settings.errorPlacement(b,a(c))}else{b.insertAfter(c)}}}if(!d&&this.settings.success){b.text("");if(typeof this.settings.success==="string"){b.addClass(this.settings.success)}else{this.settings.success(b,c)}}this.toShow=this.toShow.add(b)},errorsFor:function(c){var b=this.idOrName(c);return this.errors().filter(function(){return a(this).attr("for")===b})},idOrName:function(b){return this.groups[b.name]||(this.checkable(b)?b.name:b.id||b.name)},validationTargetFor:function(b){if(this.checkable(b)){b=this.findByName(b.name).not(this.settings.ignore)[0]}return b},checkable:function(b){return(/radio|checkbox/i).test(b.type)},findByName:function(b){return a(this.currentForm).find("[name='"+b+"']")},getLength:function(c,b){switch(b.nodeName.toLowerCase()){case"select":return a("option:selected",b).length;case"input":if(this.checkable(b)){return this.findByName(b.name).filter(":checked").length}}return c.length},depend:function(c,b){return this.dependTypes[typeof c]?this.dependTypes[typeof c](c,b):true},dependTypes:{"boolean":function(c,b){return c},string:function(c,b){return !!a(c,b.form).length},"function":function(c,b){return c(b)}},optional:function(b){var c=this.elementValue(b);return !a.validator.methods.required.call(this,c,b)&&"dependency-mismatch"},startRequest:function(b){if(!this.pending[b.name]){this.pendingRequest++;this.pending[b.name]=true}},stopRequest:function(b,c){this.pendingRequest--;if(this.pendingRequest<0){this.pendingRequest=0}delete this.pending[b.name];if(c&&this.pendingRequest===0&&this.formSubmitted&&this.form()){a(this.currentForm).submit();this.formSubmitted=false}else{if(!c&&this.pendingRequest===0&&this.formSubmitted){a(this.currentForm).triggerHandler("invalid-form",[this]);this.formSubmitted=false}}},previousValue:function(b){return a.data(b,"previousValue")||a.data(b,"previousValue",{old:null,valid:true,message:this.defaultMessage(b,"remote")})}},classRuleSettings:{required:{required:true},email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},number:{number:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(b,c){if(b.constructor===String){this.classRuleSettings[b]=c}else{a.extend(this.classRuleSettings,b)}},classRules:function(c){var d={};var b=a(c).attr("class");if(b){a.each(b.split(" "),function(){if(this in a.validator.classRuleSettings){a.extend(d,a.validator.classRuleSettings[this])}})}return d},attributeRules:function(c){var f={};var b=a(c);var d=b[0].getAttribute("type");for(var g in a.validator.methods){var e;if(g==="required"){e=b.get(0).getAttribute(g);if(e===""){e=true}e=!!e}else{e=b.attr(g)}if(/min|max/.test(g)&&(d===null||/number|range|text/.test(d))){e=Number(e)}if(e){f[g]=e}else{if(d===g&&d!=="range"){f[g]=true}}}if(f.maxlength&&/-1|2147483647|524288/.test(f.maxlength)){delete f.maxlength}return f},dataRules:function(c){var f,d,e={},b=a(c);for(f in a.validator.methods){d=b.data("rule-"+f.toLowerCase());if(d!==undefined){e[f]=d}}return e},staticRules:function(c){var d={};var b=a.data(c.form,"validator");if(b.settings.rules){d=a.validator.normalizeRule(b.settings.rules[c.name])||{}}return d},normalizeRules:function(c,b){a.each(c,function(f,e){if(e===false){delete c[f];return}if(e.param||e.depends){var d=true;switch(typeof e.depends){case"string":d=!!a(e.depends,b.form).length;break;case"function":d=e.depends.call(b,b);break}if(d){c[f]=e.param!==undefined?e.param:true}else{delete c[f]}}});a.each(c,function(d,e){c[d]=a.isFunction(e)?e(b):e});a.each(["minlength","maxlength"],function(){if(c[this]){c[this]=Number(c[this])}});a.each(["rangelength","range"],function(){var d;if(c[this]){if(a.isArray(c[this])){c[this]=[Number(c[this][0]),Number(c[this][1])]}else{if(typeof c[this]==="string"){d=c[this].split(/[\s,]+/);c[this]=[Number(d[0]),Number(d[1])]}}}});if(a.validator.autoCreateRanges){if(c.min&&c.max){c.range=[c.min,c.max];delete c.min;delete c.max}if(c.minlength&&c.maxlength){c.rangelength=[c.minlength,c.maxlength];delete c.minlength;delete c.maxlength}}return c},normalizeRule:function(c){if(typeof c==="string"){var b={};a.each(c.split(/\s/),function(){b[this]=true});c=b}return c},addMethod:function(b,d,c){a.validator.methods[b]=d;a.validator.messages[b]=c!==undefined?c:a.validator.messages[b];if(d.length<3){a.validator.addClassRules(b,a.validator.normalizeRule(b))}},methods:{required:function(c,b,e){if(!this.depend(e,b)){return"dependency-mismatch"}if(b.nodeName.toLowerCase()==="select"){var d=a(b).val();return d&&d.length>0}if(this.checkable(b)){return this.getLength(c,b)>0}return a.trim(c).length>0},email:function(c,b){return this.optional(b)||/^((([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(c)},url:function(c,b){return this.optional(b)||/^(https?|s?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(c)},date:function(c,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(c).toString())},dateISO:function(c,b){return this.optional(b)||/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(c)},number:function(c,b){return this.optional(b)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(c)},digits:function(c,b){return this.optional(b)||/^\d+$/.test(c)},creditcard:function(f,c){if(this.optional(c)){return"dependency-mismatch"}if(/[^0-9 \-]+/.test(f)){return false}var g=0,e=0,b=false;f=f.replace(/\D/g,"");for(var h=f.length-1;h>=0;h--){var d=f.charAt(h);e=parseInt(d,10);if(b){if((e*=2)>9){e-=9}}g+=e;b=!b}return(g%10)===0},minlength:function(d,b,e){var c=a.isArray(d)?d.length:this.getLength(a.trim(d),b);return this.optional(b)||c>=e},maxlength:function(d,b,e){var c=a.isArray(d)?d.length:this.getLength(a.trim(d),b);return this.optional(b)||c<=e},rangelength:function(d,b,e){var c=a.isArray(d)?d.length:this.getLength(a.trim(d),b);return this.optional(b)||(c>=e[0]&&c<=e[1])},min:function(c,b,d){return this.optional(b)||c>=d},max:function(c,b,d){return this.optional(b)||c<=d},range:function(c,b,d){return this.optional(b)||(c>=d[0]&&c<=d[1])},equalTo:function(c,b,e){var d=a(e);if(this.settings.onfocusout){d.unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){a(b).valid()})}return c===d.val()},remote:function(f,c,g){if(this.optional(c)){return"dependency-mismatch"}var d=this.previousValue(c);if(!this.settings.messages[c.name]){this.settings.messages[c.name]={}}d.originalMessage=this.settings.messages[c.name].remote;this.settings.messages[c.name].remote=d.message;g=typeof g==="string"&&{url:g}||g;if(d.old===f){return d.valid}d.old=f;var b=this;this.startRequest(c);var e={};e[c.name]=f;a.ajax(a.extend(true,{url:g,mode:"abort",port:"validate"+c.name,dataType:"json",data:e,success:function(i){b.settings.messages[c.name].remote=d.originalMessage;var k=i===true||i==="true";if(k){var h=b.formSubmitted;b.prepareElement(c);b.formSubmitted=h;b.successList.push(c);delete b.invalid[c.name];b.showErrors()}else{var l={};var j=i||b.defaultMessage(c,"remote");l[c.name]=d.message=a.isFunction(j)?j(f):j;b.invalid[c.name]=true;b.showErrors(l)}d.valid=k;b.stopRequest(c,k)}},g));return"pending"}}});a.format=a.validator.format}(jQuery));(function(c){var a={};if(c.ajaxPrefilter){c.ajaxPrefilter(function(f,e,g){var d=f.port;if(f.mode==="abort"){if(a[d]){a[d].abort()}a[d]=g}})}else{var b=c.ajax;c.ajax=function(e){var f=("mode" in e?e:c.ajaxSettings).mode,d=("port" in e?e:c.ajaxSettings).port;if(f==="abort"){if(a[d]){a[d].abort()}a[d]=b.apply(this,arguments);return a[d]}return b.apply(this,arguments)}}}(jQuery));(function(a){a.extend(a.fn,{validateDelegate:function(d,c,b){return this.bind(c,function(e){var f=a(e.target);if(f.is(d)){return b.apply(f,arguments)}})}})}(jQuery));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-validate-1.11.1.min.js
jquery-validate-1.11.1.min.js
(function(c){function a(d){if(d.attr("title")||typeof(d.attr("original-title"))!="string"){d.attr("original-title",d.attr("title")||"").removeAttr("title")}}function b(e,d){this.$element=c(e);this.options=d;this.enabled=true;a(this.$element)}b.prototype={show:function(){var h=this.getTitle();if(h&&this.enabled){var g=this.tip();g.find(".tipsy-inner")[this.options.html?"html":"text"](h);g[0].className="tipsy";g.remove().css({top:0,left:0,visibility:"hidden",display:"block"}).appendTo(document.body);var k=c.extend({},this.$element.offset(),{width:this.$element[0].offsetWidth,height:this.$element[0].offsetHeight});var d=g[0].offsetWidth,j=g[0].offsetHeight;var i=(typeof this.options.gravity=="function")?this.options.gravity.call(this.$element[0]):this.options.gravity;var f=(typeof this.options.offset=="function")?this.options.offset.call(this.$element[0]):this.options.offset;var e;switch(i.charAt(0)){case"n":e={top:k.top+k.height+f,left:k.left+k.width/2-d/2};break;case"s":e={top:k.top-j-f,left:k.left+k.width/2-d/2};break;case"e":e={top:k.top+k.height/2-j/2,left:k.left-d-f};break;case"w":e={top:k.top+k.height/2-j/2,left:k.left+k.width+f};break}if(i.length==2){if(i.charAt(1)=="w"){e.left=k.width<15?k.left+(k.width/2)-14:k.left-5}else{e.left=k.width<15?k.left+k.width-d+(k.width/2)+4:k.left+k.width-d+5}}e.left=Math.min(e.left,c("html").width()-d-10);g.css(e).addClass("tipsy-"+i);if(this.options.fade){g.stop().css({opacity:0,display:"block",visibility:"visible"}).animate({opacity:this.options.opacity})}else{g.css({visibility:"visible",opacity:this.options.opacity})}}},hide:function(){if(this.options.fade){this.tip().stop().fadeOut(function(){c(this).remove()})}else{this.tip().remove()}},getTitle:function(){var f,d=this.$element,e=this.options;a(d);var f,e=this.options;if(typeof e.title=="string"){f=d.attr(e.title=="title"?"original-title":e.title)}else{if(typeof e.title=="function"){f=e.title.call(d[0])}}f=(""+f).replace(/(^\s*|\s*$)/,"");return f||e.fallback},tip:function(){if(!this.$tip){this.$tip=c('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"/></div>')}return this.$tip},validate:function(){if(!this.$element[0].parentNode){this.hide();this.$element=null;this.options=null}},enable:function(){this.enabled=true},disable:function(){this.enabled=false},toggleEnabled:function(){this.enabled=!this.enabled}};c.fn.tipsy=function(h){if(h===true){return this.data("tipsy")}else{if(typeof h=="string"){return this.data("tipsy")[h]()}}h=c.extend({},c.fn.tipsy.defaults,h);function g(k){var l=c.data(k,"tipsy");if(!l){l=new b(k,c.fn.tipsy.elementOptions(k,h));c.data(k,"tipsy",l)}return l}function j(){var k=g(this);k.hoverState="in";if(h.delayIn==0){k.show()}else{setTimeout(function(){if(k.hoverState=="in"){k.show()}},h.delayIn)}}function f(){var k=g(this);k.hoverState="out";if(h.delayOut==0){k.hide()}else{setTimeout(function(){if(k.hoverState=="out"){k.hide()}},h.delayOut)}}if(!h.live){this.each(function(){g(this)})}if(h.trigger!="manual"){var d=h.live?"live":"bind",i=h.trigger=="hover"?"mouseenter":"focus",e=h.trigger=="hover"?"mouseleave":"blur";this[d](i,j)[d](e,f)}return this};c.fn.tipsy.defaults={delayIn:0,delayOut:0,fade:false,fallback:"",gravity:"n",html:false,live:false,offset:0,opacity:0.8,title:"title",trigger:"hover"};c.fn.tipsy.elementOptions=function(e,d){return c.metadata?c.extend({},d,c(e).metadata()):d};c.fn.tipsy.autoNS=function(){return c(this).offset().top>(c(document).scrollTop()+c(window).height()/2)?"s":"n"};c.fn.tipsy.autoWE=function(){return c(this).offset().left>(c(document).scrollLeft()+c(window).width()/2)?"e":"w"}})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-tipsy.min.js
jquery-tipsy.min.js
(function ($) { "use strict"; $.fn.rowGrouping = function (options) { function _fnOnGrouped() { } function _fnOnGroupCreated(oGroup, sGroup, iLevel) { ///<summary> ///Function called when a new grouping row is created(it should be overriden in properties) ///</summary> } function _fnOnGroupCompleted(oGroup, sGroup, iLevel) { ///<summary> ///Function called when a new grouping row is created(it should be overriden in properties) ///</summary> } function _getMonthName(iMonth) { var asMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; return asMonths[iMonth - 1]; } var defaults = { iGroupingColumnIndex: 0, sGroupingColumnSortDirection: "", iGroupingOrderByColumnIndex: -1, sGroupingClass: "group", sGroupItemClass: "group-item", bHideGroupingColumn: true, bHideGroupingOrderByColumn: true, sGroupBy: "name", sGroupLabelPrefix: "", fnGroupLabelFormat: function (label) { return label; }, bExpandableGrouping: false, bExpandSingleGroup: false, iExpandGroupOffset: 100, asExpandedGroups: null, sDateFormat: "dd/MM/yyyy", sEmptyGroupLabel: "-", bSetGroupingClassOnTR: false, iGroupingColumnIndex2: -1, sGroupingColumnSortDirection2: "", iGroupingOrderByColumnIndex2: -1, sGroupingClass2: "subgroup", sGroupItemClass2: "subgroup-item", bHideGroupingColumn2: true, bHideGroupingOrderByColumn2: true, sGroupBy2: "name", sGroupLabelPrefix2: "", fnGroupLabelFormat2: function (label) { return label; }, bExpandableGrouping2: false, fnOnGrouped: _fnOnGrouped, fnOnGroupCreated: _fnOnGroupCreated, fnOnGroupCompleted: _fnOnGroupCompleted, oHideEffect: null, // { method: "hide", duration: "fast", easing: "linear" }, oShowEffect: null,//{ method: "show", duration: "slow", easing: "linear" } bUseFilteringForGrouping: false // This is still work in progress option }; return this.each(function (index, elem) { var oTable = $(elem).dataTable(); var aoGroups = new Array(); $(this).dataTableExt.aoGroups = aoGroups; function fnCreateGroupRow(sGroupCleaned, sGroup, iColspan) { var nGroup = document.createElement('tr'); var nCell = document.createElement('td'); nGroup.id = "group-id-" + oTable.attr("id") + "_" + sGroupCleaned; var oGroup = { id: nGroup.id, key: sGroupCleaned, text: sGroup, level: 0, groupItemClass: ".group-item-" + sGroupCleaned, dataGroup: sGroupCleaned, aoSubgroups: new Array() }; if (properties.bSetGroupingClassOnTR) { nGroup.className = properties.sGroupingClass + " " + sGroupCleaned; } else { nCell.className = properties.sGroupingClass + " " + sGroupCleaned; } nCell.colSpan = iColspan; nCell.innerHTML = properties.sGroupLabelPrefix + properties.fnGroupLabelFormat(sGroup == "" ? properties.sEmptyGroupLabel : sGroup, oGroup); if (properties.bExpandableGrouping) { if (!_fnIsGroupCollapsed(sGroupCleaned)) { nCell.className += " expanded-group"; oGroup.state = "expanded"; } else { nCell.className += " collapsed-group"; oGroup.state = "collapsed"; } nCell.className += " group-item-expander"; $(nCell).attr('data-group', oGroup.dataGroup); //Fix provided by mssskhalsa (Issue 5) $(nCell).attr("data-group-level", oGroup.level); $(nCell).click(_fnOnGroupClick); } nGroup.appendChild(nCell); aoGroups[sGroupCleaned] = oGroup; oGroup.nGroup = nGroup; properties.fnOnGroupCreated(oGroup, sGroupCleaned, 1); return oGroup; } function _fnCreateGroup2Row(sGroup2, sGroupLabel, iColspan, oParentGroup) { var nGroup2 = document.createElement('tr'); nGroup2.id = oParentGroup.id + "_" + sGroup2; var nCell2 = document.createElement('td'); var dataGroup = oParentGroup.dataGroup + '_' + sGroup2; var oGroup = { id: nGroup2.id, key: sGroup2, text: sGroupLabel, level: oParentGroup.level + 1, groupItemClass: ".group-item-" + dataGroup, dataGroup: dataGroup, aoSubgroups: new Array() }; if (properties.bSetGroupingClassOnTR) { nGroup2.className = properties.sGroupingClass2 + " " + sGroup2; } else { nCell2.className = properties.sGroupingClass2 + " " + sGroup2; } nCell2.colSpan = iColspan; nCell2.innerHTML = properties.sGroupLabelPrefix2 + properties.fnGroupLabelFormat2(sGroupLabel == "" ? properties.sEmptyGroupLabel : sGroupLabel, oGroup); if (properties.bExpandableGrouping) { nGroup2.className += " group-item-" + oParentGroup.dataGroup; } if (properties.bExpandableGrouping && properties.bExpandableGrouping2) { if (!_fnIsGroupCollapsed(oGroup.dataGroup)) { nCell2.className += " expanded-group"; oGroup.state = "expanded"; } else { nCell2.className += " collapsed-group"; oGroup.state = "collapsed"; } nCell2.className += " group-item-expander"; $(nCell2).attr('data-group', oGroup.dataGroup); $(nCell2).attr("data-group-level", oGroup.level); $(nCell2).click(_fnOnGroupClick); } nGroup2.appendChild(nCell2); oParentGroup.aoSubgroups[oGroup.dataGroup] = oGroup; aoGroups[oGroup.dataGroup] = oGroup; oGroup.nGroup = nGroup2; properties.fnOnGroupCreated(oGroup, sGroup2, 2); return oGroup; } function _fnIsGroupCollapsed(sGroup) { if (aoGroups[sGroup] != null) return (aoGroups[sGroup].state == "collapsed"); else if (sGroup.indexOf("_") > -1) true; else if (bInitialGrouping && (asExpandedGroups == null || asExpandedGroups.length == 0)) return false;// initially if asExpandedGroups is empty - no one is collapsed else return ($.inArray(sGroup, asExpandedGroups) == -1); //the last chance check asExpandedGroups } function _fnGetYear(x) { if (x.length < (iYearIndex + iYearLength)) return x; else return x.substr(iYearIndex, iYearLength); } function _fnGetGroupByName(x) { return x; } function _fnGetGroupByLetter(x) { return x.substr(0, 1); } function _fnGetGroupByYear(x) { return _fnGetYear(x); //return Date.parseExact(x, properties.sDateFormat).getFullYear();//slooooow } function _fnGetGroupByYearMonth(x) { //var date = Date.parseExact(x, "dd/MM/yyyy"); //return date.getFullYear() + " / " + date.getMonthName(); //return x.substr(iYearIndex, iYearLength) + '/' + x.substr(iMonthIndex, iMonthLength); return x.substr(iYearIndex, iYearLength) + ' ' + _getMonthName(x.substr(iMonthIndex, iMonthLength)); } function _fnGetCleanedGroup(sGroup) { if (sGroup === "") return "-"; return sGroup.toLowerCase().replace(/[^a-zA-Z0-9\u0080-\uFFFF]+/g, "-"); //fix for unicode characters (Issue 23) //return sGroup.toLowerCase().replace(/\W+/g, "-"); //Fix provided by bmathews (Issue 7) } function _rowGroupingRowFilter(oSettings, aData, iDataIndex) { ///<summary>Used to expand/collapse groups with DataTables filtering</summary> if (oSettings.nTable.id !== oTable[0].id) return true; var sColData = aData[properties.iGroupingColumnIndex]; if (typeof sColData === "undefined") sColData = aData[oSettings.aoColumns[properties.iGroupingColumnIndex].mDataProp]; if (_fnIsGroupCollapsed(_fnGetCleanedGroup(sColData))) { if (oTable.fnIsOpen(oTable.fnGetNodes(iDataIndex))) { if (properties.fnOnRowClosed != null) { properties.fnOnRowClosed(this); // $(this.cells[0].children[0]).attr('src', '../../Images/details.png'); } oTable.fnClose(oTable.fnGetNodes(iDataIndex)); } return false; } ; return true; } //end of function _rowGroupingRowFilter function fnExpandGroup(sGroup) { ///<summary>Expand group if expanadable grouping is used</summary> aoGroups[sGroup].state = "expanded"; $("td[data-group^='" + sGroup + "']").removeClass("collapsed-group"); $("td[data-group^='" + sGroup + "']").addClass("expanded-group"); if (properties.bUseFilteringForGrouping) { oTable.fnDraw(); return;//Because rows are expanded with _rowGroupingRowFilter function } if (jQuery.inArray(sGroup, asExpandedGroups) == -1) asExpandedGroups.push(sGroup); if (properties.oHideEffect != null) $(".group-item-" + sGroup, oTable) [properties.oShowEffect.method](properties.oShowEffect.duration, properties.oShowEffect.easing, function () { }); else $(".group-item-" + sGroup, oTable).show(); } //end of function fnExpandGroup function fnCollapseGroup(sGroup) { ///<summary>Collapse group if expanadable grouping is used</summary> aoGroups[sGroup].state = "collapsed"; $("td[data-group^='" + sGroup + "']").removeClass("expanded-group"); $("td[data-group^='" + sGroup + "']").addClass("collapsed-group"); if (properties.bUseFilteringForGrouping) { oTable.fnDraw(); return;//Because rows are expanded with _rowGroupingRowFilter function } //var index = $.inArray(sGroup, asExpandedGroups); //asExpandedGroups.splice(index, 1); $('.group-item-' + sGroup).each(function () { //Issue 24 - Patch provided by Bob Graham if (oTable.fnIsOpen(this)) { if (properties.fnOnRowClosed != null) { properties.fnOnRowClosed(this); // $(this.cells[0].children[0]).attr('src', '../../Images/details.png'); } oTable.fnClose(this); } }); if (properties.oHideEffect != null) $(".group-item-" + sGroup, oTable) [properties.oHideEffect.method](properties.oHideEffect.duration, properties.oHideEffect.easing, function () { }); else $(".group-item-" + sGroup, oTable).hide(); } //end of function fnCollapseGroup function _fnOnGroupClick(e) { ///<summary> ///Function that is called when user click on the group cell in order to ///expand of collapse group ///</summary> //var sGroup = $(this).attr("rel"); var sGroup = $(this).attr("data-group"); var iGroupLevel = $(this).attr("data-group-level"); var bIsExpanded = !_fnIsGroupCollapsed(sGroup); if (properties.bExpandSingleGroup) { if (!bIsExpanded) { var sCurrentGroup = $("td.expanded-group").attr("data-group"); fnCollapseGroup(sCurrentGroup); fnExpandGroup(sGroup); if (properties.iExpandGroupOffset != -1) { var position = $("#group-id-" + oTable.attr("id") + "_" + sGroup).offset().top - properties.iExpandGroupOffset; window.scroll(0, position); } else { var position = oTable.offset().top; window.scroll(0, position); } } } else { if (bIsExpanded) { fnCollapseGroup(sGroup); } else { fnExpandGroup(sGroup); } } e.preventDefault(); }; //end function _fnOnGroupClick function _fnDrawCallBackWithGrouping(oSettings) { if (oTable.fnSettings().oFeatures.bServerSide) bInitialGrouping = true; var bUseSecondaryGrouping = false; if (properties.iGroupingColumnIndex2 != -1) bUseSecondaryGrouping = true; //-----Start grouping if (oSettings.aiDisplayMaster.length == 0) { //aiDisplay return; } var nTrs = $('tbody tr', oTable); var iColspan = 0; //nTrs[0].getElementsByTagName('td').length; for (var iColIndex = 0; iColIndex < oSettings.aoColumns.length; iColIndex++) { if (oSettings.aoColumns[iColIndex].bVisible) iColspan += 1; } var sLastGroup = null; var sLastGroup2 = null; if (oSettings.aiDisplay.length > 0) { for (var i = 0; i < nTrs.length; i++) { var iDisplayIndex = oSettings._iDisplayStart + i; if (oTable.fnSettings().oFeatures.bServerSide) iDisplayIndex = i; var sGroupData = ""; var sGroup = null; var sGroupData2 = ""; var sGroup2 = null; //Issue 31 - Start fix provided by Fabien Taysse // sGroupData = oSettings.aoData[oSettings.aiDisplay[iDisplayIndex]]._aData[properties.iGroupingColumnIndex]; // if (sGroupData == undefined) // sGroupData = oSettings.aoData[oSettings.aiDisplay[iDisplayIndex]]._aData[oSettings.aoColumns[properties.iGroupingColumnIndex].mDataProp]; sGroupData = this.fnGetData(nTrs[i], properties.iGroupingColumnIndex); //Issue 31 - End fix provided by Fabien Taysse var sGroup = sGroupData; if (properties.sGroupBy != "year") sGroup = fnGetGroup(sGroupData); if (bUseSecondaryGrouping) { sGroupData2 = oSettings.aoData[oSettings.aiDisplay[iDisplayIndex]]._aData[properties.iGroupingColumnIndex2]; if (sGroupData2 == undefined) sGroupData2 = oSettings.aoData[oSettings.aiDisplay[iDisplayIndex]]._aData[oSettings.aoColumns[properties.iGroupingColumnIndex2].mDataProp]; if (properties.sGroupBy2 != "year") sGroup2 = fnGetGroup(sGroupData2); } if (sLastGroup == null || _fnGetCleanedGroup(sGroup) != _fnGetCleanedGroup(sLastGroup)) { // new group encountered (or first of group) var sGroupCleaned = _fnGetCleanedGroup(sGroup); if (sLastGroup != null) { properties.fnOnGroupCompleted(aoGroups[_fnGetCleanedGroup(sLastGroup)]); } /* if (properties.bExpandableGrouping && bInitialGrouping) { if (properties.bExpandSingleGroup) { if (asExpandedGroups.length == 0) asExpandedGroups.push(sGroupCleaned); } else { asExpandedGroups.push(sGroupCleaned); } } */ if (properties.bAddAllGroupsAsExpanded && jQuery.inArray(sGroupCleaned, asExpandedGroups) == -1) asExpandedGroups.push(sGroupCleaned); var oGroup = fnCreateGroupRow(sGroupCleaned, sGroup, iColspan); var nGroup = oGroup.nGroup; if (nTrs[i].parentNode != null) nTrs[i].parentNode.insertBefore(nGroup, nTrs[i]); else $(nTrs[i]).before(nGroup); sLastGroup = sGroup; sLastGroup2 = null; //to reset second level grouping } // end if (sLastGroup == null || sGroup != sLastGroup) $(nTrs[i]).attr("data-group", aoGroups[sGroupCleaned].dataGroup); $(nTrs[i]).addClass(properties.sGroupItemClass); $(nTrs[i]).addClass("group-item-" + sGroupCleaned); if (properties.bExpandableGrouping) { if (_fnIsGroupCollapsed(sGroupCleaned) && !properties.bUseFilteringForGrouping) { $(nTrs[i]).hide(); } } if (bUseSecondaryGrouping) { if (sLastGroup2 == null || _fnGetCleanedGroup(sGroup2) != _fnGetCleanedGroup(sLastGroup2)) { var sGroup2Id = _fnGetCleanedGroup(sGroup) + '-' + _fnGetCleanedGroup(sGroup2); var oGroup2 = _fnCreateGroup2Row(sGroup2Id, sGroup2, iColspan, aoGroups[sGroupCleaned]) var nGroup2 = oGroup2.nGroup; nTrs[i].parentNode.insertBefore(nGroup2, nTrs[i]); sLastGroup2 = sGroup2; } $(nTrs[i]).attr("data-group", oGroup2.dataGroup) .addClass(properties.sGroupItemClass2) .addClass("group-item-" + oGroup2.dataGroup); } //end if (bUseSecondaryGrouping) } // end for (var i = 0; i < nTrs.length; i++) } ; // if (oSettings.aiDisplay.length > 0) if (sLastGroup != null) { properties.fnOnGroupCompleted(aoGroups[_fnGetCleanedGroup(sLastGroup)]); } //-----End grouping properties.fnOnGrouped(aoGroups); bInitialGrouping = false; }; // end of _fnDrawCallBackWithGrouping = function (oSettings) //var oTable = this; var iYearIndex = 6; var iYearLength = 4; var asExpandedGroups = new Array(); var bInitialGrouping = true; var properties = $.extend(defaults, options); if (properties.iGroupingOrderByColumnIndex == -1) { properties.bCustomColumnOrdering = false; properties.iGroupingOrderByColumnIndex = properties.iGroupingColumnIndex; } else { properties.bCustomColumnOrdering = true; } if (properties.sGroupingColumnSortDirection == "") { if (properties.sGroupBy == "year") properties.sGroupingColumnSortDirection = "desc"; else properties.sGroupingColumnSortDirection = "asc"; } if (properties.iGroupingOrderByColumnIndex2 == -1) { properties.bCustomColumnOrdering2 = false; properties.iGroupingOrderByColumnIndex2 = properties.iGroupingColumnIndex2; } else { properties.bCustomColumnOrdering2 = true; } if (properties.sGroupingColumnSortDirection2 == "") { if (properties.sGroupBy2 == "year") properties.sGroupingColumnSortDirection2 = "desc"; else properties.sGroupingColumnSortDirection2 = "asc"; } iYearIndex = properties.sDateFormat.toLowerCase().indexOf('yy'); iYearLength = properties.sDateFormat.toLowerCase().lastIndexOf('y') - properties.sDateFormat.toLowerCase().indexOf('y') + 1; var iMonthIndex = properties.sDateFormat.toLowerCase().indexOf('mm'); var iMonthLength = properties.sDateFormat.toLowerCase().lastIndexOf('m') - properties.sDateFormat.toLowerCase().indexOf('m') + 1; var fnGetGroup = _fnGetGroupByName; switch (properties.sGroupBy) { case "letter": fnGetGroup = _fnGetGroupByLetter; break; case "year": fnGetGroup = _fnGetGroupByYear; break; case "month": fnGetGroup = _fnGetGroupByYearMonth; break; default: fnGetGroup = _fnGetGroupByName; break; } if (properties.asExpandedGroups != null) { if (properties.asExpandedGroups == "NONE") { properties.asExpandedGroups = []; asExpandedGroups = properties.asExpandedGroups; bInitialGrouping = false; } else if (properties.asExpandedGroups == "ALL") { properties.bAddAllGroupsAsExpanded = true; } else if (properties.asExpandedGroups.constructor == String) { var currentGroup = properties.asExpandedGroups; properties.asExpandedGroups = new Array(); properties.asExpandedGroups.push(_fnGetCleanedGroup(currentGroup)); asExpandedGroups = properties.asExpandedGroups; bInitialGrouping = false; } else if (properties.asExpandedGroups.constructor == Array) { for (var i = 0; i < properties.asExpandedGroups.length; i++) { asExpandedGroups.push(_fnGetCleanedGroup(properties.asExpandedGroups[i])); if (properties.bExpandSingleGroup) break; } bInitialGrouping = false; } } else { properties.asExpandedGroups = new Array(); properties.bAddAllGroupsAsExpanded = true; } if (properties.bExpandSingleGroup) { var nTrs = $('tbody tr', oTable); var sGroupData = oTable.fnGetData(nTrs[0], properties.iGroupingColumnIndex); var sGroup = sGroupData; if (properties.sGroupBy != "year") sGroup = fnGetGroup(sGroupData); var sGroupCleaned = _fnGetCleanedGroup(sGroup); properties.asExpandedGroups = new Array(); properties.asExpandedGroups.push(sGroupCleaned); } oTable.fnSetColumnVis(properties.iGroupingColumnIndex, !properties.bHideGroupingColumn); if (properties.bCustomColumnOrdering) { oTable.fnSetColumnVis(properties.iGroupingOrderByColumnIndex, !properties.bHideGroupingOrderByColumn); } if (properties.iGroupingColumnIndex2 != -1) { oTable.fnSetColumnVis(properties.iGroupingColumnIndex2, !properties.bHideGroupingColumn2); } if (properties.bCustomColumnOrdering2) { oTable.fnSetColumnVis(properties.iGroupingOrderByColumnIndex2, !properties.bHideGroupingOrderByColumn2); } oTable.fnSettings().aoDrawCallback.push({ "fn": _fnDrawCallBackWithGrouping, "sName": "fnRowGrouping" }); var aaSortingFixed = new Array(); aaSortingFixed.push([properties.iGroupingOrderByColumnIndex, properties.sGroupingColumnSortDirection]); if (properties.iGroupingColumnIndex2 != -1) { aaSortingFixed.push([properties.iGroupingOrderByColumnIndex2, properties.sGroupingColumnSortDirection2]); } // end of if (properties.iGroupingColumnIndex2 != -1) oTable.fnSettings().aaSortingFixed = aaSortingFixed; //Old way //oTable.fnSettings().aaSortingFixed = [[properties.iGroupingOrderByColumnIndex, properties.sGroupingColumnSortDirection]]; switch (properties.sGroupBy) { case "name": break; case "letter": /* Create an array with the values of all the input boxes in a column */ oTable.fnSettings().aoColumns[properties.iGroupingOrderByColumnIndex].sSortDataType = "rg-letter"; $.fn.dataTableExt.afnSortData['rg-letter'] = function (oSettings, iColumn) { var aData = []; $('td:eq(' + iColumn + ')', oSettings.oApi._fnGetTrNodes(oSettings)).each(function () { aData.push(_fnGetGroupByLetter(this.innerHTML)); }); return aData; } break; case "year": /* Create an array with the values of all the input boxes in a column */ oTable.fnSettings().aoColumns[properties.iGroupingOrderByColumnIndex].sSortDataType = "rg-date"; $.fn.dataTableExt.afnSortData['rg-date'] = function (oSettings, iColumn) { var aData = []; var nTrs = oSettings.oApi._fnGetTrNodes(oSettings); for (i = 0; i < nTrs.length; i++) { aData.push(_fnGetYear(oTable.fnGetData(nTrs[i], iColumn))); } /* $('td:eq(' + iColumn + ')', oSettings.oApi._fnGetTrNodes(oSettings)).each(function () { aData.push(_fnGetYear(this.innerHTML)); }); */ return aData; } break; default: break; } // end of switch (properties.sGroupBy) if (properties.bUseFilteringForGrouping) $.fn.dataTableExt.afnFiltering.push(_rowGroupingRowFilter); oTable.fnDraw(); }); }; })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-rowGrouping.js
jquery-dataTables-rowGrouping.js
(function(e){var b=Math.abs,a=Math.max,d=Math.min,c=Math.round;function f(){return e("<div/>")}e.imgAreaSelect=function(R,af){var N=e(R),u,B=f(),F=f(),at=f().add(f()).add(f()).add(f()),v=f().add(f()).add(f()).add(f()),aB=e([]),am,U,ar,aC={left:0,top:0},T,aD,p,X={left:0,top:0},g=0,an="absolute",aq,ap,ad,ac,t,q,ao,k,x,aH,ak,E,n,D,l,aF={x1:0,y1:0,x2:0,y2:0,width:0,height:0},G=document.documentElement,V=navigator.userAgent,ab,S,P,O,L,Q,J;function aa(h){return h+aC.left-X.left}function Z(h){return h+aC.top-X.top}function ay(h){return h-aC.left+X.left}function ax(h){return h-aC.top+X.top}function A(h){return h.pageX-X.left}function z(h){return h.pageY-X.top}function aw(h){var o=h||ad,i=h||ac;return{x1:c(aF.x1*o),y1:c(aF.y1*i),x2:c(aF.x2*o),y2:c(aF.y2*i),width:c(aF.x2*o)-c(aF.x1*o),height:c(aF.y2*i)-c(aF.y1*i)}}function au(i,w,h,o,aI){var aK=aI||ad,aJ=aI||ac;aF={x1:c(i/aK||0),y1:c(w/aJ||0),x2:c(h/aK||0),y2:c(o/aJ||0)};aF.width=aF.x2-aF.x1;aF.height=aF.y2-aF.y1}function m(){if(!u||!N.width()){return}aC={left:c(N.offset().left),top:c(N.offset().top)};T=N.innerWidth();aD=N.innerHeight();aC.top+=(N.outerHeight()-aD)>>1;aC.left+=(N.outerWidth()-T)>>1;q=c(af.minWidth/ad)||0;ao=c(af.minHeight/ac)||0;k=c(d(af.maxWidth/ad||1<<24,T));x=c(d(af.maxHeight/ac||1<<24,aD));if(e().jquery=="1.3.2"&&an=="fixed"&&!G.getBoundingClientRect){aC.top+=a(document.body.scrollTop,G.scrollTop);aC.left+=a(document.body.scrollLeft,G.scrollLeft)}X=/absolute|relative/.test(p.css("position"))?{left:c(p.offset().left)-p.scrollLeft(),top:c(p.offset().top)-p.scrollTop()}:an=="fixed"?{left:e(document).scrollLeft(),top:e(document).scrollTop()}:{left:0,top:0};U=aa(0);ar=Z(0);if(aF.x2>T||aF.y2>aD){aE()}}function K(h){if(!ak){return}B.css({left:aa(aF.x1),top:Z(aF.y1)}).add(F).width(L=aF.width).height(Q=aF.height);F.add(at).add(aB).css({left:0,top:0});at.width(a(L-at.outerWidth()+at.innerWidth(),0)).height(a(Q-at.outerHeight()+at.innerHeight(),0));e(v[0]).css({left:U,top:ar,width:aF.x1,height:aD});e(v[1]).css({left:U+aF.x1,top:ar,width:L,height:aF.y1});e(v[2]).css({left:U+aF.x2,top:ar,width:T-aF.x2,height:aD});e(v[3]).css({left:U+aF.x1,top:ar+aF.y2,width:L,height:aD-aF.y2});L-=aB.outerWidth();Q-=aB.outerHeight();switch(aB.length){case 8:e(aB[4]).css({left:L>>1});e(aB[5]).css({left:L,top:Q>>1});e(aB[6]).css({left:L>>1,top:Q});e(aB[7]).css({top:Q>>1});case 4:aB.slice(1,3).css({left:L});aB.slice(2,4).css({top:Q})}if(h!==false){if(e.imgAreaSelect.onKeyPress!=az){e(document).unbind(e.imgAreaSelect.keyPress,e.imgAreaSelect.onKeyPress)}if(af.keys){e(document)[e.imgAreaSelect.keyPress](e.imgAreaSelect.onKeyPress=az)}}if(aj&&at.outerWidth()-at.innerWidth()==2){at.css("margin",0);setTimeout(function(){at.css("margin","auto")},0)}}function y(h){m();K(h);E=aa(aF.x1);n=Z(aF.y1);D=aa(aF.x2);l=Z(aF.y2)}function ai(h,i){af.fadeSpeed?h.fadeOut(af.fadeSpeed,i):h.hide()}function I(i){var h=ay(A(i))-aF.x1,o=ax(z(i))-aF.y1;if(!J){m();J=true;B.one("mouseout",function(){J=false})}t="";if(af.resizable){if(o<=af.resizeMargin){t="n"}else{if(o>=aF.height-af.resizeMargin){t="s"}}if(h<=af.resizeMargin){t+="w"}else{if(h>=aF.width-af.resizeMargin){t+="e"}}}B.css("cursor",t?t+"-resize":af.movable?"move":"");if(am){am.toggle()}}function j(h){e("body").css("cursor","");if(af.autoHide||aF.width*aF.height==0){ai(B.add(v),function(){e(this).hide()})}e(document).unbind("mousemove",ag);B.mousemove(I);af.onSelectEnd(R,aw())}function aA(h){if(h.which!=1){return false}m();if(t){e("body").css("cursor",t+"-resize");E=aa(aF[/w/.test(t)?"x2":"x1"]);n=Z(aF[/n/.test(t)?"y2":"y1"]);e(document).mousemove(ag).one("mouseup",j);B.unbind("mousemove",I)}else{if(af.movable){aq=U+aF.x1-A(h);ap=ar+aF.y1-z(h);B.unbind("mousemove",I);e(document).mousemove(ae).one("mouseup",function(){af.onSelectEnd(R,aw());e(document).unbind("mousemove",ae);B.mousemove(I)})}else{N.mousedown(h)}}return false}function M(h){if(aH){if(h){D=a(U,d(U+T,E+b(l-n)*aH*(D>E||-1)));l=c(a(ar,d(ar+aD,n+b(D-E)/aH*(l>n||-1))));D=c(D)}else{l=a(ar,d(ar+aD,n+b(D-E)/aH*(l>n||-1)));D=c(a(U,d(U+T,E+b(l-n)*aH*(D>E||-1))));l=c(l)}}}function aE(){E=d(E,U+T);n=d(n,ar+aD);if(b(D-E)<q){D=E-q*(D<E||-1);if(D<U){E=U+q}else{if(D>U+T){E=U+T-q}}}if(b(l-n)<ao){l=n-ao*(l<n||-1);if(l<ar){n=ar+ao}else{if(l>ar+aD){n=ar+aD-ao}}}D=a(U,d(D,U+T));l=a(ar,d(l,ar+aD));M(b(D-E)<b(l-n)*aH);if(b(D-E)>k){D=E-k*(D<E||-1);M()}if(b(l-n)>x){l=n-x*(l<n||-1);M(true)}aF={x1:ay(d(E,D)),x2:ay(a(E,D)),y1:ax(d(n,l)),y2:ax(a(n,l)),width:b(D-E),height:b(l-n)};K();af.onSelectChange(R,aw())}function ag(h){D=/w|e|^$/.test(t)||aH?A(h):aa(aF.x2);l=/n|s|^$/.test(t)||aH?z(h):Z(aF.y2);aE();return false}function W(h,i){D=(E=h)+aF.width;l=(n=i)+aF.height;e.extend(aF,{x1:ay(E),y1:ax(n),x2:ay(D),y2:ax(l)});K();af.onSelectChange(R,aw())}function ae(h){E=a(U,d(aq+A(h),U+T-aF.width));n=a(ar,d(ap+z(h),ar+aD-aF.height));W(E,n);h.preventDefault();return false}function r(){e(document).unbind("mousemove",r);m();D=E;l=n;aE();t="";if(!v.is(":visible")){B.add(v).hide().fadeIn(af.fadeSpeed||0)}ak=true;e(document).unbind("mouseup",Y).mousemove(ag).one("mouseup",j);B.unbind("mousemove",I);af.onSelectStart(R,aw())}function Y(){e(document).unbind("mousemove",r).unbind("mouseup",Y);ai(B.add(v));au(ay(E),ax(n),ay(E),ax(n));if(!(this instanceof e.imgAreaSelect)){af.onSelectChange(R,aw());af.onSelectEnd(R,aw())}}function aG(h){if(h.which!=1||v.is(":animated")){return false}m();aq=E=A(h);ap=n=z(h);e(document).mousemove(r).mouseup(Y);return false}function al(){y(false)}function s(){u=true;ah(af=e.extend({classPrefix:"imgareaselect",movable:true,parent:"body",resizable:true,resizeMargin:10,onInit:function(){},onSelectStart:function(){},onSelectChange:function(){},onSelectEnd:function(){}},af));B.add(v).css({visibility:""});if(af.show){ak=true;m();K();B.add(v).hide().fadeIn(af.fadeSpeed||0)}setTimeout(function(){af.onInit(R,aw())},0)}var az=function(w){var h=af.keys,aI,o,i=w.keyCode;aI=!isNaN(h.alt)&&(w.altKey||w.originalEvent.altKey)?h.alt:!isNaN(h.ctrl)&&w.ctrlKey?h.ctrl:!isNaN(h.shift)&&w.shiftKey?h.shift:!isNaN(h.arrows)?h.arrows:10;if(h.arrows=="resize"||(h.shift=="resize"&&w.shiftKey)||(h.ctrl=="resize"&&w.ctrlKey)||(h.alt=="resize"&&(w.altKey||w.originalEvent.altKey))){switch(i){case 37:aI=-aI;case 39:o=a(E,D);E=d(E,D);D=a(o+aI,E);M();break;case 38:aI=-aI;case 40:o=a(n,l);n=d(n,l);l=a(o+aI,n);M(true);break;default:return}aE()}else{E=d(E,D);n=d(n,l);switch(i){case 37:W(a(E-aI,U),n);break;case 38:W(E,a(n-aI,ar));break;case 39:W(E+d(aI,T-ay(D)),n);break;case 40:W(E,n+d(aI,aD-ax(l)));break;default:return}}return false};function H(h,o){for(var i in o){if(af[i]!==undefined){h.css(o[i],af[i])}}}function ah(h){if(h.parent){(p=e(h.parent)).append(B).append(v)}e.extend(af,h);m();if(h.handles!=null){aB.remove();aB=e([]);P=h.handles?h.handles=="corners"?4:8:0;while(P--){aB=aB.add(f())}aB.addClass(af.classPrefix+"-handle").css({position:"absolute",fontSize:0,zIndex:g+1||1});if(!parseInt(aB.css("width"))>=0){aB.width(5).height(5)}if(O=af.borderWidth){aB.css({borderWidth:O,borderStyle:"solid"})}H(aB,{borderColor1:"border-color",borderColor2:"background-color",borderOpacity:"opacity"})}ad=af.imageWidth/T||1;ac=af.imageHeight/aD||1;if(h.x1!=null){au(h.x1,h.y1,h.x2,h.y2);h.show=!h.hide}if(h.keys){af.keys=e.extend({shift:1,ctrl:"resize"},h.keys)}v.addClass(af.classPrefix+"-outer");F.addClass(af.classPrefix+"-selection");for(P=0;P++<4;){e(at[P-1]).addClass(af.classPrefix+"-border"+P)}H(F,{selectionColor:"background-color",selectionOpacity:"opacity"});H(at,{borderOpacity:"opacity",borderWidth:"border-width"});H(v,{outerColor:"background-color",outerOpacity:"opacity"});if(O=af.borderColor1){e(at[0]).css({borderStyle:"solid",borderColor:O})}if(O=af.borderColor2){e(at[1]).css({borderStyle:"dashed",borderColor:O})}B.append(F.add(at).add(am)).append(aB);if(aj){if(O=(v.css("filter")||"").match(/opacity=(\d+)/)){v.css("opacity",O[1]/100)}if(O=(at.css("filter")||"").match(/opacity=(\d+)/)){at.css("opacity",O[1]/100)}}if(h.hide){ai(B.add(v))}else{if(h.show&&u){ak=true;B.add(v).fadeIn(af.fadeSpeed||0);y()}}aH=(S=(af.aspectRatio||"").split(/:/))[0]/S[1];N.add(v).unbind("mousedown",aG);if(af.disable||af.enable===false){B.unbind("mousemove",I).unbind("mousedown",aA);e(window).unbind("resize",al)}else{if(af.enable||af.disable===false){if(af.resizable||af.movable){B.mousemove(I).mousedown(aA)}e(window).resize(al)}if(!af.persistent){N.add(v).mousedown(aG)}}af.enable=af.disable=undefined}this.remove=function(){ah({disable:true});B.add(v).remove()};this.getOptions=function(){return af};this.setOptions=ah;this.getSelection=aw;this.setSelection=au;this.cancelSelection=Y;this.update=y;var aj=(/msie ([\w.]+)/i.exec(V)||[])[1],av=/opera/i.test(V),C=/webkit/i.test(V)&&!/chrome/i.test(V);ab=N;while(ab.length){g=a(g,!isNaN(ab.css("z-index"))?ab.css("z-index"):g);ab=ab.parent(":not(body)")}g=af.zIndex||g;if(aj){N.attr("unselectable","on")}e.imgAreaSelect.keyPress=aj||C?"keydown":"keypress";if(av){am=f().css({width:"100%",height:"100%",position:"absolute",zIndex:g+2||2})}B.add(v).css({visibility:"hidden",position:an,overflow:"hidden",zIndex:g||"0"});B.css({zIndex:g+2||2});F.add(at).css({position:"absolute",fontSize:0});R.complete||R.readyState=="complete"||!N.is("img")?s():N.one("load",s);if(!u&&aj&&aj>=7){R.src=R.src}};e.fn.imgAreaSelect=function(g){g=g||{};this.each(function(){if(e(this).data("imgAreaSelect")){if(g.remove){e(this).data("imgAreaSelect").remove();e(this).removeData("imgAreaSelect")}else{e(this).data("imgAreaSelect").setOptions(g)}}else{if(!g.remove){if(g.enable===undefined&&g.disable===undefined){g.enable=true}e(this).data("imgAreaSelect",new e.imgAreaSelect(this,g))}}});if(g.instance){return e(this).data("imgAreaSelect")}return this}})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-imgareaselect-0.9.11-rc1.min.js
jquery-imgareaselect-0.9.11-rc1.min.js
(function($) { "use strict"; var XmlRpcFault = function() { Error.apply(this, arguments); }; XmlRpcFault.prototype = new Error(); XmlRpcFault.prototype.type = 'XML-RPC fault'; var xmlrpc = $.xmlrpc = function(url, settings) { if (arguments.length === 2) { settings.url = url; } else { settings = url; url = settings.url; } settings.dataType = 'xml json'; settings.type = 'POST'; settings.contentType = 'text/xml'; settings.converters = {'xml json': xmlrpc.parseDocument}; var xmlDoc = xmlrpc.document(settings.methodName, settings.params || []); if ("XMLSerializer" in window) { settings.data = new window.XMLSerializer().serializeToString(xmlDoc); } else { // IE does not have XMLSerializer settings.data = xmlDoc.xml; } return $.ajax(settings); }; /** * Make an XML document node. */ xmlrpc.createXMLDocument = function () { if (document.implementation && "createDocument" in document.implementation) { // Most browsers support createDocument return document.implementation.createDocument(null, null, null); } else { // IE uses ActiveXObject instead of the above. var i, length, activeX = [ "MSXML6.DomDocument", "MSXML3.DomDocument", "MSXML2.DomDocument", "MSXML.DomDocument", "Microsoft.XmlDom" ]; for (i = 0, length = activeX.length; i < length; i++) { try { return new ActiveXObject(activeX[i]); } catch(_) {} } } }; /** * Make an XML-RPC document from a method name and a set of parameters */ xmlrpc.document = function(name, params) { var doc = xmlrpc.createXMLDocument(); var $xml = function(name) { return $(doc.createElement(name)); }; var $methodName = $xml('methodName').text(name); var $params = $xml('params').append($.map(params, function(param) { var $value = $xml('value').append(xmlrpc.toXmlRpc(param, $xml)); return $xml('param').append($value); })); var $methodCall = $xml('methodCall').append($methodName, $params); doc.appendChild($methodCall.get(0)); return doc; }; var _isInt = function(x) { return (x === parseInt(x, 10)) && !isNaN(x); }; /** * Take a JavaScript value, and return an XML node representing the value * in XML-RPC style. If the value is one of the `XmlRpcType`s, that type is * used. Otherwise, a best guess is made as to its type. The best guess is * good enough in the vast majority of cases. */ xmlrpc.toXmlRpc = function(item, $xml) { if (item instanceof XmlRpcType) { return item.toXmlRpc($xml); } var types = $.xmlrpc.types; var type = $.type(item); switch (type) { case "undefined": case "null": return types.nil.encode(item, $xml); case "date": return types['datetime.iso8601'].encode(item, $xml); case "object": if (item instanceof ArrayBuffer) { return types.base64.encode(item, $xml); } else { return types.struct.encode(item, $xml); } break; case "number": // Ints and Floats encode differently if (_isInt(item)) { return types['int'].encode(item, $xml); } else { return types['double'].encode(item, $xml); } break; case "array": case "boolean": case "string": return types[type].encode(item, $xml); default: throw new Error("Unknown type", item); } }; /** * Take an XML-RPC document and decode it to an equivalent JavaScript * representation. * * If the XML-RPC document represents a fault, then an equivalent * XmlRpcFault will be thrown instead */ xmlrpc.parseDocument = function(doc) { var $doc = $(doc); var $response = $doc.children('methodresponse'); var $fault = $response.find('> fault'); if ($fault.length === 0) { var $params = $response.find('> params > param > value > *'); var json = $params.toArray().map(xmlrpc.parseNode); return json; } else { var fault = xmlrpc.parseNode($fault.find('> value > *').get(0)); var err = new XmlRpcFault(fault.faultString); err.msg = err.message = fault.faultString; err.type = err.code = fault.faultCode; throw err; } }; /* * Take an XML-RPC node, and return the JavaScript equivalent */ xmlrpc.parseNode = function(node) { // Some XML-RPC services return empty <value /> elements. This is not // legal XML-RPC, but we may as well handle it. if (node === undefined) { return null; } var nodename = node.nodeName.toLowerCase(); if (nodename in xmlrpc.types) { return xmlrpc.types[nodename].decode(node); } else { throw new Error('Unknown type ' + nodename); } }; /* * Take a <value> node, and return the JavaScript equivalent. */ xmlrpc.parseValue = function(value) { var child = $(value).children()[0]; if (child) { // Child nodes should be decoded. return xmlrpc.parseNode(child); } else { // If no child nodes, the value is a plain text node. return $(value).text(); } }; var XmlRpcType = function() { }; $.xmlrpc.types = {}; /** * Make a XML-RPC type. We use these to encode and decode values. You can * also force a values type using this. See `$.xmlrpc.force()` */ xmlrpc.makeType = function(tagName, simple, encode, decode) { var Type; Type = function(value) { this.value = value; }; Type.prototype = new XmlRpcType(); Type.prototype.tagName = tagName; if (simple) { var simpleEncode = encode, simpleDecode = decode; encode = function(value, $xml) { var text = simpleEncode(value); return $xml(Type.tagName).text(text); }; decode = function(node) { return simpleDecode($(node).text(), node); }; } Type.prototype.toXmlRpc = function($xml) { return Type.encode(this.value, $xml); }; Type.tagName = tagName; Type.encode = encode; Type.decode = decode; xmlrpc.types[tagName.toLowerCase()] = Type; }; // Number types var _fromInt = function(value) { return '' + Math.floor(value); }; var _toInt = function(text, _) { return parseInt(text, 10); }; xmlrpc.makeType('int', true, _fromInt, _toInt); xmlrpc.makeType('i4', true, _fromInt, _toInt); xmlrpc.makeType('i8', true, _fromInt, _toInt); xmlrpc.makeType('i16', true, _fromInt, _toInt); xmlrpc.makeType('i32', true, _fromInt, _toInt); xmlrpc.makeType('double', true, String, function(text) { return parseFloat(text, 10); }); // String type. Fairly simple xmlrpc.makeType('string', true, String, String); // Boolean type. True == '1', False == '0' xmlrpc.makeType('boolean', true, function(value) { return value ? '1' : '0'; }, function(text) { return text === '1'; }); // Dates are a little trickier var _pad = function(n) { return n<10 ? '0'+n : n; }; xmlrpc.makeType('dateTime.iso8601', true, function(d) { return [ d.getUTCFullYear(), '-', _pad(d.getUTCMonth()+1), '-', _pad(d.getUTCDate()), 'T', _pad(d.getUTCHours()), ':', _pad(d.getUTCMinutes()), ':', _pad(d.getUTCSeconds()), 'Z' ].join(''); }, function(text) { return new Date(text); }); // Go between a base64 string and an ArrayBuffer xmlrpc.binary = (function() { var pad = '='; var toChars = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz0123456789+/').split(""); var fromChars = toChars.reduce(function(acc, chr, i) { acc[chr] = i; return acc; }, {}); /* * In the following, three bytes are added together into a 24-bit * number, which is then split up in to 4 6-bit numbers - or vice versa. * That is why there is lots of shifting by multiples of 6 and 8, and * the magic numbers 3 and 4. * * The modulo 64 is for converting to base 64, and the modulo 256 is for * converting to 8-bit numbers. */ return { toBase64: function(ab) { var acc = []; var int8View = new Uint8Array(ab); var int8Index = 0, int24; for (; int8Index < int8View.length; int8Index += 3) { // Grab three bytes int24 = (int8View[int8Index + 0] << 16) + (int8View[int8Index + 1] << 8) + (int8View[int8Index + 2] << 0); // Push four chars acc.push(toChars[(int24 >> 18) % 64]); acc.push(toChars[(int24 >> 12) % 64]); acc.push(toChars[(int24 >> 6) % 64]); acc.push(toChars[(int24 >> 0)% 64]); } // Set the last few characters to the padding character var padChars = 3 - ((ab.byteLength % 3) || 3); while (padChars--) { acc[acc.length - padChars - 1] = pad; } return acc.join(''); }, fromBase64: function(base64) { var base64Len = base64.length; // Work out the length of the data, accommodating for padding var abLen = (base64Len / 4) * 3; if (base64.charAt(base64Len - 1) === pad) { abLen--; } if (base64.charAt(base64Len - 2) === pad) { abLen--; } // Make the ArrayBuffer, and an Int8Array to work with it var ab = new ArrayBuffer(abLen); var int8View = new Uint8Array(ab); var base64Index = 0, int8Index = 0, int24; for (; base64Index < base64Len; base64Index += 4, int8Index += 3) { // Grab four chars int24 = (fromChars[base64[base64Index + 0]] << 18) + (fromChars[base64[base64Index + 1]] << 12) + (fromChars[base64[base64Index + 2]] << 6) + (fromChars[base64[base64Index + 3]] << 0); // Push three bytes int8View[int8Index + 0] = (int24 >> 16) % 256; int8View[int8Index + 1] = (int24 >> 8) % 256; int8View[int8Index + 2] = (int24 >> 0) % 256; } return ab; } }; })(); xmlrpc.makeType('base64', true, function(ab) { return xmlrpc.binary.toBase64(ab); }, function(text) { return xmlrpc.binary.fromBase64(text); }); // Nil/null xmlrpc.makeType('nil', false, function(val, $xml) { return $xml('nil'); }, function(_) { return null; } ); // Structs/Objects xmlrpc.makeType('struct', false, function(value, $xml) { var $struct = $xml('struct'); $.each(value, function(name, value) { var $name = $xml('name').text(name); var $value = $xml('value').append(xmlrpc.toXmlRpc(value, $xml)); $struct.append($xml('member').append($name, $value)); }); return $struct; }, function(node) { return $(node) .find('> member') .toArray() .reduce(function(struct, el) { var $el = $(el); var key = $el.find('> name').text(); var value = xmlrpc.parseValue($el.find('> value')); struct[key] = value; return struct; }, {}); }); // Arrays xmlrpc.makeType('array', false, function(value, $xml) { var $array = $xml('array'); var $data = $xml('data'); $.each(value, function(i, val) { $data.append($xml('value').append(xmlrpc.toXmlRpc(val, $xml))); }); $array.append($data); return $array; }, function(node) { return $(node).find('> data > value').toArray() .map(xmlrpc.parseValue); }); /** * Force a value to an XML-RPC type. All the usual XML-RPC types are * supported */ xmlrpc.force = function(type, value) { return new xmlrpc.types[type](value); }; })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-xmlrpc.js
jquery-xmlrpc.js
(function(b){var a=function(d,c){this.element=b(d);this.picker=b('<div class="slider"><div class="slider-track"><div class="slider-selection"></div><div class="slider-handle"></div><div class="slider-handle"></div></div><div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div></div>').insertBefore(this.element).prepend(this.element);this.id=this.element.data("slider-id")||c.id;if(this.id){this.picker[0].id=this.id}if(typeof Modernizr!=="undefined"&&Modernizr.touch){this.touchCapable=true}var f=this.element.data("slider-tooltip")||c.tooltip;this.tooltip=this.picker.find(".tooltip");this.tooltipInner=this.tooltip.find("div.tooltip-inner");this.orientation=this.element.data("slider-orientation")||c.orientation;switch(this.orientation){case"vertical":this.picker.addClass("slider-vertical");this.stylePos="top";this.mousePos="pageY";this.sizePos="offsetHeight";this.tooltip.addClass("right")[0].style.left="100%";break;default:this.picker.addClass("slider-horizontal").css("width",this.element.outerWidth());this.orientation="horizontal";this.stylePos="left";this.mousePos="pageX";this.sizePos="offsetWidth";this.tooltip.addClass("top")[0].style.top=-this.tooltip.outerHeight()-14+"px";break}this.min=this.element.data("slider-min")||c.min;this.max=this.element.data("slider-max")||c.max;this.step=this.element.data("slider-step")||c.step;this.value=this.element.data("slider-value")||c.value;if(this.value[1]){this.range=true}this.selection=this.element.data("slider-selection")||c.selection;this.selectionEl=this.picker.find(".slider-selection");if(this.selection==="none"){this.selectionEl.addClass("hide")}this.selectionElStyle=this.selectionEl[0].style;this.handle1=this.picker.find(".slider-handle:first");this.handle1Stype=this.handle1[0].style;this.handle2=this.picker.find(".slider-handle:last");this.handle2Stype=this.handle2[0].style;var e=this.element.data("slider-handle")||c.handle;switch(e){case"round":this.handle1.addClass("round");this.handle2.addClass("round");break;case"triangle":this.handle1.addClass("triangle");this.handle2.addClass("triangle");break}if(this.range){this.value[0]=Math.max(this.min,Math.min(this.max,this.value[0]));this.value[1]=Math.max(this.min,Math.min(this.max,this.value[1]))}else{this.value=[Math.max(this.min,Math.min(this.max,this.value))];this.handle2.addClass("hide");if(this.selection=="after"){this.value[1]=this.max}else{this.value[1]=this.min}}this.diff=this.max-this.min;this.percentage=[(this.value[0]-this.min)*100/this.diff,(this.value[1]-this.min)*100/this.diff,this.step*100/this.diff];this.offset=this.picker.offset();this.size=this.picker[0][this.sizePos];this.formater=c.formater;this.layout();if(this.touchCapable){this.picker.on({touchstart:b.proxy(this.mousedown,this)})}else{this.picker.on({mousedown:b.proxy(this.mousedown,this)})}if(f==="show"){this.picker.on({mouseenter:b.proxy(this.showTooltip,this),mouseleave:b.proxy(this.hideTooltip,this)})}else{this.tooltip.addClass("hide")}};a.prototype={constructor:a,over:false,inDrag:false,showTooltip:function(){this.tooltip.addClass("in");this.over=true},hideTooltip:function(){if(this.inDrag===false){this.tooltip.removeClass("in")}this.over=false},layout:function(){this.handle1Stype[this.stylePos]=this.percentage[0]+"%";this.handle2Stype[this.stylePos]=this.percentage[1]+"%";if(this.orientation=="vertical"){this.selectionElStyle.top=Math.min(this.percentage[0],this.percentage[1])+"%";this.selectionElStyle.height=Math.abs(this.percentage[0]-this.percentage[1])+"%"}else{this.selectionElStyle.left=Math.min(this.percentage[0],this.percentage[1])+"%";this.selectionElStyle.width=Math.abs(this.percentage[0]-this.percentage[1])+"%"}if(this.range){this.tooltipInner.text(this.formater(this.value[0])+" : "+this.formater(this.value[1]));this.tooltip[0].style[this.stylePos]=this.size*(this.percentage[0]+(this.percentage[1]-this.percentage[0])/2)/100-(this.orientation==="vertical"?this.tooltip.outerHeight()/2:this.tooltip.outerWidth()/2)+"px"}else{this.tooltipInner.text(this.formater(this.value[0]));this.tooltip[0].style[this.stylePos]=this.size*this.percentage[0]/100-(this.orientation==="vertical"?this.tooltip.outerHeight()/2:this.tooltip.outerWidth()/2)+"px"}},mousedown:function(d){if(this.touchCapable&&d.type==="touchstart"){d=d.originalEvent}this.offset=this.picker.offset();this.size=this.picker[0][this.sizePos];var c=this.getPercentage(d);if(this.range){var g=Math.abs(this.percentage[0]-c);var e=Math.abs(this.percentage[1]-c);this.dragged=(g<e)?0:1}else{this.dragged=0}this.percentage[this.dragged]=c;this.layout();if(this.touchCapable){b(document).on({touchmove:b.proxy(this.mousemove,this),touchend:b.proxy(this.mouseup,this)})}else{b(document).on({mousemove:b.proxy(this.mousemove,this),mouseup:b.proxy(this.mouseup,this)})}this.inDrag=true;var f=this.calculateValue();this.element.trigger({type:"slideStart",value:f}).trigger({type:"slide",value:f});return false},mousemove:function(d){if(this.touchCapable&&d.type==="touchmove"){d=d.originalEvent}var c=this.getPercentage(d);if(this.range){if(this.dragged===0&&this.percentage[1]<c){this.percentage[0]=this.percentage[1];this.dragged=1}else{if(this.dragged===1&&this.percentage[0]>c){this.percentage[1]=this.percentage[0];this.dragged=0}}}this.percentage[this.dragged]=c;this.layout();var e=this.calculateValue();this.element.trigger({type:"slide",value:e}).data("value",e).prop("value",e);return false},mouseup:function(c){if(this.touchCapable){b(document).off({touchmove:this.mousemove,touchend:this.mouseup})}else{b(document).off({mousemove:this.mousemove,mouseup:this.mouseup})}this.inDrag=false;if(this.over==false){this.hideTooltip()}this.element;var d=this.calculateValue();this.element.trigger({type:"slideStop",value:d}).data("value",d).prop("value",d);return false},calculateValue:function(){var c;if(this.range){c=[(this.min+Math.round((this.diff*this.percentage[0]/100)/this.step)*this.step),(this.min+Math.round((this.diff*this.percentage[1]/100)/this.step)*this.step)];this.value=c}else{c=(this.min+Math.round((this.diff*this.percentage[0]/100)/this.step)*this.step);this.value=[c,this.value[1]]}return c},getPercentage:function(d){if(this.touchCapable){d=d.touches[0]}var c=(d[this.mousePos]-this.offset[this.stylePos])*100/this.size;c=Math.round(c/this.percentage[2])*this.percentage[2];return Math.max(0,Math.min(100,c))},getValue:function(){if(this.range){return this.value}return this.value[0]},setValue:function(c){this.value=c;if(this.range){this.value[0]=Math.max(this.min,Math.min(this.max,this.value[0]));this.value[1]=Math.max(this.min,Math.min(this.max,this.value[1]))}else{this.value=[Math.max(this.min,Math.min(this.max,this.value))];this.handle2.addClass("hide");if(this.selection=="after"){this.value[1]=this.max}else{this.value[1]=this.min}}this.diff=this.max-this.min;this.percentage=[(this.value[0]-this.min)*100/this.diff,(this.value[1]-this.min)*100/this.diff,this.step*100/this.diff];this.layout()}};b.fn.slider=function(c,d){return this.each(function(){var g=b(this),f=g.data("slider"),e=typeof c==="object"&&c;if(!f){g.data("slider",(f=new a(this,b.extend({},b.fn.slider.defaults,e))))}if(typeof c=="string"){f[c](d)}})};b.fn.slider.defaults={min:0,max:10,step:1,orientation:"horizontal",value:5,selection:"before",tooltip:"show",handle:"round",formater:function(c){return c}};b.fn.slider.Constructor=a;b.fn.BS_slider=b.fn.slider})(window.jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/bootstrap-slider-2.0.0.min.js
bootstrap-slider-2.0.0.min.js
(function (factory) { /* jshint ignore:start */ if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object') { // Node/CommonJS module.exports = factory(require('jquery')); } else { // Browser globals factory(jQuery); } /* jshint ignore:end */ }(function ($) { // Defaults $.minicolors = { defaults: { animationSpeed: 50, animationEasing: 'swing', change: null, changeDelay: 0, control: 'hue', dataUris: true, defaultValue: '', hide: null, hideSpeed: 100, inline: false, letterCase: 'lowercase', opacity: false, position: 'bottom left', show: null, showSpeed: 100, theme: 'default' } }; // Public methods $.extend($.fn, { minicolors: function(method, data) { switch(method) { // Destroy the control case 'destroy': $(this).each( function() { destroy($(this)); }); return $(this); // Hide the color picker case 'hide': hide(); return $(this); // Get/set opacity case 'opacity': // Getter if( data === undefined ) { // Getter return $(this).attr('data-opacity'); } else { // Setter $(this).each( function() { updateFromInput($(this).attr('data-opacity', data)); }); } return $(this); // Get an RGB(A) object based on the current color/opacity case 'rgbObject': return rgbObject($(this), method === 'rgbaObject'); // Get an RGB(A) string based on the current color/opacity case 'rgbString': case 'rgbaString': return rgbString($(this), method === 'rgbaString'); // Get/set settings on the fly case 'settings': if( data === undefined ) { return $(this).data('minicolors-settings'); } else { // Setter $(this).each( function() { var settings = $(this).data('minicolors-settings') || {}; destroy($(this)); $(this).minicolors($.extend(true, settings, data)); }); } return $(this); // Show the color picker case 'show': show( $(this).eq(0) ); return $(this); // Get/set the hex color value case 'value': if( data === undefined ) { // Getter return $(this).val(); } else { // Setter $(this).each( function() { updateFromInput($(this).val(data)); }); } return $(this); // Initializes the control default: if( method !== 'create' ) data = method; $(this).each( function() { init($(this), data); }); return $(this); } } }); // Initialize input elements function init(input, settings) { var minicolors = $('<div class="minicolors" />'), defaults = $.minicolors.defaults; // Do nothing if already initialized if( input.data('minicolors-initialized') ) return; // Handle settings settings = $.extend(true, {}, defaults, settings); // The wrapper minicolors .addClass('minicolors-theme-' + settings.theme) .toggleClass('minicolors-with-opacity', settings.opacity) .toggleClass('minicolors-no-data-uris', settings.dataUris !== true); // Custom positioning if( settings.position !== undefined ) { $.each(settings.position.split(' '), function() { minicolors.addClass('minicolors-position-' + this); }); } // The input input .addClass('minicolors-input') .data('minicolors-initialized', false) .data('minicolors-settings', settings) .prop('size', 7) .wrap(minicolors) .after( '<div class="minicolors-panel minicolors-slider-' + settings.control + '">' + '<div class="minicolors-slider minicolors-sprite">' + '<div class="minicolors-picker"></div>' + '</div>' + '<div class="minicolors-opacity-slider minicolors-sprite">' + '<div class="minicolors-picker"></div>' + '</div>' + '<div class="minicolors-grid minicolors-sprite">' + '<div class="minicolors-grid-inner"></div>' + '<div class="minicolors-picker"><div></div></div>' + '</div>' + '</div>' ); // The swatch if( !settings.inline ) { input.after('<span class="minicolors-swatch minicolors-sprite"><span class="minicolors-swatch-color"></span></span>'); input.next('.minicolors-swatch').on('click', function(event) { event.preventDefault(); input.focus(); }); } // Prevent text selection in IE input.parent().find('.minicolors-panel').on('selectstart', function() { return false; }).end(); // Inline controls if( settings.inline ) input.parent().addClass('minicolors-inline'); updateFromInput(input, false); input.data('minicolors-initialized', true); } // Returns the input back to its original state function destroy(input) { var minicolors = input.parent(); // Revert the input element input .removeData('minicolors-initialized') .removeData('minicolors-settings') .removeProp('size') .removeClass('minicolors-input'); // Remove the wrap and destroy whatever remains minicolors.before(input).remove(); } // Shows the specified dropdown panel function show(input) { var minicolors = input.parent(), panel = minicolors.find('.minicolors-panel'), settings = input.data('minicolors-settings'); // Do nothing if uninitialized, disabled, inline, or already open if( !input.data('minicolors-initialized') || input.prop('disabled') || minicolors.hasClass('minicolors-inline') || minicolors.hasClass('minicolors-focus') ) return; hide(); minicolors.addClass('minicolors-focus'); panel .stop(true, true) .fadeIn(settings.showSpeed, function() { if( settings.show ) settings.show.call(input.get(0)); }); } // Hides all dropdown panels function hide() { $('.minicolors-focus').each( function() { var minicolors = $(this), input = minicolors.find('.minicolors-input'), panel = minicolors.find('.minicolors-panel'), settings = input.data('minicolors-settings'); panel.fadeOut(settings.hideSpeed, function() { if( settings.hide ) settings.hide.call(input.get(0)); minicolors.removeClass('minicolors-focus'); }); }); } // Moves the selected picker function move(target, event, animate) { var input = target.parents('.minicolors').find('.minicolors-input'), settings = input.data('minicolors-settings'), picker = target.find('[class$=-picker]'), offsetX = target.offset().left, offsetY = target.offset().top, x = Math.round(event.pageX - offsetX), y = Math.round(event.pageY - offsetY), duration = animate ? settings.animationSpeed : 0, wx, wy, r, phi; // Touch support if( event.originalEvent.changedTouches ) { x = event.originalEvent.changedTouches[0].pageX - offsetX; y = event.originalEvent.changedTouches[0].pageY - offsetY; } // Constrain picker to its container if( x < 0 ) x = 0; if( y < 0 ) y = 0; if( x > target.width() ) x = target.width(); if( y > target.height() ) y = target.height(); // Constrain color wheel values to the wheel if( target.parent().is('.minicolors-slider-wheel') && picker.parent().is('.minicolors-grid') ) { wx = 75 - x; wy = 75 - y; r = Math.sqrt(wx * wx + wy * wy); phi = Math.atan2(wy, wx); if( phi < 0 ) phi += Math.PI * 2; if( r > 75 ) { r = 75; x = 75 - (75 * Math.cos(phi)); y = 75 - (75 * Math.sin(phi)); } x = Math.round(x); y = Math.round(y); } // Move the picker if( target.is('.minicolors-grid') ) { picker .stop(true) .animate({ top: y + 'px', left: x + 'px' }, duration, settings.animationEasing, function() { updateFromControl(input, target); }); } else { picker .stop(true) .animate({ top: y + 'px' }, duration, settings.animationEasing, function() { updateFromControl(input, target); }); } } // Sets the input based on the color picker values function updateFromControl(input, target) { function getCoords(picker, container) { var left, top; if( !picker.length || !container ) return null; left = picker.offset().left; top = picker.offset().top; return { x: left - container.offset().left + (picker.outerWidth() / 2), y: top - container.offset().top + (picker.outerHeight() / 2) }; } var hue, saturation, brightness, x, y, r, phi, hex = input.val(), opacity = input.attr('data-opacity'), // Helpful references minicolors = input.parent(), settings = input.data('minicolors-settings'), swatch = minicolors.find('.minicolors-swatch'), // Panel objects grid = minicolors.find('.minicolors-grid'), slider = minicolors.find('.minicolors-slider'), opacitySlider = minicolors.find('.minicolors-opacity-slider'), // Picker objects gridPicker = grid.find('[class$=-picker]'), sliderPicker = slider.find('[class$=-picker]'), opacityPicker = opacitySlider.find('[class$=-picker]'), // Picker positions gridPos = getCoords(gridPicker, grid), sliderPos = getCoords(sliderPicker, slider), opacityPos = getCoords(opacityPicker, opacitySlider); // Handle colors if( target.is('.minicolors-grid, .minicolors-slider') ) { // Determine HSB values switch(settings.control) { case 'wheel': // Calculate hue, saturation, and brightness x = (grid.width() / 2) - gridPos.x; y = (grid.height() / 2) - gridPos.y; r = Math.sqrt(x * x + y * y); phi = Math.atan2(y, x); if( phi < 0 ) phi += Math.PI * 2; if( r > 75 ) { r = 75; gridPos.x = 69 - (75 * Math.cos(phi)); gridPos.y = 69 - (75 * Math.sin(phi)); } saturation = keepWithin(r / 0.75, 0, 100); hue = keepWithin(phi * 180 / Math.PI, 0, 360); brightness = keepWithin(100 - Math.floor(sliderPos.y * (100 / slider.height())), 0, 100); hex = hsb2hex({ h: hue, s: saturation, b: brightness }); // Update UI slider.css('backgroundColor', hsb2hex({ h: hue, s: saturation, b: 100 })); break; case 'saturation': // Calculate hue, saturation, and brightness hue = keepWithin(parseInt(gridPos.x * (360 / grid.width()), 10), 0, 360); saturation = keepWithin(100 - Math.floor(sliderPos.y * (100 / slider.height())), 0, 100); brightness = keepWithin(100 - Math.floor(gridPos.y * (100 / grid.height())), 0, 100); hex = hsb2hex({ h: hue, s: saturation, b: brightness }); // Update UI slider.css('backgroundColor', hsb2hex({ h: hue, s: 100, b: brightness })); minicolors.find('.minicolors-grid-inner').css('opacity', saturation / 100); break; case 'brightness': // Calculate hue, saturation, and brightness hue = keepWithin(parseInt(gridPos.x * (360 / grid.width()), 10), 0, 360); saturation = keepWithin(100 - Math.floor(gridPos.y * (100 / grid.height())), 0, 100); brightness = keepWithin(100 - Math.floor(sliderPos.y * (100 / slider.height())), 0, 100); hex = hsb2hex({ h: hue, s: saturation, b: brightness }); // Update UI slider.css('backgroundColor', hsb2hex({ h: hue, s: saturation, b: 100 })); minicolors.find('.minicolors-grid-inner').css('opacity', 1 - (brightness / 100)); break; default: // Calculate hue, saturation, and brightness hue = keepWithin(360 - parseInt(sliderPos.y * (360 / slider.height()), 10), 0, 360); saturation = keepWithin(Math.floor(gridPos.x * (100 / grid.width())), 0, 100); brightness = keepWithin(100 - Math.floor(gridPos.y * (100 / grid.height())), 0, 100); hex = hsb2hex({ h: hue, s: saturation, b: brightness }); // Update UI grid.css('backgroundColor', hsb2hex({ h: hue, s: 100, b: 100 })); break; } // Adjust case input.val( convertCase(hex, settings.letterCase) ); } // Handle opacity if( target.is('.minicolors-opacity-slider') ) { if( settings.opacity ) { opacity = parseFloat(1 - (opacityPos.y / opacitySlider.height())).toFixed(2); } else { opacity = 1; } if( settings.opacity ) input.attr('data-opacity', opacity); } // Set swatch color swatch.find('SPAN').css({ backgroundColor: hex, opacity: opacity }); // Handle change event doChange(input, hex, opacity); } // Sets the color picker values from the input function updateFromInput(input, preserveInputValue) { var hex, hsb, opacity, x, y, r, phi, // Helpful references minicolors = input.parent(), settings = input.data('minicolors-settings'), swatch = minicolors.find('.minicolors-swatch'), // Panel objects grid = minicolors.find('.minicolors-grid'), slider = minicolors.find('.minicolors-slider'), opacitySlider = minicolors.find('.minicolors-opacity-slider'), // Picker objects gridPicker = grid.find('[class$=-picker]'), sliderPicker = slider.find('[class$=-picker]'), opacityPicker = opacitySlider.find('[class$=-picker]'); // Determine hex/HSB values hex = convertCase(parseHex(input.val(), true), settings.letterCase); if( !hex ){ hex = convertCase(parseHex(settings.defaultValue, true), settings.letterCase); } hsb = hex2hsb(hex); // Update input value if( !preserveInputValue ) input.val(hex); // Determine opacity value if( settings.opacity ) { // Get from data-opacity attribute and keep within 0-1 range opacity = input.attr('data-opacity') === '' ? 1 : keepWithin(parseFloat(input.attr('data-opacity')).toFixed(2), 0, 1); if( isNaN(opacity) ) opacity = 1; input.attr('data-opacity', opacity); swatch.find('SPAN').css('opacity', opacity); // Set opacity picker position y = keepWithin(opacitySlider.height() - (opacitySlider.height() * opacity), 0, opacitySlider.height()); opacityPicker.css('top', y + 'px'); } // Update swatch swatch.find('SPAN').css('backgroundColor', hex); // Determine picker locations switch(settings.control) { case 'wheel': // Set grid position r = keepWithin(Math.ceil(hsb.s * 0.75), 0, grid.height() / 2); phi = hsb.h * Math.PI / 180; x = keepWithin(75 - Math.cos(phi) * r, 0, grid.width()); y = keepWithin(75 - Math.sin(phi) * r, 0, grid.height()); gridPicker.css({ top: y + 'px', left: x + 'px' }); // Set slider position y = 150 - (hsb.b / (100 / grid.height())); if( hex === '' ) y = 0; sliderPicker.css('top', y + 'px'); // Update panel color slider.css('backgroundColor', hsb2hex({ h: hsb.h, s: hsb.s, b: 100 })); break; case 'saturation': // Set grid position x = keepWithin((5 * hsb.h) / 12, 0, 150); y = keepWithin(grid.height() - Math.ceil(hsb.b / (100 / grid.height())), 0, grid.height()); gridPicker.css({ top: y + 'px', left: x + 'px' }); // Set slider position y = keepWithin(slider.height() - (hsb.s * (slider.height() / 100)), 0, slider.height()); sliderPicker.css('top', y + 'px'); // Update UI slider.css('backgroundColor', hsb2hex({ h: hsb.h, s: 100, b: hsb.b })); minicolors.find('.minicolors-grid-inner').css('opacity', hsb.s / 100); break; case 'brightness': // Set grid position x = keepWithin((5 * hsb.h) / 12, 0, 150); y = keepWithin(grid.height() - Math.ceil(hsb.s / (100 / grid.height())), 0, grid.height()); gridPicker.css({ top: y + 'px', left: x + 'px' }); // Set slider position y = keepWithin(slider.height() - (hsb.b * (slider.height() / 100)), 0, slider.height()); sliderPicker.css('top', y + 'px'); // Update UI slider.css('backgroundColor', hsb2hex({ h: hsb.h, s: hsb.s, b: 100 })); minicolors.find('.minicolors-grid-inner').css('opacity', 1 - (hsb.b / 100)); break; default: // Set grid position x = keepWithin(Math.ceil(hsb.s / (100 / grid.width())), 0, grid.width()); y = keepWithin(grid.height() - Math.ceil(hsb.b / (100 / grid.height())), 0, grid.height()); gridPicker.css({ top: y + 'px', left: x + 'px' }); // Set slider position y = keepWithin(slider.height() - (hsb.h / (360 / slider.height())), 0, slider.height()); sliderPicker.css('top', y + 'px'); // Update panel color grid.css('backgroundColor', hsb2hex({ h: hsb.h, s: 100, b: 100 })); break; } // Fire change event, but only if minicolors is fully initialized if( input.data('minicolors-initialized') ) { doChange(input, hex, opacity); } } // Runs the change and changeDelay callbacks function doChange(input, hex, opacity) { var settings = input.data('minicolors-settings'), lastChange = input.data('minicolors-lastChange'); // Only run if it actually changed if( !lastChange || lastChange.hex !== hex || lastChange.opacity !== opacity ) { // Remember last-changed value input.data('minicolors-lastChange', { hex: hex, opacity: opacity }); // Fire change event if( settings.change ) { if( settings.changeDelay ) { // Call after a delay clearTimeout(input.data('minicolors-changeTimeout')); input.data('minicolors-changeTimeout', setTimeout( function() { settings.change.call(input.get(0), hex, opacity); }, settings.changeDelay)); } else { // Call immediately settings.change.call(input.get(0), hex, opacity); } } input.trigger('change').trigger('input'); } } // Generates an RGB(A) object based on the input's value function rgbObject(input) { var hex = parseHex($(input).val(), true), rgb = hex2rgb(hex), opacity = $(input).attr('data-opacity'); if( !rgb ) return null; if( opacity !== undefined ) $.extend(rgb, { a: parseFloat(opacity) }); return rgb; } // Genearates an RGB(A) string based on the input's value function rgbString(input, alpha) { var hex = parseHex($(input).val(), true), rgb = hex2rgb(hex), opacity = $(input).attr('data-opacity'); if( !rgb ) return null; if( opacity === undefined ) opacity = 1; if( alpha ) { return 'rgba(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ', ' + parseFloat(opacity) + ')'; } else { return 'rgb(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ')'; } } // Converts to the letter case specified in settings function convertCase(string, letterCase) { return letterCase === 'uppercase' ? string.toUpperCase() : string.toLowerCase(); } // Parses a string and returns a valid hex string when possible function parseHex(string, expand) { string = string.replace(/[^A-F0-9]/ig, ''); if( string.length !== 3 && string.length !== 6 ) return ''; if( string.length === 3 && expand ) { string = string[0] + string[0] + string[1] + string[1] + string[2] + string[2]; } return '#' + string; } // Keeps value within min and max function keepWithin(value, min, max) { if( value < min ) value = min; if( value > max ) value = max; return value; } // Converts an HSB object to an RGB object function hsb2rgb(hsb) { var rgb = {}; var h = Math.round(hsb.h); var s = Math.round(hsb.s * 255 / 100); var v = Math.round(hsb.b * 255 / 100); if(s === 0) { rgb.r = rgb.g = rgb.b = v; } else { var t1 = v; var t2 = (255 - s) * v / 255; var t3 = (t1 - t2) * (h % 60) / 60; if( h === 360 ) h = 0; if( h < 60 ) { rgb.r = t1; rgb.b = t2; rgb.g = t2 + t3; } else if( h < 120 ) {rgb.g = t1; rgb.b = t2; rgb.r = t1 - t3; } else if( h < 180 ) {rgb.g = t1; rgb.r = t2; rgb.b = t2 + t3; } else if( h < 240 ) {rgb.b = t1; rgb.r = t2; rgb.g = t1 - t3; } else if( h < 300 ) {rgb.b = t1; rgb.g = t2; rgb.r = t2 + t3; } else if( h < 360 ) {rgb.r = t1; rgb.g = t2; rgb.b = t1 - t3; } else { rgb.r = 0; rgb.g = 0; rgb.b = 0; } } return { r: Math.round(rgb.r), g: Math.round(rgb.g), b: Math.round(rgb.b) }; } // Converts an RGB object to a hex string function rgb2hex(rgb) { var hex = [ rgb.r.toString(16), rgb.g.toString(16), rgb.b.toString(16) ]; $.each(hex, function(nr, val) { if (val.length === 1) hex[nr] = '0' + val; }); return '#' + hex.join(''); } // Converts an HSB object to a hex string function hsb2hex(hsb) { return rgb2hex(hsb2rgb(hsb)); } // Converts a hex string to an HSB object function hex2hsb(hex) { var hsb = rgb2hsb(hex2rgb(hex)); if( hsb.s === 0 ) hsb.h = 360; return hsb; } // Converts an RGB object to an HSB object function rgb2hsb(rgb) { var hsb = { h: 0, s: 0, b: 0 }; var min = Math.min(rgb.r, rgb.g, rgb.b); var max = Math.max(rgb.r, rgb.g, rgb.b); var delta = max - min; hsb.b = max; hsb.s = max !== 0 ? 255 * delta / max : 0; if( hsb.s !== 0 ) { if( rgb.r === max ) { hsb.h = (rgb.g - rgb.b) / delta; } else if( rgb.g === max ) { hsb.h = 2 + (rgb.b - rgb.r) / delta; } else { hsb.h = 4 + (rgb.r - rgb.g) / delta; } } else { hsb.h = -1; } hsb.h *= 60; if( hsb.h < 0 ) { hsb.h += 360; } hsb.s *= 100/255; hsb.b *= 100/255; return hsb; } // Converts a hex string to an RGB object function hex2rgb(hex) { hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16); return { /* jshint ignore:start */ r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF) /* jshint ignore:end */ }; } // Handle events $(document) // Hide on clicks outside of the control .on('mousedown.minicolors touchstart.minicolors', function(event) { if( !$(event.target).parents().add(event.target).hasClass('minicolors') ) { hide(); } }) // Start moving .on('mousedown.minicolors touchstart.minicolors', '.minicolors-grid, .minicolors-slider, .minicolors-opacity-slider', function(event) { var target = $(this); event.preventDefault(); $(document).data('minicolors-target', target); move(target, event, true); }) // Move pickers .on('mousemove.minicolors touchmove.minicolors', function(event) { var target = $(document).data('minicolors-target'); if( target ) move(target, event); }) // Stop moving .on('mouseup.minicolors touchend.minicolors', function() { $(this).removeData('minicolors-target'); }) // Show panel when swatch is clicked .on('mousedown.minicolors touchstart.minicolors', '.minicolors-swatch', function(event) { var input = $(this).parent().find('.minicolors-input'); event.preventDefault(); show(input); }) // Show on focus .on('focus.minicolors', '.minicolors-input', function() { var input = $(this); if( !input.data('minicolors-initialized') ) return; show(input); }) // Fix hex on blur .on('blur.minicolors', '.minicolors-input', function() { var input = $(this), settings = input.data('minicolors-settings'); if( !input.data('minicolors-initialized') ) return; // Parse Hex input.val(parseHex(input.val(), true)); // Is it blank? if( input.val() === '' ) input.val(parseHex(settings.defaultValue, true)); // Adjust case input.val( convertCase(input.val(), settings.letterCase) ); }) // Handle keypresses .on('keydown.minicolors', '.minicolors-input', function(event) { var input = $(this); if( !input.data('minicolors-initialized') ) return; switch(event.keyCode) { case 9: // tab hide(); break; case 13: // enter case 27: // esc hide(); input.blur(); break; } }) // Update on keyup .on('keyup.minicolors', '.minicolors-input', function() { var input = $(this); if( !input.data('minicolors-initialized') ) return; updateFromInput(input, true); }) // Update on paste .on('paste.minicolors', '.minicolors-input', function() { var input = $(this); if( !input.data('minicolors-initialized') ) return; setTimeout( function() { updateFromInput(input, true); }, 1); }); }));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-minicolors.js
jquery-minicolors.js
(function(a){a.extend({progressBar:new function(){this.defaults={steps:20,step_duration:20,max:100,showText:true,textFormat:"percentage",width:120,height:12,callback:null,boxImage:"/--static--/ztfy.jqueryui/img/progressbar.gif",barImage:{0:"/--static--/ztfy.jqueryui/img/progressbg_red.gif",30:"/--static--/ztfy.jqueryui/img/progressbg_orange.gif",70:"/--static--/ztfy.jqueryui/img/progressbg_green.gif"},running_value:0,value:0,image:null};this.construct=function(c,b){var d=null;var e=null;if(c!=null){if(!isNaN(c)){d=c;if(b!=null){e=b}}else{e=c}}return this.each(function(f){var n=this;var h=this.config;if(d!=null&&this.bar!=null&&this.config!=null){this.config.value=d;if(e!=null){n.config=a.extend(this.config,e)}h=n.config}else{var l=a(this);var h=a.extend({},a.progressBar.defaults,e);h.id=l.attr("id")?l.attr("id"):Math.ceil(Math.random()*100000);if(d==null){d=l.html().replace("%","")}h.value=d;h.running_value=0;h.image=k(h);l.html("");var j=document.createElement("img");var p=document.createElement("span");var g=a(j);var m=a(p);n.bar=g;g.attr("id",h.id+"_pbImage");m.attr("id",h.id+"_pbText");m.html(o(h));g.attr("title",o(h));g.attr("alt",o(h));g.attr("src",h.boxImage);g.attr("width",h.width);g.css("width",h.width+"px");g.css("height",h.height+"px");g.css("background-image","url("+h.image+")");g.css("background-position",((h.width*-1))+"px 50%");g.css("padding","0");g.css("margin","0");l.append(g);l.append(m)}function i(r){return r.running_value*100/r.max}function k(r){var t=r.barImage;if(typeof(r.barImage)=="object"){for(var s in r.barImage){if(i(r)>=parseInt(s)){t=r.barImage[s]}else{break}}}return t}function o(r){if(r.showText){if(r.textFormat=="percentage"){return" "+Math.round(r.running_value)+"%"}else{if(r.textFormat=="fraction"){return" "+r.running_value+"/"+r.max}}}}h.increment=Math.round((h.value-h.running_value)/h.steps);if(h.increment<0){h.increment*=-1}if(h.increment<1){h.increment=1}var q=setInterval(function(){var v=h.width/100;var r=false;if(h.running_value>h.value){if(h.running_value-h.increment<h.value){h.running_value=h.value}else{h.running_value-=h.increment}}else{if(h.running_value<h.value){if(h.running_value+h.increment>h.value){h.running_value=h.value}else{h.running_value+=h.increment}}}if(h.running_value==h.value){clearInterval(q)}var u=a("#"+h.id+"_pbImage");var s=a("#"+h.id+"_pbText");var t=k(h);if(t!=h.image){u.css("background-image","url("+t+")");h.image=t}u.css("background-position",(((h.width*-1))+(i(h)*v))+"px 50%");u.attr("title",o(h));s.html(o(h));if(h.callback!=null&&typeof(h.callback)=="function"){h.callback(h)}n.config=h},h.step_duration)})};this.submit=function(f){var e=a("input:file",f);if(e.length>0){var h=a("iframe[name=progress]",f);if(h.length>0){var d="";for(var c=0;c<32;c++){d+=Math.floor(Math.random()*16).toString(16)}var g=a(f).attr("action");if(old_id=/X-Progress-ID=([^&]+)/.exec(g)){g=g.replace(old_id[1],d)}else{g=g+"?X-Progress-ID="+d}a(f).attr("action",g);var b=a(h).get(0).contentWindow.updateUploadProgress;if(b){b(d);return d}}}}}});a.fn.extend({progressBar:a.progressBar.construct})})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-progressbar.min.js
jquery-progressbar.min.js
* @summary Scroller * @description Virtual rendering for DataTables * @version 1.2.0 * @file dataTables.scroller.js * @author SpryMedia Ltd (www.sprymedia.co.uk) * @contact www.sprymedia.co.uk/contact * @copyright Copyright 2011-2014 SpryMedia Ltd. * * This source file is free software, available under the following license: * MIT license - http://datatables.net/license/mit * * 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 */ (function (window, document, undefined) { var factory = function ($, DataTable) { "use strict"; /** * Scroller is a virtual rendering plug-in for DataTables which allows large * datasets to be drawn on screen every quickly. What the virtual rendering means * is that only the visible portion of the table (and a bit to either side to make * the scrolling smooth) is drawn, while the scrolling container gives the * visual impression that the whole table is visible. This is done by making use * of the pagination abilities of DataTables and moving the table around in the * scrolling container DataTables adds to the page. The scrolling container is * forced to the height it would be for the full table display using an extra * element. * * Note that rows in the table MUST all be the same height. Information in a cell * which expands on to multiple lines will cause some odd behaviour in the scrolling. * * Scroller is initialised by simply including the letter 'S' in the sDom for the * table you want to have this feature enabled on. Note that the 'S' must come * AFTER the 't' parameter in `dom`. * * Key features include: * <ul class="limit_length"> * <li>Speed! The aim of Scroller for DataTables is to make rendering large data sets fast</li> * <li>Full compatibility with deferred rendering in DataTables 1.9 for maximum speed</li> * <li>Display millions of rows</li> * <li>Integration with state saving in DataTables (scrolling position is saved)</li> * <li>Easy to use</li> * </ul> * * @class * @constructor * @global * @param {object} oDT DataTables settings object * @param {object} [oOpts={}] Configuration object for FixedColumns. Options * are defined by {@link Scroller.defaults} * * @requires jQuery 1.7+ * @requires DataTables 1.9.0+ * * @example * $(document).ready(function() { * $('#example').dataTable( { * "sScrollY": "200px", * "sAjaxSource": "media/dataset/large.txt", * "sDom": "frtiS", * "bDeferRender": true * } ); * } ); */ var Scroller = function (oDTSettings, oOpts) { /* Sanity check - you just know it will happen */ if (!this instanceof Scroller) { alert("Scroller warning: Scroller must be initialised with the 'new' keyword."); return; } if (typeof oOpts == 'undefined') { oOpts = {}; } /** * Settings object which contains customisable information for the Scroller instance * @namespace * @private * @extends Scroller.defaults */ this.s = { /** * DataTables settings object * @type object * @default Passed in as first parameter to constructor */ "dt": oDTSettings, /** * Pixel location of the top of the drawn table in the viewport * @type int * @default 0 */ "tableTop": 0, /** * Pixel location of the bottom of the drawn table in the viewport * @type int * @default 0 */ "tableBottom": 0, /** * Pixel location of the boundary for when the next data set should be loaded and drawn * when scrolling up the way. * @type int * @default 0 * @private */ "redrawTop": 0, /** * Pixel location of the boundary for when the next data set should be loaded and drawn * when scrolling down the way. Note that this is actually caluated as the offset from * the top. * @type int * @default 0 * @private */ "redrawBottom": 0, /** * Auto row height or not indicator * @type bool * @default 0 */ "autoHeight": true, /** * Number of rows calculated as visible in the visible viewport * @type int * @default 0 */ "viewportRows": 0, /** * setTimeout reference for state saving, used when state saving is enabled in the DataTable * and when the user scrolls the viewport in order to stop the cookie set taking too much * CPU! * @type int * @default 0 */ "stateTO": null, /** * setTimeout reference for the redraw, used when server-side processing is enabled in the * DataTables in order to prevent DoSing the server * @type int * @default null */ "drawTO": null, heights: { jump: null, page: null, virtual: null, scroll: null, /** * Height of rows in the table * @type int * @default 0 */ row: null, /** * Pixel height of the viewport * @type int * @default 0 */ viewport: null }, topRowFloat: 0, scrollDrawDiff: null }; this.s = $.extend(this.s, Scroller.oDefaults, oOpts); /** * DOM elements used by the class instance * @private * @namespace * */ this.dom = { "force": document.createElement('div'), "scroller": null, "table": null }; /* Attach the instance to the DataTables instance so it can be accessed */ this.s.dt.oScroller = this; /* Let's do it */ this._fnConstruct(); }; Scroller.prototype = /** @lends Scroller.prototype */{ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Calculate the pixel position from the top of the scrolling container for * a given row * @param {int} iRow Row number to calculate the position of * @returns {int} Pixels * @example * $(document).ready(function() { * $('#example').dataTable( { * "sScrollY": "200px", * "sAjaxSource": "media/dataset/large.txt", * "sDom": "frtiS", * "bDeferRender": true, * "fnInitComplete": function (o) { * // Find where row 25 is * alert( o.oScroller.fnRowToPixels( 25 ) ); * } * } ); * } ); */ "fnRowToPixels": function (rowIdx, intParse, virtual) { var pixels; if (virtual) { pixels = this._domain('virtualToPhysical', rowIdx * this.s.heights.row); } else { var diff = rowIdx - this.s.baseRowTop; pixels = this.s.baseScrollTop + (diff * this.s.heights.row); } return intParse || intParse === undefined ? parseInt(pixels, 10) : pixels; }, /** * Calculate the row number that will be found at the given pixel position * (y-scroll). * * Please note that when the height of the full table exceeds 1 million * pixels, Scroller switches into a non-linear mode for the scrollbar to fit * all of the records into a finite area, but this function returns a linear * value (relative to the last non-linear positioning). * @param {int} iPixels Offset from top to calculate the row number of * @param {int} [intParse=true] If an integer value should be returned * @param {int} [virtual=false] Perform the calculations in the virtual domain * @returns {int} Row index * @example * $(document).ready(function() { * $('#example').dataTable( { * "sScrollY": "200px", * "sAjaxSource": "media/dataset/large.txt", * "sDom": "frtiS", * "bDeferRender": true, * "fnInitComplete": function (o) { * // Find what row number is at 500px * alert( o.oScroller.fnPixelsToRow( 500 ) ); * } * } ); * } ); */ "fnPixelsToRow": function (pixels, intParse, virtual) { var diff = pixels - this.s.baseScrollTop; var row = virtual ? this._domain('physicalToVirtual', pixels) / this.s.heights.row : ( diff / this.s.heights.row ) + this.s.baseRowTop; return intParse || intParse === undefined ? parseInt(row, 10) : row; }, /** * Calculate the row number that will be found at the given pixel position (y-scroll) * @param {int} iRow Row index to scroll to * @param {bool} [bAnimate=true] Animate the transision or not * @returns {void} * @example * $(document).ready(function() { * $('#example').dataTable( { * "sScrollY": "200px", * "sAjaxSource": "media/dataset/large.txt", * "sDom": "frtiS", * "bDeferRender": true, * "fnInitComplete": function (o) { * // Immediately scroll to row 1000 * o.oScroller.fnScrollToRow( 1000 ); * } * } ); * * // Sometime later on use the following to scroll to row 500... * var oSettings = $('#example').dataTable().fnSettings(); * oSettings.oScroller.fnScrollToRow( 500 ); * } ); */ "fnScrollToRow": function (iRow, bAnimate) { var that = this; var ani = false; var px = this.fnRowToPixels(iRow); // We need to know if the table will redraw or not before doing the // scroll. If it will not redraw, then we need to use the currently // displayed table, and scroll with the physical pixels. Otherwise, we // need to calculate the table's new position from the virtual // transform. var preRows = ((this.s.displayBuffer - 1) / 2) * this.s.viewportRows; var drawRow = iRow - preRows; if (drawRow < 0) { drawRow = 0; } if ((px > this.s.redrawBottom || px < this.s.redrawTop) && this.s.dt._iDisplayStart !== drawRow) { ani = true; px = this.fnRowToPixels(iRow, false, true); } if (typeof bAnimate == 'undefined' || bAnimate) { this.s.ani = ani; $(this.dom.scroller).animate({ "scrollTop": px }, function () { // This needs to happen after the animation has completed and // the final scroll event fired setTimeout(function () { that.s.ani = false; }, 0); }); } else { $(this.dom.scroller).scrollTop(px); } }, /** * Calculate and store information about how many rows are to be displayed * in the scrolling viewport, based on current dimensions in the browser's * rendering. This can be particularly useful if the table is initially * drawn in a hidden element - for example in a tab. * @param {bool} [bRedraw=true] Redraw the table automatically after the recalculation, with * the new dimentions forming the basis for the draw. * @returns {void} * @example * $(document).ready(function() { * // Make the example container hidden to throw off the browser's sizing * document.getElementById('container').style.display = "none"; * var oTable = $('#example').dataTable( { * "sScrollY": "200px", * "sAjaxSource": "media/dataset/large.txt", * "sDom": "frtiS", * "bDeferRender": true, * "fnInitComplete": function (o) { * // Immediately scroll to row 1000 * o.oScroller.fnScrollToRow( 1000 ); * } * } ); * * setTimeout( function () { * // Make the example container visible and recalculate the scroller sizes * document.getElementById('container').style.display = "block"; * oTable.fnSettings().oScroller.fnMeasure(); * }, 3000 ); */ "fnMeasure": function (bRedraw) { if (this.s.autoHeight) { this._fnCalcRowHeight(); } var heights = this.s.heights; heights.viewport = $(this.dom.scroller).height(); this.s.viewportRows = parseInt(heights.viewport / heights.row, 10) + 1; this.s.dt._iDisplayLength = this.s.viewportRows * this.s.displayBuffer; if (typeof bRedraw == 'undefined' || bRedraw) { this.s.dt.oInstance.fnDraw(); } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Initialisation for Scroller * @returns {void} * @private */ "_fnConstruct": function () { var that = this; /* Sanity check */ if (!this.s.dt.oFeatures.bPaginate) { this.s.dt.oApi._fnLog(this.s.dt, 0, 'Pagination must be enabled for Scroller'); return; } /* Insert a div element that we can use to force the DT scrolling container to * the height that would be required if the whole table was being displayed */ this.dom.force.style.position = "absolute"; this.dom.force.style.top = "0px"; this.dom.force.style.left = "0px"; this.dom.force.style.width = "1px"; this.dom.scroller = $('div.' + this.s.dt.oClasses.sScrollBody, this.s.dt.nTableWrapper)[0]; this.dom.scroller.appendChild(this.dom.force); this.dom.scroller.style.position = "relative"; this.dom.table = $('>table', this.dom.scroller)[0]; this.dom.table.style.position = "absolute"; this.dom.table.style.top = "0px"; this.dom.table.style.left = "0px"; // Add class to 'announce' that we are a Scroller table $(this.s.dt.nTableWrapper).addClass('DTS'); // Add a 'loading' indicator if (this.s.loadingIndicator) { $(this.dom.scroller.parentNode) .css('position', 'relative') .append('<div class="DTS_Loading">' + this.s.dt.oLanguage.sLoadingRecords + '</div>'); } /* Initial size calculations */ if (this.s.heights.row && this.s.heights.row != 'auto') { this.s.autoHeight = false; } this.fnMeasure(false); /* Scrolling callback to see if a page change is needed */ $(this.dom.scroller).on('scroll.DTS', function () { that._fnScroll.call(that); }); /* In iOS we catch the touchstart event incase the user tries to scroll * while the display is already scrolling */ $(this.dom.scroller).on('touchstart.DTS', function () { that._fnScroll.call(that); }); /* Update the scroller when the DataTable is redrawn */ this.s.dt.aoDrawCallback.push({ "fn": function () { if (that.s.dt.bInitialised) { that._fnDrawCallback.call(that); } }, "sName": "Scroller" }); /* On resize, update the information element, since the number of rows shown might change */ $(window).on('resize.DTS', function () { that._fnInfo(); }); /* Add a state saving parameter to the DT state saving so we can restore the exact * position of the scrolling */ var initialStateSave = true; this.s.dt.oApi._fnCallbackReg(this.s.dt, 'aoStateSaveParams', function (oS, oData) { /* Set iScroller to saved scroll position on initialization. */ if (initialStateSave && that.s.dt.oLoadedState) { oData.iScroller = that.s.dt.oLoadedState.iScroller; initialStateSave = false; } else { oData.iScroller = that.dom.scroller.scrollTop; } }, "Scroller_State"); /* Destructor */ this.s.dt.aoDestroyCallback.push({ "sName": "Scroller", "fn": function () { $(window).off('resize.DTS'); $(that.dom.scroller).off('touchstart.DTS scroll.DTS'); $(that.s.dt.nTableWrapper).removeClass('DTS'); $('div.DTS_Loading', that.dom.scroller.parentNode).remove(); that.dom.table.style.position = ""; that.dom.table.style.top = ""; that.dom.table.style.left = ""; } }); }, /** * Scrolling function - fired whenever the scrolling position is changed. * This method needs to use the stored values to see if the table should be * redrawn as we are moving towards the end of the information that is * currently drawn or not. If needed, then it will redraw the table based on * the new position. * @returns {void} * @private */ "_fnScroll": function () { var that = this, heights = this.s.heights, iScrollTop = this.dom.scroller.scrollTop, iTopRow; if (this.s.skip) { return; } /* If the table has been sorted or filtered, then we use the redraw that * DataTables as done, rather than performing our own */ if (this.s.dt.bFiltered || this.s.dt.bSorted) { this.s.lastScrollTop = 0; return; } /* Update the table's information display for what is now in the viewport */ this._fnInfo(); /* We don't want to state save on every scroll event - that's heavy * handed, so use a timeout to update the state saving only when the * scrolling has finished */ clearTimeout(this.s.stateTO); this.s.stateTO = setTimeout(function () { that.s.dt.oApi._fnSaveState(that.s.dt); }, 250); /* Check if the scroll point is outside the trigger boundary which would required * a DataTables redraw */ if (iScrollTop < this.s.redrawTop || iScrollTop > this.s.redrawBottom) { var preRows = ((this.s.displayBuffer - 1) / 2) * this.s.viewportRows; if (Math.abs(iScrollTop - this.s.lastScrollTop) > heights.viewport || this.s.ani) { iTopRow = parseInt(this._domain('physicalToVirtual', iScrollTop) / heights.row, 10) - preRows; this.s.topRowFloat = (this._domain('physicalToVirtual', iScrollTop) / heights.row); } else { iTopRow = this.fnPixelsToRow(iScrollTop) - preRows; this.s.topRowFloat = this.fnPixelsToRow(iScrollTop, false); } if (iTopRow <= 0) { /* At the start of the table */ iTopRow = 0; } else if (iTopRow + this.s.dt._iDisplayLength > this.s.dt.fnRecordsDisplay()) { /* At the end of the table */ iTopRow = this.s.dt.fnRecordsDisplay() - this.s.dt._iDisplayLength; if (iTopRow < 0) { iTopRow = 0; } } else if (iTopRow % 2 !== 0) { // For the row-striping classes (odd/even) we want only to start // on evens otherwise the stripes will change between draws and // look rubbish iTopRow++; } if (iTopRow != this.s.dt._iDisplayStart) { /* Cache the new table position for quick lookups */ this.s.tableTop = $(this.s.dt.nTable).offset().top; this.s.tableBottom = $(this.s.dt.nTable).height() + this.s.tableTop; var draw = function () { if (that.s.scrollDrawReq === null) { that.s.scrollDrawReq = iScrollTop; } that.s.dt._iDisplayStart = iTopRow; if (that.s.dt.oApi._fnCalculateEnd) { // Removed in 1.10 that.s.dt.oApi._fnCalculateEnd(that.s.dt); } that.s.dt.oApi._fnDraw(that.s.dt); }; /* Do the DataTables redraw based on the calculated start point - note that when * using server-side processing we introduce a small delay to not DoS the server... */ if (this.s.dt.oFeatures.bServerSide) { clearTimeout(this.s.drawTO); this.s.drawTO = setTimeout(draw, this.s.serverWait); } else { draw(); } } } this.s.lastScrollTop = iScrollTop; }, /** * Convert from one domain to another. The physical domain is the actual * pixel count on the screen, while the virtual is if we had browsers which * had scrolling containers of infinite height (i.e. the absolute value) * * @param {string} dir Domain transform direction, `virtualToPhysical` or * `physicalToVirtual` * @returns {number} Calculated transform * @private */ _domain: function (dir, val) { var heights = this.s.heights; var coeff; // If the virtual and physical height match, then we use a linear // transform between the two, allowing the scrollbar to be linear if (heights.virtual === heights.scroll) { coeff = (heights.virtual - heights.viewport) / (heights.scroll - heights.viewport); if (dir === 'virtualToPhysical') { return val / coeff; } else if (dir === 'physicalToVirtual') { return val * coeff; } } // Otherwise, we want a non-linear scrollbar to take account of the // redrawing regions at the start and end of the table, otherwise these // can stutter badly - on large tables 30px (for example) scroll might // be hundreds of rows, so the table would be redrawing every few px at // the start and end. Use a simple quadratic to stop this. It does mean // the scrollbar is non-linear, but with such massive data sets, the // scrollbar is going to be a best guess anyway var xMax = (heights.scroll - heights.viewport) / 2; var yMax = (heights.virtual - heights.viewport) / 2; coeff = yMax / ( xMax * xMax ); if (dir === 'virtualToPhysical') { if (val < yMax) { return Math.pow(val / coeff, 0.5); } else { val = (yMax * 2) - val; return val < 0 ? heights.scroll : (xMax * 2) - Math.pow(val / coeff, 0.5); } } else if (dir === 'physicalToVirtual') { if (val < xMax) { return val * val * coeff; } else { val = (xMax * 2) - val; return val < 0 ? heights.virtual : (yMax * 2) - (val * val * coeff); } } }, /** * Draw callback function which is fired when the DataTable is redrawn. The main function of * this method is to position the drawn table correctly the scrolling container for the rows * that is displays as a result of the scrolling position. * @returns {void} * @private */ "_fnDrawCallback": function () { var that = this, heights = this.s.heights, iScrollTop = this.dom.scroller.scrollTop, iActualScrollTop = iScrollTop, iScrollBottom = iScrollTop + heights.viewport, iTableHeight = $(this.s.dt.nTable).height(), displayStart = this.s.dt._iDisplayStart, displayLen = this.s.dt._iDisplayLength, displayEnd = this.s.dt.fnRecordsDisplay(); // Disable the scroll event listener while we are updating the DOM this.s.skip = true; // Resize the scroll forcing element this._fnScrollForce(); // Reposition the scrolling for the updated virtual position if needed if (displayStart === 0) { // Linear calculation at the top of the table iScrollTop = this.s.topRowFloat * heights.row; } else if (displayStart + displayLen >= displayEnd) { // Linear calculation that the bottom as well iScrollTop = heights.scroll - ((displayEnd - this.s.topRowFloat) * heights.row); } else { // Domain scaled in the middle iScrollTop = this._domain('virtualToPhysical', this.s.topRowFloat * heights.row); } this.dom.scroller.scrollTop = iScrollTop; // Store positional information so positional calculations can be based // upon the current table draw position this.s.baseScrollTop = iScrollTop; this.s.baseRowTop = this.s.topRowFloat; // Position the table in the virtual scroller var tableTop = iScrollTop - ((this.s.topRowFloat - displayStart) * heights.row); if (displayStart === 0) { tableTop = 0; } else if (displayStart + displayLen >= displayEnd) { tableTop = heights.scroll - iTableHeight; } this.dom.table.style.top = tableTop + 'px'; /* Cache some information for the scroller */ this.s.tableTop = tableTop; this.s.tableBottom = iTableHeight + this.s.tableTop; // Calculate the boundaries for where a redraw will be triggered by the // scroll event listener var boundaryPx = (iScrollTop - this.s.tableTop) * this.s.boundaryScale; this.s.redrawTop = iScrollTop - boundaryPx; this.s.redrawBottom = iScrollTop + boundaryPx; this.s.skip = false; // Because of the order of the DT callbacks, the info update will // take precidence over the one we want here. So a 'thread' break is // needed setTimeout(function () { that._fnInfo.call(that); }, 0); // Restore the scrolling position that was saved by DataTable's state // saving Note that this is done on the second draw when data is Ajax // sourced, and the first draw when DOM soured if (this.s.dt.oFeatures.bStateSave && this.s.dt.oLoadedState !== null && typeof this.s.dt.oLoadedState.iScroller != 'undefined') { var ajaxSourced = this.s.dt.sAjaxSource || that.s.dt.ajax ? true : false; if (( ajaxSourced && this.s.dt.iDraw == 2) || (!ajaxSourced && this.s.dt.iDraw == 1)) { setTimeout(function () { $(that.dom.scroller).scrollTop(that.s.dt.oLoadedState.iScroller); that.s.redrawTop = that.s.dt.oLoadedState.iScroller - (heights.viewport / 2); }, 0); } } }, /** * Force the scrolling container to have height beyond that of just the * table that has been drawn so the user can scroll the whole data set. * * Note that if the calculated required scrolling height exceeds a maximum * value (1 million pixels - hard-coded) the forcing element will be set * only to that maximum value and virtual / physical domain transforms will * be used to allow Scroller to display tables of any number of records. * @returns {void} * @private */ _fnScrollForce: function () { var heights = this.s.heights; var max = 1000000; heights.virtual = heights.row * this.s.dt.fnRecordsDisplay(); heights.scroll = heights.virtual; if (heights.scroll > max) { heights.scroll = max; } this.dom.force.style.height = heights.scroll + "px"; }, /** * Automatic calculation of table row height. This is just a little tricky here as using * initialisation DataTables has tale the table out of the document, so we need to create * a new table and insert it into the document, calculate the row height and then whip the * table out. * @returns {void} * @private */ "_fnCalcRowHeight": function () { var nTable = this.s.dt.nTable.cloneNode(false); var tbody = $('<tbody/>').appendTo(nTable); var container = $( '<div class="' + this.s.dt.oClasses.sWrapper + ' DTS">' + '<div class="' + this.s.dt.oClasses.sScrollWrapper + '">' + '<div class="' + this.s.dt.oClasses.sScrollBody + '"></div>' + '</div>' + '</div>' ); // Want 3 rows in the sizing table so :first-child and :last-child // CSS styles don't come into play - take the size of the middle row $('tbody tr:lt(4)', nTable).clone().appendTo(tbody); while ($('tr', tbody).length < 3) { tbody.append('<tr><td>&nbsp;</td></tr>'); } $('div.' + this.s.dt.oClasses.sScrollBody, container).append(nTable); container.appendTo('body'); this.s.heights.row = $('tr', tbody).eq(1).outerHeight(); container.remove(); }, /** * Update any information elements that are controlled by the DataTable based on the scrolling * viewport and what rows are visible in it. This function basically acts in the same way as * _fnUpdateInfo in DataTables, and effectively replaces that function. * @returns {void} * @private */ "_fnInfo": function () { if (!this.s.dt.oFeatures.bInfo) { return; } var dt = this.s.dt, iScrollTop = this.dom.scroller.scrollTop, iStart = Math.floor(this.fnPixelsToRow(iScrollTop, false, this.s.ani) + 1), iMax = dt.fnRecordsTotal(), iTotal = dt.fnRecordsDisplay(), iPossibleEnd = Math.ceil(this.fnPixelsToRow(iScrollTop + this.s.heights.viewport, false, this.s.ani)), iEnd = iTotal < iPossibleEnd ? iTotal : iPossibleEnd, sStart = dt.fnFormatNumber(iStart), sEnd = dt.fnFormatNumber(iEnd), sMax = dt.fnFormatNumber(iMax), sTotal = dt.fnFormatNumber(iTotal), sOut; if (dt.fnRecordsDisplay() === 0 && dt.fnRecordsDisplay() == dt.fnRecordsTotal()) { /* Empty record set */ sOut = dt.oLanguage.sInfoEmpty + dt.oLanguage.sInfoPostFix; } else if (dt.fnRecordsDisplay() === 0) { /* Rmpty record set after filtering */ sOut = dt.oLanguage.sInfoEmpty + ' ' + dt.oLanguage.sInfoFiltered.replace('_MAX_', sMax) + dt.oLanguage.sInfoPostFix; } else if (dt.fnRecordsDisplay() == dt.fnRecordsTotal()) { /* Normal record set */ sOut = dt.oLanguage.sInfo. replace('_START_', sStart). replace('_END_', sEnd). replace('_TOTAL_', sTotal) + dt.oLanguage.sInfoPostFix; } else { /* Record set after filtering */ sOut = dt.oLanguage.sInfo. replace('_START_', sStart). replace('_END_', sEnd). replace('_TOTAL_', sTotal) + ' ' + dt.oLanguage.sInfoFiltered.replace('_MAX_', dt.fnFormatNumber(dt.fnRecordsTotal())) + dt.oLanguage.sInfoPostFix; } var n = dt.aanFeatures.i; if (typeof n != 'undefined') { for (var i = 0, iLen = n.length; i < iLen; i++) { $(n[i]).html(sOut); } } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Statics * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Scroller default settings for initialisation * @namespace * @name Scroller.defaults * @static */ Scroller.defaults = { /** * Indicate if Scroller show show trace information on the console or not. This can be * useful when debugging Scroller or if just curious as to what it is doing, but should * be turned off for production. * @type bool * @default false * @static * @example * var oTable = $('#example').dataTable( { * "sScrollY": "200px", * "sDom": "frtiS", * "bDeferRender": true, * "oScroller": { * "trace": true * } * } ); */ "trace": false, /** * Scroller will attempt to automatically calculate the height of rows for it's internal * calculations. However the height that is used can be overridden using this parameter. * @type int|string * @default auto * @static * @example * var oTable = $('#example').dataTable( { * "sScrollY": "200px", * "sDom": "frtiS", * "bDeferRender": true, * "oScroller": { * "rowHeight": 30 * } * } ); */ "rowHeight": "auto", /** * When using server-side processing, Scroller will wait a small amount of time to allow * the scrolling to finish before requesting more data from the server. This prevents * you from DoSing your own server! The wait time can be configured by this parameter. * @type int * @default 200 * @static * @example * var oTable = $('#example').dataTable( { * "sScrollY": "200px", * "sDom": "frtiS", * "bDeferRender": true, * "oScroller": { * "serverWait": 100 * } * } ); */ "serverWait": 200, /** * The display buffer is what Scroller uses to calculate how many rows it should pre-fetch * for scrolling. Scroller automatically adjusts DataTables' display length to pre-fetch * rows that will be shown in "near scrolling" (i.e. just beyond the current display area). * The value is based upon the number of rows that can be displayed in the viewport (i.e. * a value of 1), and will apply the display range to records before before and after the * current viewport - i.e. a factor of 3 will allow Scroller to pre-fetch 1 viewport's worth * of rows before the current viewport, the current viewport's rows and 1 viewport's worth * of rows after the current viewport. Adjusting this value can be useful for ensuring * smooth scrolling based on your data set. * @type int * @default 7 * @static * @example * var oTable = $('#example').dataTable( { * "sScrollY": "200px", * "sDom": "frtiS", * "bDeferRender": true, * "oScroller": { * "displayBuffer": 10 * } * } ); */ "displayBuffer": 9, /** * Scroller uses the boundary scaling factor to decide when to redraw the table - which it * typically does before you reach the end of the currently loaded data set (in order to * allow the data to look continuous to a user scrolling through the data). If given as 0 * then the table will be redrawn whenever the viewport is scrolled, while 1 would not * redraw the table until the currently loaded data has all been shown. You will want * something in the middle - the default factor of 0.5 is usually suitable. * @type float * @default 0.5 * @static * @example * var oTable = $('#example').dataTable( { * "sScrollY": "200px", * "sDom": "frtiS", * "bDeferRender": true, * "oScroller": { * "boundaryScale": 0.75 * } * } ); */ "boundaryScale": 0.5, /** * Show (or not) the loading element in the background of the table. Note that you should * include the dataTables.scroller.css file for this to be displayed correctly. * @type boolean * @default false * @static * @example * var oTable = $('#example').dataTable( { * "sScrollY": "200px", * "sDom": "frtiS", * "bDeferRender": true, * "oScroller": { * "loadingIndicator": true * } * } ); */ "loadingIndicator": false }; Scroller.oDefaults = Scroller.defaults; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Scroller version * @type String * @default See code * @name Scroller.version * @static */ Scroller.version = "1.2.0"; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Register a new feature with DataTables */ if (typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.9.0')) { $.fn.dataTableExt.aoFeatures.push({ "fnInit": function (oDTSettings) { var init = oDTSettings.oInit; var opts = init.scroller || init.oScroller || {}; var oScroller = new Scroller(oDTSettings, opts); return oScroller.dom.wrapper; }, "cFeature": "S", "sFeature": "Scroller" }); } else { alert("Warning: Scroller requires DataTables 1.9.0 or greater - www.datatables.net/download"); } // Attach Scroller to DataTables so it can be accessed as an 'extra' $.fn.dataTable.Scroller = Scroller; $.fn.DataTable.Scroller = Scroller; // DataTables 1.10 API method aliases if ($.fn.dataTable.Api) { var Api = $.fn.dataTable.Api; Api.register('scroller().rowToPixels()', function (rowIdx, intParse, virtual) { var ctx = this.context; if (ctx.length && ctx[0].oScroller) { return ctx[0].oScroller.fnRowToPixels(rowIdx, intParse, virtual); } // undefined }); Api.register('scroller().pixelsToRow()', function (pixels, intParse, virtual) { var ctx = this.context; if (ctx.length && ctx[0].oScroller) { return ctx[0].oScroller.fnPixelsToRow(pixels, intParse, virtual); } // undefined }); Api.register('scroller().scrollToRow()', function (row, ani) { this.iterator('table', function (ctx) { if (ctx.oScroller) { ctx.oScroller.fnScrollToRow(row, ani); } }); return this; }); Api.register('scroller().measure()', function (redraw) { this.iterator('table', function (ctx) { if (ctx.oScroller) { ctx.oScroller.fnMeasure(redraw); } }); return this; }); } return Scroller; }; // /factory factory(jQuery, jQuery.fn.dataTable); })(window, document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-scroller.js
jquery-dataTables-scroller.js
(function (window, document, $, undefined) { "use strict"; var H = $("html"), W = $(window), D = $(document), F = $.fancybox = function () { F.open.apply( this, arguments ); }, IE = navigator.userAgent.match(/msie/i), didUpdate = null, isTouch = document.createTouch !== undefined, isQuery = function(obj) { return obj && obj.hasOwnProperty && obj instanceof $; }, isString = function(str) { return str && $.type(str) === "string"; }, isPercentage = function(str) { return isString(str) && str.indexOf('%') > 0; }, isScrollable = function(el) { return (el && !(el.style.overflow && el.style.overflow === 'hidden') && ((el.clientWidth && el.scrollWidth > el.clientWidth) || (el.clientHeight && el.scrollHeight > el.clientHeight))); }, getScalar = function(orig, dim) { var value = parseInt(orig, 10) || 0; if (dim && isPercentage(orig)) { value = F.getViewport()[ dim ] / 100 * value; } return Math.ceil(value); }, getValue = function(value, dim) { return getScalar(value, dim) + 'px'; }; $.extend(F, { // The current version of fancyBox version: '2.1.5', defaults: { padding : 15, margin : 20, width : 800, height : 600, minWidth : 100, minHeight : 100, maxWidth : 9999, maxHeight : 9999, pixelRatio: 1, // Set to 2 for retina display support autoSize : true, autoHeight : false, autoWidth : false, autoResize : true, autoCenter : !isTouch, fitToView : true, aspectRatio : false, topRatio : 0.5, leftRatio : 0.5, scrolling : 'auto', // 'auto', 'yes' or 'no' wrapCSS : '', arrows : true, closeBtn : true, closeClick : false, nextClick : false, mouseWheel : true, autoPlay : false, playSpeed : 3000, preload : 3, modal : false, loop : true, ajax : { dataType : 'html', headers : { 'X-fancyBox': true } }, iframe : { scrolling : 'auto', preload : true }, swf : { wmode: 'transparent', allowfullscreen : 'true', allowscriptaccess : 'always' }, keys : { next : { 13 : 'left', // enter 34 : 'up', // page down 39 : 'left', // right arrow 40 : 'up' // down arrow }, prev : { 8 : 'right', // backspace 33 : 'down', // page up 37 : 'right', // left arrow 38 : 'down' // up arrow }, close : [27], // escape key play : [32], // space - start/stop slideshow toggle : [70] // letter "f" - toggle fullscreen }, direction : { next : 'left', prev : 'right' }, scrollOutside : true, // Override some properties index : 0, type : null, href : null, content : null, title : null, // HTML templates tpl: { wrap : '<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>', image : '<img class="fancybox-image" src="{href}" alt="" />', iframe : '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen' + (IE ? ' allowtransparency="true"' : '') + '></iframe>', error : '<p class="fancybox-error">' + (MyAMS.plugins.i18n.fancybox.ERROR || 'The requested content cannot be loaded.') + '<br/>' + (MyAMS.plugins.i18n.fancybox.RETRY || 'Please try again later.') + '</p>', closeBtn : '<a title="'+ (MyAMS.plugins.i18n.fancybox.CLOSE || 'Close') + '" class="fancybox-item fancybox-close" href="javascript:;"></a>', next : '<a title="'+ (MyAMS.plugins.i18n.fancybox.NEXT || 'Next') + '" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>', prev : '<a title="'+ (MyAMS.plugins.i18n.fancybox.PREVIOUS || 'Previous') + '" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>' }, // Properties for each animation type // Opening fancyBox openEffect : 'fade', // 'elastic', 'fade' or 'none' openSpeed : 250, openEasing : 'swing', openOpacity : true, openMethod : 'zoomIn', // Closing fancyBox closeEffect : 'fade', // 'elastic', 'fade' or 'none' closeSpeed : 250, closeEasing : 'swing', closeOpacity : true, closeMethod : 'zoomOut', // Changing next gallery item nextEffect : 'elastic', // 'elastic', 'fade' or 'none' nextSpeed : 250, nextEasing : 'swing', nextMethod : 'changeIn', // Changing previous gallery item prevEffect : 'elastic', // 'elastic', 'fade' or 'none' prevSpeed : 250, prevEasing : 'swing', prevMethod : 'changeOut', // Enable default helpers helpers : { overlay : true, title : true }, // Callbacks onCancel : $.noop, // If canceling beforeLoad : $.noop, // Before loading afterLoad : $.noop, // After loading beforeShow : $.noop, // Before changing in current item afterShow : $.noop, // After opening beforeChange : $.noop, // Before changing gallery item beforeClose : $.noop, // Before closing afterClose : $.noop // After closing }, //Current state group : {}, // Selected group opts : {}, // Group options previous : null, // Previous element coming : null, // Element being loaded current : null, // Currently loaded element isActive : false, // Is activated isOpen : false, // Is currently open isOpened : false, // Have been fully opened at least once wrap : null, skin : null, outer : null, inner : null, player : { timer : null, isActive : false }, // Loaders ajaxLoad : null, imgPreload : null, // Some collections transitions : {}, helpers : {}, /* * Static methods */ open: function (group, opts) { if (!group) { return; } if (!$.isPlainObject(opts)) { opts = {}; } // Close if already active if (false === F.close(true)) { return; } // Normalize group if (!$.isArray(group)) { group = isQuery(group) ? $(group).get() : [group]; } // Recheck if the type of each element is `object` and set content type (image, ajax, etc) $.each(group, function(i, element) { var obj = {}, href, title, content, type, rez, hrefParts, selector; if ($.type(element) === "object") { // Check if is DOM element if (element.nodeType) { element = $(element); } if (isQuery(element)) { obj = { href : element.data('fancybox-href') || element.attr('href'), title : element.data('fancybox-title') || element.attr('title'), isDom : true, element : element }; if ($.metadata) { $.extend(true, obj, element.metadata()); } } else { obj = element; } } href = opts.href || obj.href || (isString(element) ? element : null); title = opts.title !== undefined ? opts.title : obj.title || ''; content = opts.content || obj.content; type = content ? 'html' : (opts.type || obj.type); if (!type && obj.isDom) { type = element.data('fancybox-type'); if (!type) { rez = element.prop('class').match(/fancybox\.(\w+)/); type = rez ? rez[1] : null; } } if (isString(href)) { // Try to guess the content type if (!type) { if (F.isImage(href)) { type = 'image'; } else if (F.isSWF(href)) { type = 'swf'; } else if (href.charAt(0) === '#') { type = 'inline'; } else if (isString(element)) { type = 'html'; content = element; } } // Split url into two pieces with source url and content selector, e.g, // "/mypage.html #my_id" will load "/mypage.html" and display element having id "my_id" if (type === 'ajax') { hrefParts = href.split(/\s+/, 2); href = hrefParts.shift(); selector = hrefParts.shift(); } } if (!content) { if (type === 'inline') { if (href) { content = $( isString(href) ? href.replace(/.*(?=#[^\s]+$)/, '') : href ); //strip for ie7 } else if (obj.isDom) { content = element; } } else if (type === 'html') { content = href; } else if (!type && !href && obj.isDom) { type = 'inline'; content = element; } } $.extend(obj, { href : href, type : type, content : content, title : title, selector : selector }); group[ i ] = obj; }); // Extend the defaults F.opts = $.extend(true, {}, F.defaults, opts); // All options are merged recursive except keys if (opts.keys !== undefined) { F.opts.keys = opts.keys ? $.extend({}, F.defaults.keys, opts.keys) : false; } F.group = group; return F._start(F.opts.index); }, // Cancel image loading or abort ajax request cancel: function () { var coming = F.coming; if (!coming || false === F.trigger('onCancel')) { return; } F.hideLoading(); if (F.ajaxLoad) { F.ajaxLoad.abort(); } F.ajaxLoad = null; if (F.imgPreload) { F.imgPreload.onload = F.imgPreload.onerror = null; } if (coming.wrap) { coming.wrap.stop(true, true).trigger('onReset').remove(); } F.coming = null; // If the first item has been canceled, then clear everything if (!F.current) { F._afterZoomOut( coming ); } }, // Start closing animation if is open; remove immediately if opening/closing close: function (event) { F.cancel(); if (false === F.trigger('beforeClose')) { return; } F.unbindEvents(); if (!F.isActive) { return; } if (!F.isOpen || event === true) { $('.fancybox-wrap').stop(true).trigger('onReset').remove(); F._afterZoomOut(); } else { F.isOpen = F.isOpened = false; F.isClosing = true; $('.fancybox-item, .fancybox-nav').remove(); F.wrap.stop(true, true).removeClass('fancybox-opened'); F.transitions[ F.current.closeMethod ](); } }, // Manage slideshow: // $.fancybox.play(); - toggle slideshow // $.fancybox.play( true ); - start // $.fancybox.play( false ); - stop play: function ( action ) { var clear = function () { clearTimeout(F.player.timer); }, set = function () { clear(); if (F.current && F.player.isActive) { F.player.timer = setTimeout(F.next, F.current.playSpeed); } }, stop = function () { clear(); D.unbind('.player'); F.player.isActive = false; F.trigger('onPlayEnd'); }, start = function () { if (F.current && (F.current.loop || F.current.index < F.group.length - 1)) { F.player.isActive = true; D.bind({ 'onCancel.player beforeClose.player' : stop, 'onUpdate.player' : set, 'beforeLoad.player' : clear }); set(); F.trigger('onPlayStart'); } }; if (action === true || (!F.player.isActive && action !== false)) { start(); } else { stop(); } }, // Navigate to next gallery item next: function ( direction ) { var current = F.current; if (current) { if (!isString(direction)) { direction = current.direction.next; } F.jumpto(current.index + 1, direction, 'next'); } }, // Navigate to previous gallery item prev: function ( direction ) { var current = F.current; if (current) { if (!isString(direction)) { direction = current.direction.prev; } F.jumpto(current.index - 1, direction, 'prev'); } }, // Navigate to gallery item by index jumpto: function ( index, direction, router ) { var current = F.current; if (!current) { return; } index = getScalar(index); F.direction = direction || current.direction[ (index >= current.index ? 'next' : 'prev') ]; F.router = router || 'jumpto'; if (current.loop) { if (index < 0) { index = current.group.length + (index % current.group.length); } index = index % current.group.length; } if (current.group[ index ] !== undefined) { F.cancel(); F._start(index); } }, // Center inside viewport and toggle position type to fixed or absolute if needed reposition: function (e, onlyAbsolute) { var current = F.current, wrap = current ? current.wrap : null, pos; if (wrap) { pos = F._getPosition(onlyAbsolute); if (e && e.type === 'scroll') { delete pos.position; wrap.stop(true, true).animate(pos, 200); } else { wrap.css(pos); current.pos = $.extend({}, current.dim, pos); } } }, update: function (e) { var type = (e && e.type), anyway = !type || type === 'orientationchange'; if (anyway) { clearTimeout(didUpdate); didUpdate = null; } if (!F.isOpen || didUpdate) { return; } didUpdate = setTimeout(function() { var current = F.current; if (!current || F.isClosing) { return; } F.wrap.removeClass('fancybox-tmp'); if (anyway || type === 'load' || (type === 'resize' && current.autoResize)) { F._setDimension(); } if (!(type === 'scroll' && current.canShrink)) { F.reposition(e); } F.trigger('onUpdate'); didUpdate = null; }, (anyway && !isTouch ? 0 : 300)); }, // Shrink content to fit inside viewport or restore if resized toggle: function ( action ) { if (F.isOpen) { F.current.fitToView = $.type(action) === "boolean" ? action : !F.current.fitToView; // Help browser to restore document dimensions if (isTouch) { F.wrap.removeAttr('style').addClass('fancybox-tmp'); F.trigger('onUpdate'); } F.update(); } }, hideLoading: function () { D.unbind('.loading'); $('#fancybox-loading').remove(); }, showLoading: function () { var el, viewport; F.hideLoading(); el = $('<div id="fancybox-loading"><div></div></div>').click(F.cancel).appendTo('body'); // If user will press the escape-button, the request will be canceled D.bind('keydown.loading', function(e) { if ((e.which || e.keyCode) === 27) { e.preventDefault(); F.cancel(); } }); if (!F.defaults.fixed) { viewport = F.getViewport(); el.css({ position : 'absolute', top : (viewport.h * 0.5) + viewport.y, left : (viewport.w * 0.5) + viewport.x }); } }, getViewport: function () { var locked = (F.current && F.current.locked) || false, rez = { x: W.scrollLeft(), y: W.scrollTop() }; if (locked) { rez.w = locked[0].clientWidth; rez.h = locked[0].clientHeight; } else { // See http://bugs.jquery.com/ticket/6724 rez.w = isTouch && window.innerWidth ? window.innerWidth : W.width(); rez.h = isTouch && window.innerHeight ? window.innerHeight : W.height(); } return rez; }, // Unbind the keyboard / clicking actions unbindEvents: function () { if (F.wrap && isQuery(F.wrap)) { F.wrap.unbind('.fb'); } D.unbind('.fb'); W.unbind('.fb'); }, bindEvents: function () { var current = F.current, keys; if (!current) { return; } // Changing document height on iOS devices triggers a 'resize' event, // that can change document height... repeating infinitely W.bind('orientationchange.fb' + (isTouch ? '' : ' resize.fb') + (current.autoCenter && !current.locked ? ' scroll.fb' : ''), F.update); keys = current.keys; if (keys) { D.bind('keydown.fb', function (e) { var code = e.which || e.keyCode, target = e.target || e.srcElement; // Skip esc key if loading, because showLoading will cancel preloading if (code === 27 && F.coming) { return false; } // Ignore key combinations and key events within form elements if (!e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey && !(target && (target.type || $(target).is('[contenteditable]')))) { $.each(keys, function(i, val) { if (current.group.length > 1 && val[ code ] !== undefined) { F[ i ]( val[ code ] ); e.preventDefault(); return false; } if ($.inArray(code, val) > -1) { F[ i ] (); e.preventDefault(); return false; } }); } }); } if ($.fn.mousewheel && current.mouseWheel) { F.wrap.bind('mousewheel.fb', function (e, delta, deltaX, deltaY) { var target = e.target || null, parent = $(target), canScroll = false; while (parent.length) { if (canScroll || parent.is('.fancybox-skin') || parent.is('.fancybox-wrap')) { break; } canScroll = isScrollable( parent[0] ); parent = $(parent).parent(); } if (delta !== 0 && !canScroll) { if (F.group.length > 1 && !current.canShrink) { if (deltaY > 0 || deltaX > 0) { F.prev( deltaY > 0 ? 'down' : 'left' ); } else if (deltaY < 0 || deltaX < 0) { F.next( deltaY < 0 ? 'up' : 'right' ); } e.preventDefault(); } } }); } }, trigger: function (event, o) { var ret, obj = o || F.coming || F.current; if (!obj) { return; } if ($.isFunction( obj[event] )) { ret = obj[event].apply(obj, Array.prototype.slice.call(arguments, 1)); } if (ret === false) { return false; } if (obj.helpers) { $.each(obj.helpers, function (helper, opts) { if (opts && F.helpers[helper] && $.isFunction(F.helpers[helper][event])) { F.helpers[helper][event]($.extend(true, {}, F.helpers[helper].defaults, opts), obj); } }); } D.trigger(event); }, isImage: function (str) { return isString(str) && str.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i); }, isSWF: function (str) { return isString(str) && str.match(/\.(swf)((\?|#).*)?$/i); }, _start: function (index) { var coming = {}, obj, href, type, margin, padding; index = getScalar( index ); obj = F.group[ index ] || null; if (!obj) { return false; } coming = $.extend(true, {}, F.opts, obj); // Convert margin and padding properties to array - top, right, bottom, left margin = coming.margin; padding = coming.padding; if ($.type(margin) === 'number') { coming.margin = [margin, margin, margin, margin]; } if ($.type(padding) === 'number') { coming.padding = [padding, padding, padding, padding]; } // 'modal' propery is just a shortcut if (coming.modal) { $.extend(true, coming, { closeBtn : false, closeClick : false, nextClick : false, arrows : false, mouseWheel : false, keys : null, helpers: { overlay : { closeClick : false } } }); } // 'autoSize' property is a shortcut, too if (coming.autoSize) { coming.autoWidth = coming.autoHeight = true; } if (coming.width === 'auto') { coming.autoWidth = true; } if (coming.height === 'auto') { coming.autoHeight = true; } /* * Add reference to the group, so it`s possible to access from callbacks, example: * afterLoad : function() { * this.title = 'Image ' + (this.index + 1) + ' of ' + this.group.length + (this.title ? ' - ' + this.title : ''); * } */ coming.group = F.group; coming.index = index; // Give a chance for callback or helpers to update coming item (type, title, etc) F.coming = coming; if (false === F.trigger('beforeLoad')) { F.coming = null; return; } type = coming.type; href = coming.href; if (!type) { F.coming = null; //If we can not determine content type then drop silently or display next/prev item if looping through gallery if (F.current && F.router && F.router !== 'jumpto') { F.current.index = index; return F[ F.router ]( F.direction ); } return false; } F.isActive = true; if (type === 'image' || type === 'swf') { coming.autoHeight = coming.autoWidth = false; coming.scrolling = 'visible'; } if (type === 'image') { coming.aspectRatio = true; } if (type === 'iframe' && isTouch) { coming.scrolling = 'scroll'; } // Build the neccessary markup coming.wrap = $(coming.tpl.wrap).addClass('fancybox-' + (isTouch ? 'mobile' : 'desktop') + ' fancybox-type-' + type + ' fancybox-tmp ' + coming.wrapCSS).appendTo( coming.parent || 'body' ); $.extend(coming, { skin : $('.fancybox-skin', coming.wrap), outer : $('.fancybox-outer', coming.wrap), inner : $('.fancybox-inner', coming.wrap) }); $.each(["Top", "Right", "Bottom", "Left"], function(i, v) { coming.skin.css('padding' + v, getValue(coming.padding[ i ])); }); F.trigger('onReady'); // Check before try to load; 'inline' and 'html' types need content, others - href if (type === 'inline' || type === 'html') { if (!coming.content || !coming.content.length) { return F._error( 'content' ); } } else if (!href) { return F._error( 'href' ); } if (type === 'image') { F._loadImage(); } else if (type === 'ajax') { F._loadAjax(); } else if (type === 'iframe') { F._loadIframe(); } else { F._afterLoad(); } }, _error: function ( type ) { $.extend(F.coming, { type : 'html', autoWidth : true, autoHeight : true, minWidth : 0, minHeight : 0, scrolling : 'no', hasError : type, content : F.coming.tpl.error }); F._afterLoad(); }, _loadImage: function () { // Reset preload image so it is later possible to check "complete" property var img = F.imgPreload = new Image(); img.onload = function () { this.onload = this.onerror = null; F.coming.width = this.width / F.opts.pixelRatio; F.coming.height = this.height / F.opts.pixelRatio; F._afterLoad(); }; img.onerror = function () { this.onload = this.onerror = null; F._error( 'image' ); }; img.src = F.coming.href; if (img.complete !== true) { F.showLoading(); } }, _loadAjax: function () { var coming = F.coming; F.showLoading(); F.ajaxLoad = $.ajax($.extend({}, coming.ajax, { url: coming.href, error: function (jqXHR, textStatus) { if (F.coming && textStatus !== 'abort') { F._error( 'ajax', jqXHR ); } else { F.hideLoading(); } }, success: function (data, textStatus) { if (textStatus === 'success') { coming.content = data; F._afterLoad(); } } })); }, _loadIframe: function() { var coming = F.coming, iframe = $(coming.tpl.iframe.replace(/\{rnd\}/g, new Date().getTime())) .attr('scrolling', isTouch ? 'auto' : coming.iframe.scrolling) .attr('src', coming.href); // This helps IE $(coming.wrap).bind('onReset', function () { try { $(this).find('iframe').hide().attr('src', '//about:blank').end().empty(); } catch (e) {} }); if (coming.iframe.preload) { F.showLoading(); iframe.one('load', function() { $(this).data('ready', 1); // iOS will lose scrolling if we resize if (!isTouch) { $(this).bind('load.fb', F.update); } // Without this trick: // - iframe won't scroll on iOS devices // - IE7 sometimes displays empty iframe $(this).parents('.fancybox-wrap').width('100%').removeClass('fancybox-tmp').show(); F._afterLoad(); }); } coming.content = iframe.appendTo( coming.inner ); if (!coming.iframe.preload) { F._afterLoad(); } }, _preloadImages: function() { var group = F.group, current = F.current, len = group.length, cnt = current.preload ? Math.min(current.preload, len - 1) : 0, item, i; for (i = 1; i <= cnt; i += 1) { item = group[ (current.index + i ) % len ]; if (item.type === 'image' && item.href) { new Image().src = item.href; } } }, _afterLoad: function () { var coming = F.coming, previous = F.current, placeholder = 'fancybox-placeholder', current, content, type, scrolling, href, embed; F.hideLoading(); if (!coming || F.isActive === false) { return; } if (false === F.trigger('afterLoad', coming, previous)) { coming.wrap.stop(true).trigger('onReset').remove(); F.coming = null; return; } if (previous) { F.trigger('beforeChange', previous); previous.wrap.stop(true).removeClass('fancybox-opened') .find('.fancybox-item, .fancybox-nav') .remove(); } F.unbindEvents(); current = coming; content = coming.content; type = coming.type; scrolling = coming.scrolling; $.extend(F, { wrap : current.wrap, skin : current.skin, outer : current.outer, inner : current.inner, current : current, previous : previous }); href = current.href; switch (type) { case 'inline': case 'ajax': case 'html': if (current.selector) { content = $('<div>').html(content).find(current.selector); } else if (isQuery(content)) { if (!content.data(placeholder)) { content.data(placeholder, $('<div class="' + placeholder + '"></div>').insertAfter( content ).hide() ); } content = content.show().detach(); current.wrap.bind('onReset', function () { if ($(this).find(content).length) { content.hide().replaceAll( content.data(placeholder) ).data(placeholder, false); } }); } break; case 'image': content = current.tpl.image.replace('{href}', href); break; case 'swf': content = '<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="' + href + '"></param>'; embed = ''; $.each(current.swf, function(name, val) { content += '<param name="' + name + '" value="' + val + '"></param>'; embed += ' ' + name + '="' + val + '"'; }); content += '<embed src="' + href + '" type="application/x-shockwave-flash" width="100%" height="100%"' + embed + '></embed></object>'; break; } if (!(isQuery(content) && content.parent().is(current.inner))) { current.inner.append( content ); } // Give a chance for helpers or callbacks to update elements F.trigger('beforeShow'); // Set scrolling before calculating dimensions current.inner.css('overflow', scrolling === 'yes' ? 'scroll' : (scrolling === 'no' ? 'hidden' : scrolling)); // Set initial dimensions and start position F._setDimension(); F.reposition(); F.isOpen = false; F.coming = null; F.bindEvents(); if (!F.isOpened) { $('.fancybox-wrap').not( current.wrap ).stop(true).trigger('onReset').remove(); } else if (previous.prevMethod) { F.transitions[ previous.prevMethod ](); } F.transitions[ F.isOpened ? current.nextMethod : current.openMethod ](); F._preloadImages(); }, _setDimension: function () { var viewport = F.getViewport(), steps = 0, canShrink = false, canExpand = false, wrap = F.wrap, skin = F.skin, inner = F.inner, current = F.current, width = current.width, height = current.height, minWidth = current.minWidth, minHeight = current.minHeight, maxWidth = current.maxWidth, maxHeight = current.maxHeight, scrolling = current.scrolling, scrollOut = current.scrollOutside ? current.scrollbarWidth : 0, margin = current.margin, wMargin = getScalar(margin[1] + margin[3]), hMargin = getScalar(margin[0] + margin[2]), wPadding, hPadding, wSpace, hSpace, origWidth, origHeight, origMaxWidth, origMaxHeight, ratio, width_, height_, maxWidth_, maxHeight_, iframe, body; // Reset dimensions so we could re-check actual size wrap.add(skin).add(inner).width('auto').height('auto').removeClass('fancybox-tmp'); wPadding = getScalar(skin.outerWidth(true) - skin.width()); hPadding = getScalar(skin.outerHeight(true) - skin.height()); // Any space between content and viewport (margin, padding, border, title) wSpace = wMargin + wPadding; hSpace = hMargin + hPadding; origWidth = isPercentage(width) ? (viewport.w - wSpace) * getScalar(width) / 100 : width; origHeight = isPercentage(height) ? (viewport.h - hSpace) * getScalar(height) / 100 : height; if (current.type === 'iframe') { iframe = current.content; if (current.autoHeight && iframe.data('ready') === 1) { try { if (iframe[0].contentWindow.document.location) { inner.width( origWidth ).height(9999); body = iframe.contents().find('body'); if (scrollOut) { body.css('overflow-x', 'hidden'); } origHeight = body.outerHeight(true); } } catch (e) {} } } else if (current.autoWidth || current.autoHeight) { inner.addClass( 'fancybox-tmp' ); // Set width or height in case we need to calculate only one dimension if (!current.autoWidth) { inner.width( origWidth ); } if (!current.autoHeight) { inner.height( origHeight ); } if (current.autoWidth) { origWidth = inner.width(); } if (current.autoHeight) { origHeight = inner.height(); } inner.removeClass( 'fancybox-tmp' ); } width = getScalar( origWidth ); height = getScalar( origHeight ); ratio = origWidth / origHeight; // Calculations for the content minWidth = getScalar(isPercentage(minWidth) ? getScalar(minWidth, 'w') - wSpace : minWidth); maxWidth = getScalar(isPercentage(maxWidth) ? getScalar(maxWidth, 'w') - wSpace : maxWidth); minHeight = getScalar(isPercentage(minHeight) ? getScalar(minHeight, 'h') - hSpace : minHeight); maxHeight = getScalar(isPercentage(maxHeight) ? getScalar(maxHeight, 'h') - hSpace : maxHeight); // These will be used to determine if wrap can fit in the viewport origMaxWidth = maxWidth; origMaxHeight = maxHeight; if (current.fitToView) { maxWidth = Math.min(viewport.w - wSpace, maxWidth); maxHeight = Math.min(viewport.h - hSpace, maxHeight); } maxWidth_ = viewport.w - wMargin; maxHeight_ = viewport.h - hMargin; if (current.aspectRatio) { if (width > maxWidth) { width = maxWidth; height = getScalar(width / ratio); } if (height > maxHeight) { height = maxHeight; width = getScalar(height * ratio); } if (width < minWidth) { width = minWidth; height = getScalar(width / ratio); } if (height < minHeight) { height = minHeight; width = getScalar(height * ratio); } } else { width = Math.max(minWidth, Math.min(width, maxWidth)); if (current.autoHeight && current.type !== 'iframe') { inner.width( width ); height = inner.height(); } height = Math.max(minHeight, Math.min(height, maxHeight)); } // Try to fit inside viewport (including the title) if (current.fitToView) { inner.width( width ).height( height ); wrap.width( width + wPadding ); // Real wrap dimensions width_ = wrap.width(); height_ = wrap.height(); if (current.aspectRatio) { while ((width_ > maxWidth_ || height_ > maxHeight_) && width > minWidth && height > minHeight) { if (steps++ > 19) { break; } height = Math.max(minHeight, Math.min(maxHeight, height - 10)); width = getScalar(height * ratio); if (width < minWidth) { width = minWidth; height = getScalar(width / ratio); } if (width > maxWidth) { width = maxWidth; height = getScalar(width / ratio); } inner.width( width ).height( height ); wrap.width( width + wPadding ); width_ = wrap.width(); height_ = wrap.height(); } } else { width = Math.max(minWidth, Math.min(width, width - (width_ - maxWidth_))); height = Math.max(minHeight, Math.min(height, height - (height_ - maxHeight_))); } } if (scrollOut && scrolling === 'auto' && height < origHeight && (width + wPadding + scrollOut) < maxWidth_) { width += scrollOut; } inner.width( width ).height( height ); wrap.width( width + wPadding ); width_ = wrap.width(); height_ = wrap.height(); canShrink = (width_ > maxWidth_ || height_ > maxHeight_) && width > minWidth && height > minHeight; canExpand = current.aspectRatio ? (width < origMaxWidth && height < origMaxHeight && width < origWidth && height < origHeight) : ((width < origMaxWidth || height < origMaxHeight) && (width < origWidth || height < origHeight)); $.extend(current, { dim : { width : getValue( width_ ), height : getValue( height_ ) }, origWidth : origWidth, origHeight : origHeight, canShrink : canShrink, canExpand : canExpand, wPadding : wPadding, hPadding : hPadding, wrapSpace : height_ - skin.outerHeight(true), skinSpace : skin.height() - height }); if (!iframe && current.autoHeight && height > minHeight && height < maxHeight && !canExpand) { inner.height('auto'); } }, _getPosition: function (onlyAbsolute) { var current = F.current, viewport = F.getViewport(), margin = current.margin, width = F.wrap.width() + margin[1] + margin[3], height = F.wrap.height() + margin[0] + margin[2], rez = { position: 'absolute', top : margin[0], left : margin[3] }; if (current.autoCenter && current.fixed && !onlyAbsolute && height <= viewport.h && width <= viewport.w) { rez.position = 'fixed'; } else if (!current.locked) { rez.top += viewport.y; rez.left += viewport.x; } rez.top = getValue(Math.max(rez.top, rez.top + ((viewport.h - height) * current.topRatio))); rez.left = getValue(Math.max(rez.left, rez.left + ((viewport.w - width) * current.leftRatio))); return rez; }, _afterZoomIn: function () { var current = F.current; if (!current) { return; } F.isOpen = F.isOpened = true; F.wrap.css('overflow', 'visible').addClass('fancybox-opened'); F.update(); // Assign a click event if ( current.closeClick || (current.nextClick && F.group.length > 1) ) { F.inner.css('cursor', 'pointer').bind('click.fb', function(e) { if (!$(e.target).is('a') && !$(e.target).parent().is('a')) { e.preventDefault(); F[ current.closeClick ? 'close' : 'next' ](); } }); } // Create a close button if (current.closeBtn) { $(current.tpl.closeBtn).appendTo(F.skin).bind('click.fb', function(e) { e.preventDefault(); F.close(); }); } // Create navigation arrows if (current.arrows && F.group.length > 1) { if (current.loop || current.index > 0) { $(current.tpl.prev).appendTo(F.outer).bind('click.fb', F.prev); } if (current.loop || current.index < F.group.length - 1) { $(current.tpl.next).appendTo(F.outer).bind('click.fb', F.next); } } F.trigger('afterShow'); // Stop the slideshow if this is the last item if (!current.loop && current.index === current.group.length - 1) { F.play( false ); } else if (F.opts.autoPlay && !F.player.isActive) { F.opts.autoPlay = false; F.play(); } }, _afterZoomOut: function ( obj ) { obj = obj || F.current; $('.fancybox-wrap').trigger('onReset').remove(); $.extend(F, { group : {}, opts : {}, router : false, current : null, isActive : false, isOpened : false, isOpen : false, isClosing : false, wrap : null, skin : null, outer : null, inner : null }); F.trigger('afterClose', obj); } }); /* * Default transitions */ F.transitions = { getOrigPosition: function () { var current = F.current, element = current.element, orig = current.orig, pos = {}, width = 50, height = 50, hPadding = current.hPadding, wPadding = current.wPadding, viewport = F.getViewport(); if (!orig && current.isDom && element.is(':visible')) { orig = element.find('img:first'); if (!orig.length) { orig = element; } } if (isQuery(orig)) { pos = orig.offset(); if (orig.is('img')) { width = orig.outerWidth(); height = orig.outerHeight(); } } else { pos.top = viewport.y + (viewport.h - height) * current.topRatio; pos.left = viewport.x + (viewport.w - width) * current.leftRatio; } if (F.wrap.css('position') === 'fixed' || current.locked) { pos.top -= viewport.y; pos.left -= viewport.x; } pos = { top : getValue(pos.top - hPadding * current.topRatio), left : getValue(pos.left - wPadding * current.leftRatio), width : getValue(width + wPadding), height : getValue(height + hPadding) }; return pos; }, step: function (now, fx) { var ratio, padding, value, prop = fx.prop, current = F.current, wrapSpace = current.wrapSpace, skinSpace = current.skinSpace; if (prop === 'width' || prop === 'height') { ratio = fx.end === fx.start ? 1 : (now - fx.start) / (fx.end - fx.start); if (F.isClosing) { ratio = 1 - ratio; } padding = prop === 'width' ? current.wPadding : current.hPadding; value = now - padding; F.skin[ prop ]( getScalar( prop === 'width' ? value : value - (wrapSpace * ratio) ) ); F.inner[ prop ]( getScalar( prop === 'width' ? value : value - (wrapSpace * ratio) - (skinSpace * ratio) ) ); } }, zoomIn: function () { var current = F.current, startPos = current.pos, effect = current.openEffect, elastic = effect === 'elastic', endPos = $.extend({opacity : 1}, startPos); // Remove "position" property that breaks older IE delete endPos.position; if (elastic) { startPos = this.getOrigPosition(); if (current.openOpacity) { startPos.opacity = 0.1; } } else if (effect === 'fade') { startPos.opacity = 0.1; } F.wrap.css(startPos).animate(endPos, { duration : effect === 'none' ? 0 : current.openSpeed, easing : current.openEasing, step : elastic ? this.step : null, complete : F._afterZoomIn }); }, zoomOut: function () { var current = F.current, effect = current.closeEffect, elastic = effect === 'elastic', endPos = {opacity : 0.1}; if (elastic) { endPos = this.getOrigPosition(); if (current.closeOpacity) { endPos.opacity = 0.1; } } F.wrap.animate(endPos, { duration : effect === 'none' ? 0 : current.closeSpeed, easing : current.closeEasing, step : elastic ? this.step : null, complete : F._afterZoomOut }); }, changeIn: function () { var current = F.current, effect = current.nextEffect, startPos = current.pos, endPos = { opacity : 1 }, direction = F.direction, distance = 200, field; startPos.opacity = 0.1; if (effect === 'elastic') { field = direction === 'down' || direction === 'up' ? 'top' : 'left'; if (direction === 'down' || direction === 'right') { startPos[ field ] = getValue(getScalar(startPos[ field ]) - distance); endPos[ field ] = '+=' + distance + 'px'; } else { startPos[ field ] = getValue(getScalar(startPos[ field ]) + distance); endPos[ field ] = '-=' + distance + 'px'; } } // Workaround for http://bugs.jquery.com/ticket/12273 if (effect === 'none') { F._afterZoomIn(); } else { F.wrap.css(startPos).animate(endPos, { duration : current.nextSpeed, easing : current.nextEasing, complete : F._afterZoomIn }); } }, changeOut: function () { var previous = F.previous, effect = previous.prevEffect, endPos = { opacity : 0.1 }, direction = F.direction, distance = 200; if (effect === 'elastic') { endPos[ direction === 'down' || direction === 'up' ? 'top' : 'left' ] = ( direction === 'up' || direction === 'left' ? '-' : '+' ) + '=' + distance + 'px'; } previous.wrap.animate(endPos, { duration : effect === 'none' ? 0 : previous.prevSpeed, easing : previous.prevEasing, complete : function () { $(this).trigger('onReset').remove(); } }); } }; /* * Overlay helper */ F.helpers.overlay = { defaults : { closeClick : true, // if true, fancyBox will be closed when user clicks on the overlay speedOut : 200, // duration of fadeOut animation showEarly : true, // indicates if should be opened immediately or wait until the content is ready css : {}, // custom CSS properties locked : !isTouch, // if true, the content will be locked into overlay fixed : true // if false, the overlay CSS position property will not be set to "fixed" }, overlay : null, // current handle fixed : false, // indicates if the overlay has position "fixed" el : $('html'), // element that contains "the lock" // Public methods create : function(opts) { opts = $.extend({}, this.defaults, opts); if (this.overlay) { this.close(); } this.overlay = $('<div class="fancybox-overlay"></div>').appendTo( F.coming ? F.coming.parent : opts.parent ); this.fixed = false; if (opts.fixed && F.defaults.fixed) { this.overlay.addClass('fancybox-overlay-fixed'); this.fixed = true; } }, open : function(opts) { var that = this; opts = $.extend({}, this.defaults, opts); if (this.overlay) { this.overlay.unbind('.overlay').width('auto').height('auto'); } else { this.create(opts); } if (!this.fixed) { W.bind('resize.overlay', $.proxy( this.update, this) ); this.update(); } if (opts.closeClick) { this.overlay.bind('click.overlay', function(e) { if ($(e.target).hasClass('fancybox-overlay')) { if (F.isActive) { F.close(); } else { that.close(); } return false; } }); } this.overlay.css( opts.css ).show(); }, close : function() { var scrollV, scrollH; W.unbind('resize.overlay'); if (this.el.hasClass('fancybox-lock')) { $('.fancybox-margin').removeClass('fancybox-margin'); scrollV = W.scrollTop(); scrollH = W.scrollLeft(); this.el.removeClass('fancybox-lock'); W.scrollTop( scrollV ).scrollLeft( scrollH ); } $('.fancybox-overlay').remove().hide(); $.extend(this, { overlay : null, fixed : false }); }, // Private, callbacks update : function () { var width = '100%', offsetWidth; // Reset width/height so it will not mess this.overlay.width(width).height('100%'); // jQuery does not return reliable result for IE if (IE) { offsetWidth = Math.max(document.documentElement.offsetWidth, document.body.offsetWidth); if (D.width() > offsetWidth) { width = D.width(); } } else if (D.width() > W.width()) { width = D.width(); } this.overlay.width(width).height(D.height()); }, // This is where we can manipulate DOM, because later it would cause iframes to reload onReady : function (opts, obj) { var overlay = this.overlay; $('.fancybox-overlay').stop(true, true); if (!overlay) { this.create(opts); } if (opts.locked && this.fixed && obj.fixed) { if (!overlay) { this.margin = D.height() > W.height() ? $('html').css('margin-right').replace("px", "") : false; } obj.locked = this.overlay.append( obj.wrap ); obj.fixed = false; } if (opts.showEarly === true) { this.beforeShow.apply(this, arguments); } }, beforeShow : function(opts, obj) { var scrollV, scrollH; if (obj.locked) { if (this.margin !== false) { $('*').filter(function(){ return ($(this).css('position') === 'fixed' && !$(this).hasClass("fancybox-overlay") && !$(this).hasClass("fancybox-wrap") ); }).addClass('fancybox-margin'); this.el.addClass('fancybox-margin'); } scrollV = W.scrollTop(); scrollH = W.scrollLeft(); this.el.addClass('fancybox-lock'); W.scrollTop( scrollV ).scrollLeft( scrollH ); } this.open(opts); }, onUpdate : function() { if (!this.fixed) { this.update(); } }, afterClose: function (opts) { // Remove overlay if exists and fancyBox is not opening // (e.g., it is not being open using afterClose callback) //if (this.overlay && !F.isActive) { if (this.overlay && !F.coming) { this.overlay.fadeOut(opts.speedOut, $.proxy( this.close, this )); } } }; /* * Title helper */ F.helpers.title = { defaults : { type : 'float', // 'float', 'inside', 'outside' or 'over', position : 'bottom' // 'top' or 'bottom' }, beforeShow: function (opts) { var current = F.current, text = current.title, type = opts.type, title, target; if ($.isFunction(text)) { text = text.call(current.element, current); } if (!isString(text) || $.trim(text) === '') { return; } title = $('<div class="fancybox-title fancybox-title-' + type + '-wrap">' + text + '</div>'); switch (type) { case 'inside': target = F.skin; break; case 'outside': target = F.wrap; break; case 'over': target = F.inner; break; default: // 'float' target = F.skin; title.appendTo('body'); if (IE) { title.width( title.width() ); } title.wrapInner('<span class="child"></span>'); //Increase bottom margin so this title will also fit into viewport F.current.margin[2] += Math.abs( getScalar(title.css('margin-bottom')) ); break; } title[ (opts.position === 'top' ? 'prependTo' : 'appendTo') ](target); } }; // jQuery plugin initialization $.fn.fancybox = function (options) { var index, that = $(this), selector = this.selector || '', run = function(e) { var what = $(this).blur(), idx = index, relType, relVal; if (!(e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) && !what.is('.fancybox-wrap')) { relType = options.groupAttr || 'data-fancybox-group'; relVal = what.attr(relType); if (!relVal) { relType = 'rel'; relVal = what.get(0)[ relType ]; } if (relVal && relVal !== '' && relVal !== 'nofollow') { what = selector.length ? $(selector) : that; what = what.filter('[' + relType + '="' + relVal + '"]'); idx = what.index(this); } options.index = idx; // Stop an event from bubbling if everything is fine if (F.open(what, options) !== false) { e.preventDefault(); } } }; options = options || {}; index = options.index || 0; if (!selector || options.live === false) { that.unbind('click.fb-start').bind('click.fb-start', run); } else { D.undelegate(selector, 'click.fb-start').delegate(selector + ":not('.fancybox-item, .fancybox-nav')", 'click.fb-start', run); } this.filter('[data-fancybox-start=1]').trigger('click'); return this; }; // Tests that need a body at doc ready D.ready(function() { var w1, w2; if ( $.scrollbarWidth === undefined ) { // http://benalman.com/projects/jquery-misc-plugins/#scrollbarwidth $.scrollbarWidth = function() { var parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body'), child = parent.children(), width = child.innerWidth() - child.height( 99 ).innerWidth(); parent.remove(); return width; }; } if ( $.support.fixedPosition === undefined ) { $.support.fixedPosition = (function() { var elem = $('<div style="position:fixed;top:20px;"></div>').appendTo('body'), fixed = ( elem[0].offsetTop === 20 || elem[0].offsetTop === 15 ); elem.remove(); return fixed; }()); } $.extend(F.defaults, { scrollbarWidth : $.scrollbarWidth(), fixed : $.support.fixedPosition, parent : $('body') }); //Get real width of page scroll-bar w1 = $(window).width(); H.addClass('fancybox-lock-test'); w2 = $(window).width(); H.removeClass('fancybox-lock-test'); $("<style type='text/css'>.fancybox-margin{margin-right:" + (w2 - w1) + "px;}</style>").appendTo("head"); }); }(window, document, jQuery));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-fancybox-2.1.5.js
jquery-fancybox-2.1.5.js
* jQuery resize event - v1.1 - 3/14/2010 * http://benalman.com/projects/jquery-resize-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function ($, h, c) { var a = $([]), e = $.resize = $.extend($.resize, {}), i, k = "setTimeout", j = "resize", d = j + "-special-event", b = "delay", f = "throttleWindow"; e[b] = 250; e[f] = true; $.event.special[j] = {setup: function () { if (!e[f] && this[k]) { return false } var l = $(this); a = a.add(l); $.data(this, d, {w: l.width(), h: l.height()}); if (a.length === 1) { g() } }, teardown: function () { if (!e[f] && this[k]) { return false } var l = $(this); a = a.not(l); l.removeData(d); if (!a.length) { clearTimeout(i) } }, add: function (l) { if (!e[f] && this[k]) { return false } var n; function m(s, o, p) { var q = $(this), r = $.data(this, d); r.w = o !== c ? o : q.width(); r.h = p !== c ? p : q.height(); n.apply(this, arguments) } if ($.isFunction(l)) { n = l; return m } else { n = l.handler; l.handler = m } }}; function g() { i = h[k](function () { a.each(function () { var n = $(this), m = n.width(), l = n.height(), o = $.data(this, d); if (m !== o.w || l !== o.h) { n.trigger(j, [o.w = m, o.h = l]) } }); g() }, e[b]) } })(jQuery, this); (function ($) { var options = { }; // no options function init(plot) { function onResize() { var placeholder = plot.getPlaceholder(); // somebody might have hidden us and we can't plot // when we don't have the dimensions if (placeholder.width() == 0 || placeholder.height() == 0) return; plot.resize(); plot.setupGrid(); plot.draw(); } function bindEvents(plot, eventHolder) { plot.getPlaceholder().resize(onResize); } function shutdown(plot, eventHolder) { plot.getPlaceholder().unbind("resize", onResize); } plot.hooks.bindEvents.push(bindEvents); plot.hooks.shutdown.push(shutdown); } $.plot.plugins.push({ init: init, options: options, name: 'resize', version: '1.0' }); })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-plot-resize-1.1.js
jquery-plot-resize-1.1.js
!function(factory) { "function" == typeof define && define.amd ? define([ "jquery" ], factory) : factory("object" == typeof exports ? require("jquery") : jQuery); }(function($) { var caretTimeoutId, ua = navigator.userAgent, iPhone = /iphone/i.test(ua), chrome = /chrome/i.test(ua), android = /android/i.test(ua); $.mask = { definitions: { "9": "[0-9]", a: "[A-Za-z]", "*": "[A-Za-z0-9]" }, autoclear: !0, dataName: "rawMaskFn", placeholder: "_" }, $.fn.extend({ caret: function(begin, end) { var range; if (0 !== this.length && !this.is(":hidden")) return "number" == typeof begin ? (end = "number" == typeof end ? end : begin, this.each(function() { this.setSelectionRange ? this.setSelectionRange(begin, end) : this.createTextRange && (range = this.createTextRange(), range.collapse(!0), range.moveEnd("character", end), range.moveStart("character", begin), range.select()); })) : (this[0].setSelectionRange ? (begin = this[0].selectionStart, end = this[0].selectionEnd) : document.selection && document.selection.createRange && (range = document.selection.createRange(), begin = 0 - range.duplicate().moveStart("character", -1e5), end = begin + range.text.length), { begin: begin, end: end }); }, unmask: function() { return this.trigger("unmask"); }, mask: function(mask, settings) { var input, defs, tests, partialPosition, firstNonMaskPos, lastRequiredNonMaskPos, len, oldVal; if (!mask && this.length > 0) { input = $(this[0]); var fn = input.data($.mask.dataName); return fn ? fn() : void 0; } return settings = $.extend({ autoclear: $.mask.autoclear, placeholder: $.mask.placeholder, completed: null }, settings), defs = $.mask.definitions, tests = [], partialPosition = len = mask.length, firstNonMaskPos = null, $.each(mask.split(""), function(i, c) { "?" == c ? (len--, partialPosition = i) : defs[c] ? (tests.push(new RegExp(defs[c])), null === firstNonMaskPos && (firstNonMaskPos = tests.length - 1), partialPosition > i && (lastRequiredNonMaskPos = tests.length - 1)) : tests.push(null); }), this.trigger("unmask").each(function() { function tryFireCompleted() { if (settings.completed) { for (var i = firstNonMaskPos; lastRequiredNonMaskPos >= i; i++) if (tests[i] && buffer[i] === getPlaceholder(i)) return; settings.completed.call(input); } } function getPlaceholder(i) { return settings.placeholder.charAt(i < settings.placeholder.length ? i : 0); } function seekNext(pos) { for (;++pos < len && !tests[pos]; ) ; return pos; } function seekPrev(pos) { for (;--pos >= 0 && !tests[pos]; ) ; return pos; } function shiftL(begin, end) { var i, j; if (!(0 > begin)) { for (i = begin, j = seekNext(end); len > i; i++) if (tests[i]) { if (!(len > j && tests[i].test(buffer[j]))) break; buffer[i] = buffer[j], buffer[j] = getPlaceholder(j), j = seekNext(j); } writeBuffer(), input.caret(Math.max(firstNonMaskPos, begin)); } } function shiftR(pos) { var i, c, j, t; for (i = pos, c = getPlaceholder(pos); len > i; i++) if (tests[i]) { if (j = seekNext(i), t = buffer[i], buffer[i] = c, !(len > j && tests[j].test(t))) break; c = t; } } function androidInputEvent() { var curVal = input.val(), pos = input.caret(); if (oldVal && oldVal.length && oldVal.length > curVal.length) { for (checkVal(!0); pos.begin > 0 && !tests[pos.begin - 1]; ) pos.begin--; if (0 === pos.begin) for (;pos.begin < firstNonMaskPos && !tests[pos.begin]; ) pos.begin++; input.caret(pos.begin, pos.begin); } else { for (checkVal(!0); pos.begin < len && !tests[pos.begin]; ) pos.begin++; input.caret(pos.begin, pos.begin); } tryFireCompleted(); } function blurEvent() { checkVal(), input.val() != focusText && input.change(); } function keydownEvent(e) { if (!input.prop("readonly")) { var pos, begin, end, k = e.which || e.keyCode; oldVal = input.val(), 8 === k || 46 === k || iPhone && 127 === k ? (pos = input.caret(), begin = pos.begin, end = pos.end, end - begin === 0 && (begin = 46 !== k ? seekPrev(begin) : end = seekNext(begin - 1), end = 46 === k ? seekNext(end) : end), clearBuffer(begin, end), shiftL(begin, end - 1), e.preventDefault()) : 13 === k ? blurEvent.call(this, e) : 27 === k && (input.val(focusText), input.caret(0, checkVal()), e.preventDefault()); } } function keypressEvent(e) { if (!input.prop("readonly")) { var p, c, next, k = e.which || e.keyCode, pos = input.caret(); if (!(e.ctrlKey || e.altKey || e.metaKey || 32 > k) && k && 13 !== k) { if (pos.end - pos.begin !== 0 && (clearBuffer(pos.begin, pos.end), shiftL(pos.begin, pos.end - 1)), p = seekNext(pos.begin - 1), len > p && (c = String.fromCharCode(k), tests[p].test(c))) { if (shiftR(p), buffer[p] = c, writeBuffer(), next = seekNext(p), android) { var proxy = function() { $.proxy($.fn.caret, input, next)(); }; setTimeout(proxy, 0); } else input.caret(next); pos.begin <= lastRequiredNonMaskPos && tryFireCompleted(); } e.preventDefault(); } } } function clearBuffer(start, end) { var i; for (i = start; end > i && len > i; i++) tests[i] && (buffer[i] = getPlaceholder(i)); } function writeBuffer() { input.val(buffer.join("")); } function checkVal(allow) { var i, c, pos, test = input.val(), lastMatch = -1; for (i = 0, pos = 0; len > i; i++) if (tests[i]) { for (buffer[i] = getPlaceholder(i); pos++ < test.length; ) if (c = test.charAt(pos - 1), tests[i].test(c)) { buffer[i] = c, lastMatch = i; break; } if (pos > test.length) { clearBuffer(i + 1, len); break; } } else buffer[i] === test.charAt(pos) && pos++, partialPosition > i && (lastMatch = i); return allow ? writeBuffer() : partialPosition > lastMatch + 1 ? settings.autoclear || buffer.join("") === defaultBuffer ? (input.val() && input.val(""), clearBuffer(0, len)) : writeBuffer() : (writeBuffer(), input.val(input.val().substring(0, lastMatch + 1))), partialPosition ? i : firstNonMaskPos; } var input = $(this), buffer = $.map(mask.split(""), function(c, i) { return "?" != c ? defs[c] ? getPlaceholder(i) : c : void 0; }), defaultBuffer = buffer.join(""), focusText = input.val(); input.data($.mask.dataName, function() { return $.map(buffer, function(c, i) { return tests[i] && c != getPlaceholder(i) ? c : null; }).join(""); }), input.one("unmask", function() { input.off(".mask").removeData($.mask.dataName); }).on("focus.mask", function() { if (!input.prop("readonly")) { clearTimeout(caretTimeoutId); var pos; focusText = input.val(), pos = checkVal(), caretTimeoutId = setTimeout(function() { input.get(0) === document.activeElement && (writeBuffer(), pos == mask.replace("?", "").length ? input.caret(0, pos) : input.caret(pos)); }, 10); } }).on("blur.mask", blurEvent).on("keydown.mask", keydownEvent).on("keypress.mask", keypressEvent).on("input.mask paste.mask", function() { input.prop("readonly") || setTimeout(function() { var pos = checkVal(!0); input.caret(pos), tryFireCompleted(); }, 0); }), chrome && android && input.off("input.mask").on("input.mask", androidInputEvent), checkVal(); }); } }); });
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-maskedinput-1.4.1.js
jquery-maskedinput-1.4.1.js
!function ($) { "use strict"; // jshint ;_; /* MODAL CLASS DEFINITION * ====================== */ var Modal = function (element, options) { this.init(element, options); }; Modal.prototype = { constructor: Modal, init: function (element, options) { var that = this; this.options = options; this.$element = $(element) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)); this.options.remote && this.$element.find('.modal-body').load(this.options.remote, function () { var e = $.Event('loaded'); that.$element.trigger(e); }); var manager = typeof this.options.manager === 'function' ? this.options.manager.call(this) : this.options.manager; manager = manager.appendModal ? manager : $(manager).modalmanager().data('modalmanager'); manager.appendModal(this); }, toggle: function () { return this[!this.isShown ? 'show' : 'hide'](); }, show: function () { var e = $.Event('show'); if (this.isShown) return; this.$element.trigger(e); if (e.isDefaultPrevented()) return; this.escape(); this.tab(); this.options.loading && this.loading(); }, hide: function (e) { e && e.preventDefault(); e = $.Event('hide'); this.$element.trigger(e); if (!this.isShown || e.isDefaultPrevented()) return (this.isShown = false); this.isShown = false; this.escape(); this.tab(); this.isLoading && this.loading(); $(document).off('focusin.modal'); this.$element .removeClass('in') .removeClass('animated') .removeClass(this.options.attentionAnimation) .removeClass('modal-overflow') .attr('aria-hidden', true); $.support.transition && this.$element.hasClass('fade') ? this.hideWithTransition() : this.hideModal(); }, layout: function () { var prop = this.options.height ? 'height' : 'max-height', value = this.options.height || this.options.maxHeight; if (this.options.width) { this.$element.css('width', this.options.width); var that = this; this.$element.css('margin-left', function () { if (/%/ig.test(that.options.width)) { return -(parseInt(that.options.width) / 2) + '%'; } else { return -($(this).width() / 2) + 'px'; } }); } else { this.$element.css('width', ''); this.$element.css('margin-left', ''); } this.$element.find(this.options.overflow) .css('overflow', '') .css(prop, ''); if (value) { var body = this.$element.find(this.options.overflow); if (body.css('overflow') === undefined) { body.style('overflow', 'auto', 'important'); } body.style(prop, (typeof(value) === 'function' ? value() : value) + 'px', 'important'); } var modalOverflow = $(window).height() - 10 < this.$element.height(); // if (modalOverflow || this.options.modalOverflow) { this.$element .css('margin-top', 0) .addClass('modal-overflow'); // } else { // this.$element // .css('margin-top', 0 - this.$element.height() / 2) // .removeClass('modal-overflow'); // } }, tab: function () { var that = this; if (this.isShown && this.options.consumeTab) { this.$element.on('keydown.tabindex.modal', '[data-tabindex]', function (e) { if (e.keyCode && e.keyCode == 9) { var elements = [], tabindex = Number($(this).data('tabindex')); that.$element.find('[data-tabindex]:enabled:visible:not([readonly])').each(function (ev) { elements.push(Number($(this).data('tabindex'))); }); elements.sort(function(a,b){return a-b}); var arrayPos = $.inArray(tabindex, elements); if (!e.shiftKey){ arrayPos < elements.length-1 ? that.$element.find('[data-tabindex='+elements[arrayPos+1]+']').focus() : that.$element.find('[data-tabindex='+elements[0]+']').focus(); } else { arrayPos == 0 ? that.$element.find('[data-tabindex='+elements[elements.length-1]+']').focus() : that.$element.find('[data-tabindex='+elements[arrayPos-1]+']').focus(); } e.preventDefault(); } }); } else if (!this.isShown) { this.$element.off('keydown.tabindex.modal'); } }, escape: function () { var that = this; if (this.isShown && this.options.keyboard) { if (!this.$element.attr('tabindex')) this.$element.attr('tabindex', -1); this.$element.on('keyup.dismiss.modal', function (e) { e.which == 27 && that.hide(); }); } else if (!this.isShown) { this.$element.off('keyup.dismiss.modal') } }, hideWithTransition: function () { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end); that.hideModal(); }, 500); this.$element.one($.support.transition.end, function () { clearTimeout(timeout); that.hideModal(); }); }, hideModal: function () { var prop = this.options.height ? 'height' : 'max-height'; var value = this.options.height || this.options.maxHeight; if (value) { this.$element.find(this.options.overflow) .css('overflow', '') .css(prop, ''); } this.$element .hide() .trigger('hidden'); }, removeLoading: function () { this.$loading.remove(); this.$loading = null; this.isLoading = false; }, loading: function (callback) { callback = callback || function () {}; var animate = this.$element.hasClass('fade') ? 'fade' : ''; if (!this.isLoading) { var doAnimate = $.support.transition && animate; this.$loading = $('<div class="loading-mask ' + animate + '">') .append(this.options.spinner) .appendTo(this.$element); if (doAnimate) this.$loading[0].offsetWidth; // force reflow this.$loading.addClass('in'); this.isLoading = true; doAnimate ? this.$loading.one($.support.transition.end, callback) : callback(); } else if (this.isLoading && this.$loading) { this.$loading.removeClass('in'); var that = this; $.support.transition && this.$element.hasClass('fade') ? this.$loading.one($.support.transition.end, function () { that.removeLoading() }) : that.removeLoading(); } else if (callback) { callback(this.isLoading); } }, focus: function () { var $focusElem = this.$element.find(this.options.focusOn); $focusElem = $focusElem.length ? $focusElem : this.$element; $focusElem.focus(); }, attention: function () { // NOTE: transitionEnd with keyframes causes odd behaviour if (this.options.attentionAnimation) { this.$element .removeClass('animated') .removeClass(this.options.attentionAnimation); var that = this; setTimeout(function () { that.$element .addClass('animated') .addClass(that.options.attentionAnimation); }, 0); } this.focus(); }, destroy: function () { var e = $.Event('destroy'); this.$element.trigger(e); if (e.isDefaultPrevented()) return; this.$element .off('.modal') .removeData('modal') .removeClass('in') .attr('aria-hidden', true); if (this.$parent !== this.$element.parent()) { this.$element.appendTo(this.$parent); } else if (!this.$parent.length) { // modal is not part of the DOM so remove it. this.$element.remove(); this.$element = null; } this.$element.trigger('destroyed'); } }; /* MODAL PLUGIN DEFINITION * ======================= */ $.fn.modal = function (option, args) { return this.each(function () { var $this = $(this), data = $this.data('modal'), options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option); if (!data) $this.data('modal', (data = new Modal(this, options))); if (typeof option == 'string') data[option].apply(data, [].concat(args)); else if (options.show) data.show() }) }; $.fn.modal.defaults = { keyboard: true, backdrop: true, loading: false, show: true, width: null, height: null, maxHeight: null, modalOverflow: false, consumeTab: true, focusOn: null, replace: false, resize: false, overflow: '.modal-body', attentionAnimation: 'shake', manager: 'body', spinner: '<div class="loading-spinner" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>', backdropTemplate: '<div class="modal-backdrop" />' }; $.fn.modal.Constructor = Modal; /* MODAL DATA-API * ============== */ $(function () { $(document).off('click.modal').on('click.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this), href = $this.attr('href'), $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))), //strip for ie7 option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()); e.preventDefault(); $target .modal(option) .one('hide', function () { $this.focus(); }); }); }); }(window.jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/bootstrap-modal.js
bootstrap-modal.js
;(function($) { var bootstrapWizardCreate = function(element, options) { var element = $(element); var obj = this; // selector skips any 'li' elements that do not contain a child with a tab data-toggle var baseItemSelector = 'li:has([data-toggle="tab"])'; var historyStack = []; // Merge options with defaults var $settings = $.extend({}, $.fn.bootstrapWizard.defaults, options); var $activeTab = null; var $navigation = null; this.rebindClick = function(selector, fn) { selector.unbind('click', fn).bind('click', fn); } this.fixNavigationButtons = function() { // Get the current active tab if(!$activeTab.length) { // Select first one $navigation.find('a:first').tab('show'); $activeTab = $navigation.find(baseItemSelector + ':first'); } // See if we're currently in the first/last then disable the previous and last buttons $($settings.previousSelector, element).toggleClass('disabled', (obj.firstIndex() >= obj.currentIndex())); $($settings.nextSelector, element).toggleClass('disabled', (obj.currentIndex() >= obj.navigationLength())); $($settings.nextSelector, element).toggleClass('hidden', (obj.currentIndex() >= obj.navigationLength() && $($settings.finishSelector, element).length > 0)); $($settings.lastSelector, element).toggleClass('hidden', (obj.currentIndex() >= obj.navigationLength() && $($settings.finishSelector, element).length > 0)); $($settings.finishSelector, element).toggleClass('hidden', (obj.currentIndex() < obj.navigationLength())); $($settings.backSelector, element).toggleClass('disabled', historyStack.length === 0); $($settings.backSelector, element).toggleClass('hidden', (obj.currentIndex() >= obj.navigationLength() && $($settings.finishSelector, element).length > 0)); // We are unbinding and rebinding to ensure single firing and no double-click errors obj.rebindClick($($settings.nextSelector, element), obj.next); obj.rebindClick($($settings.previousSelector, element), obj.previous); obj.rebindClick($($settings.lastSelector, element), obj.last); obj.rebindClick($($settings.firstSelector, element), obj.first); obj.rebindClick($($settings.finishSelector, element), obj.finish); obj.rebindClick($($settings.backSelector, element), obj.back); if($settings.onTabShow && typeof $settings.onTabShow === 'function' && $settings.onTabShow($activeTab, $navigation, obj.currentIndex())===false){ return false; } }; this.next = function(e) { // If we clicked the last then dont activate this if(element.hasClass('last')) { return false; } if($settings.onNext && typeof $settings.onNext === 'function' && $settings.onNext($activeTab, $navigation, obj.nextIndex())===false){ return false; } var formerIndex = obj.currentIndex(); var $index = obj.nextIndex(); // Did we click the last button if($index > obj.navigationLength()) { } else { historyStack.push(formerIndex); $navigation.find(baseItemSelector + ($settings.withVisible ? ':visible' : '') + ':eq(' + $index + ') a').tab('show'); } }; this.previous = function(e) { // If we clicked the first then dont activate this if(element.hasClass('first')) { return false; } if($settings.onPrevious && typeof $settings.onPrevious === 'function' && $settings.onPrevious($activeTab, $navigation, obj.previousIndex())===false){ return false; } var formerIndex = obj.currentIndex(); var $index = obj.previousIndex(); if($index < 0) { } else { historyStack.push(formerIndex); $navigation.find(baseItemSelector + ($settings.withVisible ? ':visible' : '') + ':eq(' + $index + ') a').tab('show'); } }; this.first = function (e) { if($settings.onFirst && typeof $settings.onFirst === 'function' && $settings.onFirst($activeTab, $navigation, obj.firstIndex())===false){ return false; } // If the element is disabled then we won't do anything if(element.hasClass('disabled')) { return false; } historyStack.push(obj.currentIndex()); $navigation.find(baseItemSelector + ':eq(0) a').tab('show'); }; this.last = function(e) { if($settings.onLast && typeof $settings.onLast === 'function' && $settings.onLast($activeTab, $navigation, obj.lastIndex())===false){ return false; } // If the element is disabled then we won't do anything if(element.hasClass('disabled')) { return false; } historyStack.push(obj.currentIndex()); $navigation.find(baseItemSelector + ':eq(' + obj.navigationLength() + ') a').tab('show'); }; this.finish = function (e) { if ($settings.onFinish && typeof $settings.onFinish === 'function') { $settings.onFinish($activeTab, $navigation, obj.lastIndex()); } }; this.back = function () { if (historyStack.length == 0) { return null; } var formerIndex = historyStack.pop(); if ($settings.onBack && typeof $settings.onBack === 'function' && $settings.onBack($activeTab, $navigation, formerIndex) === false) { historyStack.push(formerIndex); return false; } element.find(baseItemSelector + ':eq(' + formerIndex + ') a').tab('show'); }; this.currentIndex = function() { return $navigation.find(baseItemSelector + ($settings.withVisible ? ':visible' : '')).index($activeTab); }; this.firstIndex = function() { return 0; }; this.lastIndex = function() { return obj.navigationLength(); }; this.getIndex = function(e) { return $navigation.find(baseItemSelector + ($settings.withVisible ? ':visible' : '')).index(e); }; this.nextIndex = function() { var nextIndexCandidate=this.currentIndex(); var nextTabCandidate=null; do { nextIndexCandidate++; nextTabCandidate = $navigation.find(baseItemSelector + ($settings.withVisible ? ':visible' : '') + ":eq(" + nextIndexCandidate + ")"); } while ((nextTabCandidate)&&(nextTabCandidate.hasClass("disabled"))); return nextIndexCandidate; }; this.previousIndex = function() { var prevIndexCandidate=this.currentIndex(); var prevTabCandidate=null; do { prevIndexCandidate--; prevTabCandidate = $navigation.find(baseItemSelector + ($settings.withVisible ? ':visible' : '') + ":eq(" + prevIndexCandidate + ")"); } while ((prevTabCandidate)&&(prevTabCandidate.hasClass("disabled"))); return prevIndexCandidate; }; this.navigationLength = function() { return $navigation.find(baseItemSelector + ($settings.withVisible ? ':visible' : '')).length - 1; }; this.activeTab = function() { return $activeTab; }; this.nextTab = function() { return $navigation.find(baseItemSelector + ':eq('+(obj.currentIndex()+1)+')').length ? $navigation.find(baseItemSelector + ':eq('+(obj.currentIndex()+1)+')') : null; }; this.previousTab = function() { if(obj.currentIndex() <= 0) { return null; } return $navigation.find(baseItemSelector + ':eq('+parseInt(obj.currentIndex()-1)+')'); }; this.show = function(index) { var tabToShow = isNaN(index) ? element.find(baseItemSelector + ' a[href="#' + index + '"]') : element.find(baseItemSelector + ':eq(' + index + ') a'); if (tabToShow.length > 0) { historyStack.push(obj.currentIndex()); tabToShow.tab('show'); } }; this.disable = function (index) { $navigation.find(baseItemSelector + ':eq('+index+')').addClass('disabled'); }; this.enable = function(index) { $navigation.find(baseItemSelector + ':eq('+index+')').removeClass('disabled'); }; this.hide = function(index) { $navigation.find(baseItemSelector + ':eq('+index+')').hide(); }; this.display = function(index) { $navigation.find(baseItemSelector + ':eq('+index+')').show(); }; this.remove = function(args) { var $index = args[0]; var $removeTabPane = typeof args[1] != 'undefined' ? args[1] : false; var $item = $navigation.find(baseItemSelector + ':eq('+$index+')'); // Remove the tab pane first if needed if($removeTabPane) { var $href = $item.find('a').attr('href'); $($href).remove(); } // Remove menu item $item.remove(); }; var innerTabClick = function (e) { // Get the index of the clicked tab var $ul = $navigation.find(baseItemSelector); var clickedIndex = $ul.index($(e.currentTarget).parent(baseItemSelector)); var $clickedTab = $( $ul[clickedIndex] ); if($settings.onTabClick && typeof $settings.onTabClick === 'function' && $settings.onTabClick($activeTab, $navigation, obj.currentIndex(), clickedIndex, $clickedTab)===false){ return false; } }; var innerTabShown = function (e) { var $element = $(e.target).parent(); var nextTab = $navigation.find(baseItemSelector).index($element); // If it's disabled then do not change if($element.hasClass('disabled')) { return false; } if($settings.onTabChange && typeof $settings.onTabChange === 'function' && $settings.onTabChange($activeTab, $navigation, obj.currentIndex(), nextTab)===false){ return false; } $activeTab = $element; // activated tab obj.fixNavigationButtons(); }; this.resetWizard = function() { // remove the existing handlers $('a[data-toggle="tab"]', $navigation).off('click', innerTabClick); $('a[data-toggle="tab"]', $navigation).off('show show.bs.tab', innerTabShown); // reset elements based on current state of the DOM $navigation = element.find('ul:first', element); $activeTab = $navigation.find(baseItemSelector + '.active', element); // re-add handlers $('a[data-toggle="tab"]', $navigation).on('click', innerTabClick); $('a[data-toggle="tab"]', $navigation).on('show show.bs.tab', innerTabShown); obj.fixNavigationButtons(); }; $navigation = element.find('ul:first', element); $activeTab = $navigation.find(baseItemSelector + '.active', element); if(!$navigation.hasClass($settings.tabClass)) { $navigation.addClass($settings.tabClass); } // Load onInit if($settings.onInit && typeof $settings.onInit === 'function'){ $settings.onInit($activeTab, $navigation, 0); } // Load onShow if($settings.onShow && typeof $settings.onShow === 'function'){ $settings.onShow($activeTab, $navigation, obj.nextIndex()); } $('a[data-toggle="tab"]', $navigation).on('click', innerTabClick); // attach to both show and show.bs.tab to support Bootstrap versions 2.3.2 and 3.0.0 $('a[data-toggle="tab"]', $navigation).on('show show.bs.tab', innerTabShown); }; $.fn.bootstrapWizard = function(options) { //expose methods if (typeof options == 'string') { var args = Array.prototype.slice.call(arguments, 1) if(args.length === 1) { args.toString(); } return this.data('bootstrapWizard')[options](args); } return this.each(function(index){ var element = $(this); // Return early if this element already has a plugin instance if (element.data('bootstrapWizard')) return; // pass options to plugin constructor var wizard = new bootstrapWizardCreate(element, options); // Store plugin object in this element's data element.data('bootstrapWizard', wizard); // and then trigger initial change wizard.fixNavigationButtons(); }); }; // expose options $.fn.bootstrapWizard.defaults = { withVisible: true, tabClass: 'nav nav-pills', nextSelector: '.wizard li.next', previousSelector: '.wizard li.previous', firstSelector: '.wizard li.first', lastSelector: '.wizard li.last', finishSelector: '.wizard li.finish', backSelector: '.wizard li.back', onShow: null, onInit: null, onNext: null, onPrevious: null, onLast: null, onFirst: null, onFinish: null, onBack: null, onTabChange: null, onTabClick: null, onTabShow: null }; })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/bootstrap-wizard-1.4.2.js
bootstrap-wizard-1.4.2.js
!function(c){var a=function(f,e){this.init(f,e)};a.prototype={constructor:a,init:function(f,e){this.$element=c(f);this.options=c.extend({},c.fn.modalmanager.defaults,this.$element.data(),typeof e==="object"&&e);this.stack=[];this.backdropCount=0;if(this.options.resize){var h,g=this;c(window).on("resize.modal",function(){if(h){clearTimeout(h)}h=setTimeout(function(){for(var j=0;j<g.stack.length;j++){if(g.stack[j].isShown){g.stack[j].layout()}}},10)})}},createModal:function(f,e){c(f).modal(c.extend({manager:this},e))},appendModal:function(f){this.stack.push(f);var e=this;f.$element.on("show.modalmanager",b(function(h){var g=function(){f.isShown=true;var i=c.support.transition&&f.$element.hasClass("fade");e.$element.toggleClass("modal-open",e.hasOpenModal()).toggleClass("page-overflow",c(window).height()<e.$element.height());f.$parent=f.$element.parent();f.$container=e.createContainer(f);f.$element.appendTo(f.$container);e.backdrop(f,function(){f.$element.show();if(i){f.$element[0].offsetWidth}f.layout();f.$element.addClass("in").attr("aria-hidden",false);var j=function(){e.setFocus();f.$element.trigger("shown")};if(i){f.$element.one(c.support.transition.end,j)}else{j()}})};if(f.options.replace){e.replace(g)}else{g()}}));f.$element.on("hidden.modalmanager",b(function(g){e.backdrop(f);if(!f.$element.parent().length){e.destroyModal(f)}else{if(f.$backdrop){var h=c.support.transition&&f.$element.hasClass("fade");if(h){f.$element[0].offsetWidth}if(c.support.transition&&f.$element.hasClass("fade")){f.$backdrop.one(c.support.transition.end,function(){f.destroy()})}else{f.destroy()}}else{f.destroy()}}}));f.$element.on("destroyed.modalmanager",b(function(g){e.destroyModal(f)}))},getOpenModals:function(){var f=[];for(var e=0;e<this.stack.length;e++){if(this.stack[e].isShown){f.push(this.stack[e])}}return f},hasOpenModal:function(){return this.getOpenModals().length>0},setFocus:function(){var f;for(var e=0;e<this.stack.length;e++){if(this.stack[e].isShown){f=this.stack[e]}}if(!f){return}f.focus()},destroyModal:function(f){f.$element.off(".modalmanager");if(f.$backdrop){this.removeBackdrop(f)}this.stack.splice(this.getIndexOfModal(f),1);var e=this.hasOpenModal();this.$element.toggleClass("modal-open",e);if(!e){this.$element.removeClass("page-overflow")}this.removeContainer(f);this.setFocus()},getModalAt:function(e){return this.stack[e]},getIndexOfModal:function(f){for(var e=0;e<this.stack.length;e++){if(f===this.stack[e]){return e}}},replace:function(g){var f;for(var e=0;e<this.stack.length;e++){if(this.stack[e].isShown){f=this.stack[e]}}if(f){this.$backdropHandle=f.$backdrop;f.$backdrop=null;if(g){f.$element.one("hidden",b(c.proxy(g,this)))}f.hide()}else{if(g){g()}}},removeBackdrop:function(e){e.$backdrop.remove();e.$backdrop=null},createBackdrop:function(g,f){var e;if(!this.$backdropHandle){e=c(f).addClass(g).appendTo(this.$element)}else{e=this.$backdropHandle;e.off(".modalmanager");this.$backdropHandle=null;if(this.isLoading){this.removeSpinner()}}return e},removeContainer:function(e){e.$container.remove();e.$container=null},createContainer:function(e){var f;f=c('<div class="modal-scrollable">').css("z-index",d("modal",this.getOpenModals().length)).appendTo(this.$element);if(e&&e.options.backdrop==="hide"){f.on("click.modal",b(function(g){e.hide()}))}else{if(e&&e.options.backdrop==="attention"){f.on("click.modal",b(function(g){e.attention()}))}}return f},backdrop:function(h,j){var f=h.$element.hasClass("fade")?"fade":"",i=h.options.backdrop&&this.backdropCount<this.options.backdropLimit;if(h.isShown&&i){var e=c.support.transition&&f&&!this.$backdropHandle;h.$backdrop=this.createBackdrop(f,h.options.backdropTemplate);h.$backdrop.css("z-index",d("backdrop",this.getOpenModals().length));if(e){h.$backdrop[0].offsetWidth}h.$backdrop.addClass("in");this.backdropCount+=1;if(e){h.$backdrop.one(c.support.transition.end,j)}else{j()}}else{if(!h.isShown&&h.$backdrop){h.$backdrop.removeClass("in");this.backdropCount-=1;var g=this;if(c.support.transition&&h.$element.hasClass("fade")){h.$backdrop.one(c.support.transition.end,function(){g.removeBackdrop(h)})}else{g.removeBackdrop(h)}}else{if(j){j()}}}},removeSpinner:function(){if(this.$spinner){this.$spinner.remove()}this.$spinner=null;this.isLoading=false},removeLoading:function(){if(this.$backdropHandle){this.$backdropHandle.remove()}this.$backdropHandle=null;this.removeSpinner()},loading:function(h){h=h||function(){};this.$element.toggleClass("modal-open",!this.isLoading||this.hasOpenModal()).toggleClass("page-overflow",c(window).height()<this.$element.height());if(!this.isLoading){this.$backdropHandle=this.createBackdrop("fade",this.options.backdropTemplate);this.$backdropHandle[0].offsetWidth;var e=this.getOpenModals();this.$backdropHandle.css("z-index",d("backdrop",e.length+1)).addClass("in");var g=c(this.options.spinner).css("z-index",d("modal",e.length+1)).appendTo(this.$element).addClass("in");this.$spinner=c(this.createContainer()).append(g).on("click.modalmanager",c.proxy(this.loading,this));this.isLoading=true;if(c.support.transition){this.$backdropHandle.one(c.support.transition.end,h)}else{h()}}else{if(this.isLoading&&this.$backdropHandle){this.$backdropHandle.removeClass("in");var f=this;if(c.support.transition){this.$backdropHandle.one(c.support.transition.end,function(){f.removeLoading()})}else{f.removeLoading()}}else{if(h){h(this.isLoading)}}}}};var d=(function(){var f,e={};return function(g,j){if(typeof f==="undefined"){var i=c('<div class="modal hide" />').appendTo("body"),h=c('<div class="modal-backdrop hide" />').appendTo("body");e.modal=+i.css("z-index");e.backdrop=+h.css("z-index");f=e.modal-e.backdrop;i.remove();h.remove();h=i=null}return e[g]+(f*j)}}());function b(e){return function(f){if(f&&this===f.target){return e.apply(this,arguments)}}}c.fn.modalmanager=function(f,e){return this.each(function(){var h=c(this),g=h.data("modalmanager");if(!g){h.data("modalmanager",(g=new a(this,f)))}if(typeof f==="string"){g[f].apply(g,[].concat(e))}})};c.fn.modalmanager.defaults={backdropLimit:999,resize:true,spinner:'<div class="loading-spinner fade" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',backdropTemplate:'<div class="modal-backdrop" />'};c.fn.modalmanager.Constructor=a;c(function(){c(document).off("show.bs.modal").off("hidden.bs.modal")})}(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/bootstrap-modalmanager.min.js
bootstrap-modalmanager.min.js
* @summary ColVis * @description Controls for column visibility in DataTables * @version 1.1.0 * @file dataTables.colReorder.js * @author SpryMedia Ltd (www.sprymedia.co.uk) * @contact www.sprymedia.co.uk/contact * @copyright Copyright 2010-2014 SpryMedia Ltd. * * This source file is free software, available under the following license: * MIT license - http://datatables.net/license/mit * * 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 */ (function (window, document, undefined) { var factory = function ($, DataTable) { "use strict"; /** * ColVis provides column visibility control for DataTables * * @class ColVis * @constructor * @param {object} DataTables settings object. With DataTables 1.10 this can * also be and API instance, table node, jQuery collection or jQuery selector. * @param {object} ColVis configuration options */ var ColVis = function (oDTSettings, oInit) { /* Santiy check that we are a new instance */ if (!this.CLASS || this.CLASS != "ColVis") { alert("Warning: ColVis must be initialised with the keyword 'new'"); } if (typeof oInit == 'undefined') { oInit = {}; } if ($.fn.dataTable.camelToHungarian) { $.fn.dataTable.camelToHungarian(ColVis.defaults, oInit); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for * ColVis instance. Augmented by ColVis.defaults */ this.s = { /** * DataTables settings object * @property dt * @type Object * @default null */ "dt": null, /** * Customisation object * @property oInit * @type Object * @default passed in */ "oInit": oInit, /** * Flag to say if the collection is hidden * @property hidden * @type boolean * @default true */ "hidden": true, /** * Store the original visibility settings so they could be restored * @property abOriginal * @type Array * @default [] */ "abOriginal": [] }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * Wrapper for the button - given back to DataTables as the node to insert * @property wrapper * @type Node * @default null */ "wrapper": null, /** * Activation button * @property button * @type Node * @default null */ "button": null, /** * Collection list node * @property collection * @type Node * @default null */ "collection": null, /** * Background node used for shading the display and event capturing * @property background * @type Node * @default null */ "background": null, /** * Element to position over the activation button to catch mouse events when using mouseover * @property catcher * @type Node * @default null */ "catcher": null, /** * List of button elements * @property buttons * @type Array * @default [] */ "buttons": [], /** * List of group button elements * @property groupButtons * @type Array * @default [] */ "groupButtons": [], /** * Restore button * @property restore * @type Node * @default null */ "restore": null }; /* Store global reference */ ColVis.aInstances.push(this); /* Constructor logic */ this.s.dt = $.fn.dataTable.Api ? new $.fn.dataTable.Api(oDTSettings).settings()[0] : oDTSettings; this._fnConstruct(oInit); return this; }; ColVis.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Get the ColVis instance's control button so it can be injected into the * DOM * @method button * @returns {node} ColVis button */ button: function () { return this.dom.wrapper; }, /** * Alias of `rebuild` for backwards compatibility * @method fnRebuild */ "fnRebuild": function () { this.rebuild(); }, /** * Rebuild the list of buttons for this instance (i.e. if there is a column * header update) * @method fnRebuild */ rebuild: function () { /* Remove the old buttons */ for (var i = this.dom.buttons.length - 1; i >= 0; i--) { this.dom.collection.removeChild(this.dom.buttons[i]); } this.dom.buttons.splice(0, this.dom.buttons.length); if (this.dom.restore) { this.dom.restore.parentNode(this.dom.restore); } /* Re-add them (this is not the optimal way of doing this, it is fast and effective) */ this._fnAddGroups(); this._fnAddButtons(); /* Update the checkboxes */ this._fnDrawCallback(); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Constructor logic * @method _fnConstruct * @returns void * @private */ "_fnConstruct": function (init) { this._fnApplyCustomisation(init); var that = this; var i, iLen; this.dom.wrapper = document.createElement('div'); this.dom.wrapper.className = "ColVis"; this.dom.button = $('<button />', { 'class': !this.s.dt.bJUI ? "ColVis_Button ColVis_MasterButton" : "ColVis_Button ColVis_MasterButton ui-button ui-state-default" }) .append('<span>' + this.s.buttonText + '</span>') .bind(this.s.activate == "mouseover" ? "mouseover" : "click", function (e) { e.preventDefault(); that._fnCollectionShow(); }) .appendTo(this.dom.wrapper)[0]; this.dom.catcher = this._fnDomCatcher(); this.dom.collection = this._fnDomCollection(); this.dom.background = this._fnDomBackground(); this._fnAddGroups(); this._fnAddButtons(); /* Store the original visibility information */ for (i = 0, iLen = this.s.dt.aoColumns.length; i < iLen; i++) { this.s.abOriginal.push(this.s.dt.aoColumns[i].bVisible); } /* Update on each draw */ this.s.dt.aoDrawCallback.push({ "fn": function () { that._fnDrawCallback.call(that); }, "sName": "ColVis" }); /* If columns are reordered, then we need to update our exclude list and * rebuild the displayed list */ $(this.s.dt.oInstance).bind('column-reorder', function (e, oSettings, oReorder) { for (i = 0, iLen = that.s.aiExclude.length; i < iLen; i++) { that.s.aiExclude[i] = oReorder.aiInvertMapping[ that.s.aiExclude[i] ]; } var mStore = that.s.abOriginal.splice(oReorder.iFrom, 1)[0]; that.s.abOriginal.splice(oReorder.iTo, 0, mStore); that.fnRebuild(); }); // Set the initial state this._fnDrawCallback(); }, /** * Apply any customisation to the settings from the DataTables initialisation * @method _fnApplyCustomisation * @returns void * @private */ "_fnApplyCustomisation": function (init) { $.extend(true, this.s, ColVis.defaults, init); // Slightly messy overlap for the camelCase notation if (!this.s.showAll && this.s.bShowAll) { this.s.showAll = this.s.sShowAll; } if (!this.s.restore && this.s.bRestore) { this.s.restore = this.s.sRestore; } // CamelCase to Hungarian for the column groups var groups = this.s.groups; var hungarianGroups = this.s.aoGroups; if (groups) { for (var i = 0, ien = groups.length; i < ien; i++) { if (groups[i].title) { hungarianGroups[i].sTitle = groups[i].title; } if (groups[i].columns) { hungarianGroups[i].aiColumns = groups[i].columns; } } } }, /** * On each table draw, check the visibility checkboxes as needed. This allows any process to * update the table's column visibility and ColVis will still be accurate. * @method _fnDrawCallback * @returns void * @private */ "_fnDrawCallback": function () { var columns = this.s.dt.aoColumns; var buttons = this.dom.buttons; var groups = this.s.aoGroups; var button; for (var i = 0, ien = buttons.length; i < ien; i++) { button = buttons[i]; if (button.__columnIdx !== undefined) { $('input', button).prop('checked', columns[ button.__columnIdx ].bVisible); } } var allVisible = function (columnIndeces) { for (var k = 0, kLen = columnIndeces.length; k < kLen; k++) { if (columns[columnIndeces[k]].bVisible === false) { return false; } } return true; }; var allHidden = function (columnIndeces) { for (var m = 0 , mLen = columnIndeces.length; m < mLen; m++) { if (columns[columnIndeces[m]].bVisible === true) { return false; } } return true; }; for (var j = 0, jLen = groups.length; j < jLen; j++) { if (allVisible(groups[j].aiColumns)) { $('input', this.dom.groupButtons[j]).prop('checked', true); $('input', this.dom.groupButtons[j]).prop('indeterminate', false); } else if (allHidden(groups[j].aiColumns)) { $('input', this.dom.groupButtons[j]).prop('checked', false); $('input', this.dom.groupButtons[j]).prop('indeterminate', false); } else { $('input', this.dom.groupButtons[j]).prop('indeterminate', true); } } }, /** * Loop through the groups (provided in the settings) and create a button for each. * @method _fnAddgroups * @returns void * @private */ "_fnAddGroups": function () { var nButton; if (typeof this.s.aoGroups != 'undefined') { for (var i = 0, iLen = this.s.aoGroups.length; i < iLen; i++) { nButton = this._fnDomGroupButton(i); this.dom.groupButtons.push(nButton); this.dom.buttons.push(nButton); this.dom.collection.appendChild(nButton); } } }, /** * Loop through the columns in the table and as a new button for each one. * @method _fnAddButtons * @returns void * @private */ "_fnAddButtons": function () { var nButton, columns = this.s.dt.aoColumns; if ($.inArray('all', this.s.aiExclude) === -1) { for (var i = 0, iLen = columns.length; i < iLen; i++) { if ($.inArray(i, this.s.aiExclude) === -1) { nButton = this._fnDomColumnButton(i); nButton.__columnIdx = i; this.dom.buttons.push(nButton); } } } if (this.s.order === 'alpha') { this.dom.buttons.sort(function (a, b) { var titleA = columns[ a.__columnIdx ].sTitle; var titleB = columns[ b.__columnIdx ].sTitle; return titleA === titleB ? 0 : titleA < titleB ? -1 : 1; }); } if (this.s.restore) { nButton = this._fnDomRestoreButton(); nButton.className += " ColVis_Restore"; this.dom.buttons.push(nButton); } if (this.s.showAll) { nButton = this._fnDomShowAllButton(); nButton.className += " ColVis_ShowAll"; this.dom.buttons.push(nButton); } $(this.dom.collection).append(this.dom.buttons); }, /** * Create a button which allows a "restore" action * @method _fnDomRestoreButton * @returns {Node} Created button * @private */ "_fnDomRestoreButton": function () { var that = this, dt = this.s.dt; return $( '<li class="ColVis_Special ' + (dt.bJUI ? 'ui-button ui-state-default' : '') + '">' + this.s.restore + '</li>' ) .click(function (e) { for (var i = 0, iLen = that.s.abOriginal.length; i < iLen; i++) { that.s.dt.oInstance.fnSetColumnVis(i, that.s.abOriginal[i], false); } that._fnAdjustOpenRows(); that.s.dt.oInstance.fnAdjustColumnSizing(false); that.s.dt.oInstance.fnDraw(false); })[0]; }, /** * Create a button which allows a "show all" action * @method _fnDomShowAllButton * @returns {Node} Created button * @private */ "_fnDomShowAllButton": function () { var that = this, dt = this.s.dt; return $( '<li class="ColVis_Special ' + (dt.bJUI ? 'ui-button ui-state-default' : '') + '">' + this.s.showAll + '</li>' ) .click(function (e) { for (var i = 0, iLen = that.s.abOriginal.length; i < iLen; i++) { if (that.s.aiExclude.indexOf(i) === -1) { that.s.dt.oInstance.fnSetColumnVis(i, true, false); } } that._fnAdjustOpenRows(); that.s.dt.oInstance.fnAdjustColumnSizing(false); that.s.dt.oInstance.fnDraw(false); })[0]; }, /** * Create the DOM for a show / hide group button * @method _fnDomGroupButton * @param {int} i Group in question, order based on that provided in settings * @returns {Node} Created button * @private */ "_fnDomGroupButton": function (i) { var that = this, dt = this.s.dt, oGroup = this.s.aoGroups[i]; return $( '<li class="ColVis_Special ' + (dt.bJUI ? 'ui-button ui-state-default' : '') + '">' + '<label>' + '<input type="checkbox" />' + '<span>' + oGroup.sTitle + '</span>' + '</label>' + '</li>' ) .click(function (e) { var showHide = !$('input', this).is(":checked"); if (e.target.nodeName.toLowerCase() !== "li") { showHide = !showHide; } for (var j = 0; j < oGroup.aiColumns.length; j++) { that.s.dt.oInstance.fnSetColumnVis(oGroup.aiColumns[j], showHide); } })[0]; }, /** * Create the DOM for a show / hide button * @method _fnDomColumnButton * @param {int} i Column in question * @returns {Node} Created button * @private */ "_fnDomColumnButton": function (i) { var that = this, column = this.s.dt.aoColumns[i], dt = this.s.dt; var title = this.s.fnLabel === null ? column.sTitle : this.s.fnLabel(i, column.sTitle, column.nTh); return $( '<li ' + (dt.bJUI ? 'class="ui-button ui-state-default"' : '') + '>' + '<label>' + '<input type="checkbox" />' + '<span>' + title + '</span>' + '</label>' + '</li>' ) .click(function (e) { var showHide = !$('input', this).is(":checked"); if (e.target.nodeName.toLowerCase() !== "li") { showHide = !showHide; } /* Need to consider the case where the initialiser created more than one table - change the * API index that DataTables is using */ var oldIndex = $.fn.dataTableExt.iApiIndex; $.fn.dataTableExt.iApiIndex = that._fnDataTablesApiIndex.call(that); // Optimisation for server-side processing when scrolling - don't do a full redraw if (dt.oFeatures.bServerSide) { that.s.dt.oInstance.fnSetColumnVis(i, showHide, false); that.s.dt.oInstance.fnAdjustColumnSizing(false); if (dt.oScroll.sX !== "" || dt.oScroll.sY !== "") { that.s.dt.oInstance.oApi._fnScrollDraw(that.s.dt); } that._fnDrawCallback(); } else { that.s.dt.oInstance.fnSetColumnVis(i, showHide); } $.fn.dataTableExt.iApiIndex = oldIndex; /* Restore */ if (that.s.fnStateChange !== null) { that.s.fnStateChange.call(that, i, showHide); } })[0]; }, /** * Get the position in the DataTables instance array of the table for this * instance of ColVis * @method _fnDataTablesApiIndex * @returns {int} Index * @private */ "_fnDataTablesApiIndex": function () { for (var i = 0, iLen = this.s.dt.oInstance.length; i < iLen; i++) { if (this.s.dt.oInstance[i] == this.s.dt.nTable) { return i; } } return 0; }, /** * Create the element used to contain list the columns (it is shown and * hidden as needed) * @method _fnDomCollection * @returns {Node} div container for the collection * @private */ "_fnDomCollection": function () { var that = this; return $('<ul />', { 'class': !that.s.dt.bJUI ? "ColVis_collection" : "ColVis_collection ui-buttonset ui-buttonset-multi" }) .css({ 'display': 'none', 'opacity': 0, 'position': !that.s.bCssPosition ? 'absolute' : '' })[0]; }, /** * An element to be placed on top of the activate button to catch events * @method _fnDomCatcher * @returns {Node} div container for the collection * @private */ "_fnDomCatcher": function () { var that = this, nCatcher = document.createElement('div'); nCatcher.className = "ColVis_catcher"; $(nCatcher).click(function () { that._fnCollectionHide.call(that, null, null); }); return nCatcher; }, /** * Create the element used to shade the background, and capture hide events (it is shown and * hidden as needed) * @method _fnDomBackground * @returns {Node} div container for the background * @private */ "_fnDomBackground": function () { var that = this; var background = $('<div></div>') .addClass('ColVis_collectionBackground') .css('opacity', 0) .click(function () { that._fnCollectionHide.call(that, null, null); }); /* When considering a mouse over action for the activation, we also consider a mouse out * which is the same as a mouse over the background - without all the messing around of * bubbling events. Use the catcher element to avoid messing around with bubbling */ if (this.s.activate == "mouseover") { background.mouseover(function () { that.s.overcollection = false; that._fnCollectionHide.call(that, null, null); }); } return background[0]; }, /** * Show the show / hide list and the background * @method _fnCollectionShow * @returns void * @private */ "_fnCollectionShow": function () { var that = this, i, iLen, iLeft; var oPos = $(this.dom.button).offset(); var nHidden = this.dom.collection; var nBackground = this.dom.background; var iDivX = parseInt(oPos.left, 10); var iDivY = parseInt(oPos.top + $(this.dom.button).outerHeight(), 10); if (!this.s.bCssPosition) { nHidden.style.top = iDivY + "px"; nHidden.style.left = iDivX + "px"; } $(nHidden).css({ 'display': 'block', 'opacity': 0 }); // nBackground.style.bottom ='0px'; // nBackground.style.right = '0px'; // var oStyle = this.dom.catcher.style; // oStyle.height = $(this.dom.button).outerHeight()+"px"; // oStyle.width = $(this.dom.button).outerWidth()+"px"; // oStyle.top = oPos.top+"px"; // oStyle.left = iDivX+"px"; document.body.appendChild(nBackground); document.body.appendChild(nHidden); document.body.appendChild(this.dom.catcher); /* This results in a very small delay for the end user but it allows the animation to be * much smoother. If you don't want the animation, then the setTimeout can be removed */ $(nHidden).animate({"opacity": 1}, that.s.iOverlayFade); $(nBackground).animate({"opacity": 0.1}, that.s.iOverlayFade, 'linear', function () { /* In IE6 if you set the checked attribute of a hidden checkbox, then this is not visually * reflected. As such, we need to do it here, once it is visible. Unbelievable. */ if ($.browser && $.browser.msie && $.browser.version == "6.0") { that._fnDrawCallback(); } }); /* Visual corrections to try and keep the collection visible */ if (!this.s.bCssPosition) { iLeft = ( this.s.sAlign == "left" ) ? iDivX : iDivX - $(nHidden).outerWidth() + $(this.dom.button).outerWidth(); nHidden.style.left = iLeft + "px"; var iDivWidth = $(nHidden).outerWidth(); var iDivHeight = $(nHidden).outerHeight(); var iDocWidth = $(document).width(); if (iLeft + iDivWidth > iDocWidth) { nHidden.style.left = (iDocWidth - iDivWidth) + "px"; } } this.s.hidden = false; }, /** * Hide the show / hide list and the background * @method _fnCollectionHide * @returns void * @private */ "_fnCollectionHide": function () { var that = this; if (!this.s.hidden && this.dom.collection !== null) { this.s.hidden = true; $(this.dom.collection).animate({"opacity": 0}, that.s.iOverlayFade, function (e) { this.style.display = "none"; }); $(this.dom.background).animate({"opacity": 0}, that.s.iOverlayFade, function (e) { document.body.removeChild(that.dom.background); document.body.removeChild(that.dom.catcher); }); } }, /** * Alter the colspan on any fnOpen rows */ "_fnAdjustOpenRows": function () { var aoOpen = this.s.dt.aoOpenRows; var iVisible = this.s.dt.oApi._fnVisbleColumns(this.s.dt); for (var i = 0, iLen = aoOpen.length; i < iLen; i++) { aoOpen[i].nTr.getElementsByTagName('td')[0].colSpan = iVisible; } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static object methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Rebuild the collection for a given table, or all tables if no parameter given * @method ColVis.fnRebuild * @static * @param object oTable DataTable instance to consider - optional * @returns void */ ColVis.fnRebuild = function (oTable) { var nTable = null; if (typeof oTable != 'undefined') { nTable = oTable.fnSettings().nTable; } for (var i = 0, iLen = ColVis.aInstances.length; i < iLen; i++) { if (typeof oTable == 'undefined' || nTable == ColVis.aInstances[i].s.dt.nTable) { ColVis.aInstances[i].fnRebuild(); } } }; ColVis.defaults = { /** * Mode of activation. Can be 'click' or 'mouseover' * @property activate * @type string * @default click */ active: 'click', /** * Text used for the button * @property buttonText * @type string * @default Show / hide columns */ buttonText: 'Show / hide columns', /** * List of columns (integers) which should be excluded from the list * @property aiExclude * @type array * @default [] */ aiExclude: [], /** * Show restore button * @property bRestore * @type boolean * @default false */ bRestore: false, /** * Restore button text * @property sRestore * @type string * @default Restore original */ sRestore: 'Restore original', /** * Show Show-All button * @property bShowAll * @type boolean * @default false */ bShowAll: false, /** * Show All button text * @property sShowAll * @type string * @default Restore original */ sShowAll: 'Show All', /** * Position of the collection menu when shown - align "left" or "right" * @property sAlign * @type string * @default left */ sAlign: 'left', /** * Callback function to tell the user when the state has changed * @property fnStateChange * @type function * @default null */ fnStateChange: null, /** * Overlay animation duration in mS * @property iOverlayFade * @type integer|false * @default 500 */ iOverlayFade: 500, /** * Label callback for column names. Takes three parameters: 1. the * column index, 2. the column title detected by DataTables and 3. the * TH node for the column * @property fnLabel * @type function * @default null */ fnLabel: null, /** * Indicate if the column list should be positioned by Javascript, * visually below the button or allow CSS to do the positioning * @property bCssPosition * @type boolean * @default false */ bCssPosition: false, /** * Group buttons * @property aoGroups * @type array * @default [] */ aoGroups: [], /** * Button ordering - 'alpha' (alphabetical) or 'column' (table column * order) * @property order * @type string * @default column */ order: 'column' }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static object properties * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Collection of all ColVis instances * @property ColVis.aInstances * @static * @type Array * @default [] */ ColVis.aInstances = []; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Name of this class * @constant CLASS * @type String * @default ColVis */ ColVis.prototype.CLASS = "ColVis"; /** * ColVis version * @constant VERSION * @type String * @default See code */ ColVis.VERSION = "1.1.0"; ColVis.prototype.VERSION = ColVis.VERSION; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Register a new feature with DataTables */ if (typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.7.0')) { $.fn.dataTableExt.aoFeatures.push({ "fnInit": function (oDTSettings) { var init = oDTSettings.oInit; var colvis = new ColVis(oDTSettings, init.colVis || init.oColVis || {}); return colvis.button(); }, "cFeature": "C", "sFeature": "ColVis" }); } else { alert("Warning: ColVis requires DataTables 1.7 or greater - www.datatables.net/download"); } // Make ColVis accessible from the DataTables instance $.fn.dataTable.ColVis = ColVis; $.fn.DataTable.ColVis = ColVis; return ColVis; }; // /factory factory(jQuery, jQuery.fn.dataTable); })(window, document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-colVis.js
jquery-dataTables-colVis.js
(function(c){var r={isMsie:function(){return/(msie|trident)/i.test(navigator.userAgent)?navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]:false},isBlankString:function(t){return !t||/^\s*$/.test(t)},escapeRegExChars:function(t){return t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(t){return typeof t==="string"},isNumber:function(t){return typeof t==="number"},isArray:c.isArray,isFunction:c.isFunction,isObject:c.isPlainObject,isUndefined:function(t){return typeof t==="undefined"},bind:c.proxy,each:function(v,t){c.each(v,u);function u(w,x){return t(x,w)}},map:c.map,filter:c.grep,every:function(u,v){var t=true;if(!u){return t}c.each(u,function(w,x){if(!(t=v.call(null,x,w,u))){return false}});return !!t},some:function(u,v){var t=false;if(!u){return t}c.each(u,function(w,x){if(t=v.call(null,x,w,u)){return false}});return !!t},mixin:c.extend,getUniqueId:function(){var t=0;return function(){return t++}}(),templatify:function f(u){return c.isFunction(u)?u:t;function t(){return String(u)}},defer:function(t){setTimeout(t,0)},debounce:function(v,x,u){var w,t;return function(){var B=this,A=arguments,z,y;z=function(){w=null;if(!u){t=v.apply(B,A)}};y=u&&!w;clearTimeout(w);w=setTimeout(z,x);if(y){t=v.apply(B,A)}return t}},throttle:function(y,A){var w,v,z,t,x,u;x=0;u=function(){x=new Date();z=null;t=y.apply(w,v)};return function(){var B=new Date(),C=A-(B-x);w=this;v=arguments;if(C<=0){clearTimeout(z);z=null;x=B;t=y.apply(w,v)}else{if(!z){z=setTimeout(u,C)}}return t}},noop:function(){}};var o="0.10.0";var e=function(x,u){function B(C){this.maxSize=C||100;this.size=0;this.hash={};this.list=new A()}r.mixin(B.prototype,{set:function y(C,F){var E=this.list.tail,D;if(this.size>=this.maxSize){this.list.remove(E);delete this.hash[E.key]}if(D=this.hash[C]){D.val=F;this.list.moveToFront(D)}else{D=new w(C,F);this.list.add(D);this.hash[C]=D;this.size++}},get:function t(C){var D=this.hash[C];if(D){this.list.moveToFront(D);return D.val}}});function A(){this.head=this.tail=null}r.mixin(A.prototype,{add:function z(C){if(this.head){C.next=this.head;this.head.prev=C}this.head=C;this.tail=this.tail||C},remove:function v(C){C.prev?C.prev.next=C.next:this.head=C.next;C.next?C.next.prev=C.prev:this.tail=C.prev},moveToFront:function(C){this.remove(C);this.add(C)}});function w(C,D){this.key=C;this.val=D;this.prev=this.next=null}return B}(this);var p=function(){var t,u;try{t=window.localStorage;t.setItem("~~~","!");t.removeItem("~~~")}catch(y){t=null}function w(A){this.prefix=["__",A,"__"].join("");this.ttlKey="__ttl__";this.keyMatcher=new RegExp("^"+this.prefix)}if(t&&window.JSON){u={_prefix:function(A){return this.prefix+A},_ttlKey:function(A){return this._prefix(A)+this.ttlKey},get:function(A){if(this.isExpired(A)){this.remove(A)}return z(t.getItem(this._prefix(A)))},set:function(B,C,A){if(r.isNumber(A)){t.setItem(this._ttlKey(B),x(v()+A))}else{t.removeItem(this._ttlKey(B))}return t.setItem(this._prefix(B),x(C))},remove:function(A){t.removeItem(this._ttlKey(A));t.removeItem(this._prefix(A));return this},clear:function(){var C,B,D=[],A=t.length;for(C=0;C<A;C++){if((B=t.key(C)).match(this.keyMatcher)){D.push(B.replace(this.keyMatcher,""))}}for(C=D.length;C--;){this.remove(D[C])}return this},isExpired:function(B){var A=z(t.getItem(this._ttlKey(B)));return r.isNumber(A)&&v()>A?true:false}}}else{u={get:r.noop,set:r.noop,remove:r.noop,clear:r.noop,isExpired:r.noop}}r.mixin(w.prototype,u);return w;function v(){return new Date().getTime()}function x(A){return JSON.stringify(r.isUndefined(A)?null:A)}function z(A){return JSON.parse(A)}}();var q=function(){var v=0,w={},t=6,z=new e(10);function A(B){B=B||{};this._send=B.send?x(B.send):c.ajax;this._get=B.rateLimiter?B.rateLimiter(this._get):this._get}A.setMaxPendingRequests=function u(B){t=B};A.resetCache=function y(){z=new e(10)};r.mixin(A.prototype,{_get:function(E,H,C){var G=this,F;if(F=w[E]){F.done(D)}else{if(v<t){v++;w[E]=this._send(E,H).done(D).always(B)}else{this.onDeckRequestArgs=[].slice.call(arguments,0)}}function D(I){C&&C(I);z.set(E,I)}function B(){v--;delete w[E];if(G.onDeckRequestArgs){G._get.apply(G,G.onDeckRequestArgs);G.onDeckRequestArgs=null}}},get:function(C,F,B){var D=this,E;if(r.isFunction(F)){B=F;F={}}if(E=z.get(C)){r.defer(function(){B&&B(E)})}else{this._get(C,F,B)}return !!E}});return A;function x(B){return function C(E,H){var D=c.Deferred();B(E,H,G,F);return D;function G(I){r.defer(function(){D.resolve(I)})}function F(I){r.defer(function(){D.reject(I)})}}}}();var k=function(){function y(B){B=B||{};if(!B.datumTokenizer||!B.queryTokenizer){c.error("datumTokenizer and queryTokenizer are both required")}this.datumTokenizer=B.datumTokenizer;this.queryTokenizer=B.queryTokenizer;this.datums=[];this.trie=v()}r.mixin(y.prototype,{bootstrap:function w(B){this.datums=B.datums;this.trie=B.trie},add:function(C){var B=this;C=r.isArray(C)?C:[C];r.each(C,function(D){var F,E;F=B.datums.push(D)-1;E=t(B.datumTokenizer(D));r.each(E,function(G){var K,J,I,H;K=B.trie;J=G.split("");while(I=J.shift()){K=K.children[I]||(K.children[I]=v());K.ids.push(F)}})})},get:function u(D){var B=this,E,C;E=t(this.queryTokenizer(D));r.each(E,function(F){var J,I,H,G;if(C&&C.length===0){return false}J=B.trie;I=F.split("");while(J&&(H=I.shift())){J=J.children[H]}if(J&&I.length===0){G=J.ids.slice(0);C=C?z(C,G):G}else{C=[];return false}});return C?r.map(A(C),function(F){return B.datums[F]}):[]},serialize:function x(){return{datums:this.datums,trie:this.trie}}});return y;function t(B){B=r.filter(B,function(C){return !!C});B=r.map(B,function(C){return C.toLowerCase()});return B}function v(){return{ids:[],children:{}}}function A(E){var B={},D=[];for(var C=0;C<E.length;C++){if(!B[E[C]]){B[E[C]]=true;D.push(E[C])}}return D}function z(E,C){var B=0,D=0,G=[];E=E.sort(F);C=C.sort(F);while(B<E.length&&D<C.length){if(E[B]<C[D]){B++}else{if(E[B]>C[D]){D++}else{G.push(E[B]);B++;D++}}}return G;function F(I,H){return I-H}}}();var h=function(){return{local:v,prefetch:t,remote:u};function v(w){return w.local||null}function t(y){var x,w;w={url:null,thumbprint:"",ttl:24*60*60*1000,filter:null,ajax:{}};if(x=y.prefetch||null){x=r.isString(x)?{url:x}:x;x=r.mixin(w,x);x.thumbprint=o+x.thumbprint;x.ajax.method=x.ajax.method||"get";x.ajax.dataType=x.ajax.dataType||"json";!x.url&&c.error("prefetch requires url to be set")}return x}function u(A){var y,z;z={url:null,wildcard:"%QUERY",replace:null,rateLimitBy:"debounce",rateLimitWait:300,send:null,filter:null,ajax:{}};if(y=A.remote||null){y=r.isString(y)?{url:y}:y;y=r.mixin(z,y);y.rateLimiter=/^throttle$/i.test(y.rateLimitBy)?x(y.rateLimitWait):w(y.rateLimitWait);y.ajax.method=y.ajax.method||"get";y.ajax.dataType=y.ajax.dataType||"json";delete y.rateLimitBy;delete y.rateLimitWait;!y.url&&c.error("remote requires url to be set")}return y;function w(B){return function(C){return r.debounce(C,B)}}function x(B){return function(C){return r.throttle(C,B)}}}}();var a=window.Bloodhound=function(){var G;G={data:"data",protocol:"protocol",thumbprint:"thumbprint"};function A(H){if(!H||!H.local&&!H.prefetch&&!H.remote){c.error("one of local, prefetch, or remote is required")}this.limit=H.limit||5;this.sorter=H.sorter||C;this.dupDetector=H.dupDetector||v;this.local=h.local(H);this.prefetch=h.prefetch(H);this.remote=h.remote(H);this.cacheKey=this.prefetch?this.prefetch.cacheKey||this.prefetch.url:null;this.index=new k({datumTokenizer:H.datumTokenizer,queryTokenizer:H.queryTokenizer});this.storage=this.cacheKey?new p(this.cacheKey):null}A.tokenizers={whitespace:function x(H){return H.split(/\s+/)},nonword:function z(H){return H.split(/\W+/)}};r.mixin(A.prototype,{_loadPrefetch:function t(L){var I=this,K,H;if(K=this._readFromStorage(L.thumbprint)){this.index.bootstrap(K);H=c.Deferred().resolve()}else{H=c.ajax(L.url,L.ajax).done(J)}return H;function J(N){var M;M=L.filter?L.filter(N):N;I.add(M);I._saveToStorage(I.index.serialize(),L.thumbprint,L.ttl)}},_getFromRemote:function u(M,H){var L=this,J,K;M=M||"";K=encodeURIComponent(M);J=this.remote.replace?this.remote.replace(this.remote.url,M):this.remote.url.replace(this.remote.wildcard,K);return this.transport.get(J,this.remote.ajax,I);function I(O){var N=L.remote.filter?L.remote.filter(O):O;H(N)}},_saveToStorage:function D(J,I,H){if(this.storage){this.storage.set(G.data,J,H);this.storage.set(G.protocol,location.protocol,H);this.storage.set(G.thumbprint,I,H)}},_readFromStorage:function F(I){var H={};if(this.storage){H.data=this.storage.get(G.data);H.protocol=this.storage.get(G.protocol);H.thumbprint=this.storage.get(G.thumbprint)}isExpired=H.thumbprint!==I||H.protocol!==location.protocol;return H.data&&!isExpired?H.data:null},initialize:function y(){var K=this,I;I=this.prefetch?this._loadPrefetch(this.prefetch):c.Deferred().resolve();this.local&&I.done(J);this.transport=this.remote?new q(this.remote):null;this.initialize=function H(){return I.promise()};return I.promise();function J(){K.add(K.local)}},add:function E(H){this.index.add(H)},get:function w(L,H){var J=this,K,I=false;K=this.index.get(L).sort(this.sorter).slice(0,this.limit);if(K.length<this.limit&&this.transport){I=this._getFromRemote(L,M)}!I&&H&&H(K);function M(O){var N=K.slice(0);r.each(O,function(Q){var P;P=r.some(N,function(R){return J.dupDetector(Q,R)});!P&&N.push(Q);return N.length<J.limit});H&&H(N.sort(J.sorter))}},ttAdapter:function B(){return r.bind(this.get,this)}});return A;function C(){return 0}function v(){return false}}();var j={wrapper:'<span class="twitter-typeahead"></span>',dropdown:'<span class="tt-dropdown-menu"></span>',dataset:'<div class="tt-dataset-%CLASS%"></div>',suggestions:'<span class="tt-suggestions"></span>',suggestion:'<div class="tt-suggestion">%BODY%</div>'};var i={wrapper:{position:"relative",display:"inline-block"},hint:{position:"absolute",top:"0",left:"0",borderColor:"transparent",boxShadow:"none"},input:{position:"relative",verticalAlign:"top",backgroundColor:"transparent"},inputWithNoHint:{position:"relative",verticalAlign:"top"},dropdown:{position:"absolute",top:"100%",left:"0",zIndex:"100",display:"none"},suggestions:{display:"block"},suggestion:{whiteSpace:"nowrap",cursor:"pointer"},suggestionChild:{whiteSpace:"normal"},ltr:{left:"0",right:"auto"},rtl:{left:"auto",right:" 0"}};if(r.isMsie()){r.mixin(i.input,{backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"})}if(r.isMsie()&&r.isMsie()<=7){r.mixin(i.input,{marginTop:"-1px"})}var b=function(){var u="typeahead:";function t(v){if(!v||!v.el){c.error("EventBus initialized without el")}this.$el=c(v.el)}r.mixin(t.prototype,{trigger:function(w){var v=[].slice.call(arguments,1);this.$el.trigger(u+w,v)}});return t}();var g=function(){var v=/\s+/,z=t();return{onSync:A,onAsync:u,off:w,trigger:x};function B(H,F,D,E){var G;if(!D){return this}F=F.split(v);D=E?C(D,E):D;this._callbacks=this._callbacks||{};while(G=F.shift()){this._callbacks[G]=this._callbacks[G]||{sync:[],async:[]};this._callbacks[G][H].push(D)}return this}function u(F,D,E){return B.call(this,"async",F,D,E)}function A(F,D,E){return B.call(this,"sync",F,D,E)}function w(D){var E;if(!this._callbacks){return this}D=D.split(v);while(E=D.shift()){delete this._callbacks[E]}return this}function x(E){var H=this,F,G,D,I,J;if(!this._callbacks){return this}E=E.split(v);D=[].slice.call(arguments,1);while((F=E.shift())&&(G=this._callbacks[F])){I=y(G.sync,this,[F].concat(D));J=y(G.async,this,[F].concat(D));I()&&z(J)}return this}function y(G,F,E){return D;function D(){var I;for(var H=0;!I&&H<G.length;H+=1){I=G[H].apply(F,E)===false}return !I}}function t(){var E,G;if(window.setImmediate){E=function F(H){setImmediate(function(){H()})}}else{E=function D(H){setTimeout(function(){H()},0)}}return E}function C(E,D){return E.bind?E.bind(D):function(){E.apply(D,[].slice.call(arguments,0))}}}();var d=function(w){var v={node:null,pattern:null,tagName:"strong",className:null,wordsOnly:false,caseSensitive:false};return function u(A){var x;A=r.mixin({},v,A);if(!A.node||!A.pattern){return}A.pattern=r.isArray(A.pattern)?A.pattern:[A.pattern];x=t(A.pattern,A.caseSensitive,A.wordsOnly);y(A.node,z);function z(D){var C,B;if(C=x.exec(D.data)){wrapperNode=w.createElement(A.tagName);A.className&&(wrapperNode.className=A.className);B=D.splitText(C.index);B.splitText(C[0].length);wrapperNode.appendChild(B.cloneNode(true));D.parentNode.replaceChild(wrapperNode,B)}return !!C}function y(E,F){var C,D=3;for(var B=0;B<E.childNodes.length;B++){C=E.childNodes[B];if(C.nodeType===D){B+=F(C)?1:0}else{y(C,F)}}}};function t(z,x,C){var B=[],A;for(var y=0;y<z.length;y++){B.push(r.escapeRegExChars(z[y]))}A=C?"\\b("+B.join("|")+")\\b":"("+B.join("|")+")";return x?new RegExp(A):new RegExp(A,"i")}}(window.document);var m=function(){var O;O={9:"tab",27:"esc",37:"left",39:"right",13:"enter",38:"up",40:"down"};function L(X){var V=this,W,S,U,T;X=X||{};if(!X.input){c.error("input is missing")}W=r.bind(this._onBlur,this);S=r.bind(this._onFocus,this);U=r.bind(this._onKeydown,this);T=r.bind(this._onInput,this);this.$hint=c(X.hint);this.$input=c(X.input).on("blur.tt",W).on("focus.tt",S).on("keydown.tt",U);if(this.$hint.length===0){this.setHintValue=this.getHintValue=this.clearHint=r.noop}if(!r.isMsie()){this.$input.on("input.tt",T)}else{this.$input.on("keydown.tt keypress.tt cut.tt paste.tt",function(Y){if(O[Y.which||Y.keyCode]){return}r.defer(r.bind(V._onInput,V,Y))})}this.query=this.$input.val();this.$overflowHelper=E(this.$input)}L.normalizeQuery=function(S){return(S||"").replace(/^\s*/g,"").replace(/\s{2,}/g," ")};r.mixin(L.prototype,g,{_onBlur:function C(S){this.resetInputValue();this.trigger("blurred")},_onFocus:function v(S){this.trigger("focused")},_onKeydown:function Q(S){var T=O[S.which||S.keyCode];this._managePreventDefault(T,S);if(T&&this._shouldTrigger(T,S)){this.trigger(T+"Keyed",S)}},_onInput:function t(S){this._checkInputValue()},_managePreventDefault:function x(W,V){var U,T,S;switch(W){case"tab":T=this.getHintValue();S=this.getInputValue();U=T&&T!==S&&!F(V);break;case"up":case"down":U=!F(V);break;default:U=false}U&&V.preventDefault()},_shouldTrigger:function R(U,T){var S;switch(U){case"tab":S=!F(T);break;default:S=true}return S},_checkInputValue:function z(){var S,T,U;S=this.getInputValue();T=B(S,this.query);U=T?this.query.length!==S.length:false;if(!T){this.trigger("queryChanged",this.query=S)}else{if(U){this.trigger("whitespaceChanged",this.query)}}},focus:function H(){this.$input.focus()},blur:function M(){this.$input.blur()},getQuery:function J(){return this.query},setQuery:function I(S){this.query=S},getInputValue:function w(){return this.$input.val()},setInputValue:function A(T,S){this.$input.val(T);!S&&this._checkInputValue()},getHintValue:function N(){return this.$hint.val()},setHintValue:function y(S){this.$hint.val(S)},resetInputValue:function u(){this.$input.val(this.query)},clearHint:function D(){this.$hint.val("")},getLanguageDirection:function G(){return(this.$input.css("direction")||"ltr").toLowerCase()},hasOverflow:function K(){var S=this.$input.width()-2;this.$overflowHelper.text(this.getInputValue());return this.$overflowHelper.width()>=S},isCursorAtEnd:function(){var T,U,S;T=this.$input.val().length;U=this.$input[0].selectionStart;if(r.isNumber(U)){return U===T}else{if(document.selection){S=document.selection.createRange();S.moveStart("character",-T);return T===S.text.length}}return true},destroy:function P(){this.$hint.off(".tt");this.$input.off(".tt");this.$hint=this.$input=this.$overflowHelper=null}});return L;function E(S){return c('<pre aria-hidden="true"></pre>').css({position:"absolute",visibility:"hidden",whiteSpace:"nowrap",fontFamily:S.css("font-family"),fontSize:S.css("font-size"),fontStyle:S.css("font-style"),fontVariant:S.css("font-variant"),fontWeight:S.css("font-weight"),wordSpacing:S.css("word-spacing"),letterSpacing:S.css("letter-spacing"),textIndent:S.css("text-indent"),textRendering:S.css("text-rendering"),textTransform:S.css("text-transform")}).insertAfter(S)}function B(T,S){return L.normalizeQuery(T)===L.normalizeQuery(S)}function F(S){return S.altKey||S.ctrlKey||S.metaKey||S.shiftKey}}();var s=function(){var u="ttDataset",F="ttValue",A="ttDatum";function t(G){G=G||{};G.templates=G.templates||{};if(!G.source){c.error("missing source")}this.query=null;this.highlight=!!G.highlight;this.name=G.name||r.getUniqueId();this.source=G.source;this.valueKey=G.displayKey||"value";this.templates=w(G.templates,this.valueKey);this.$el=c(j.dataset.replace("%CLASS%",this.name))}t.extractDatasetName=function E(G){return c(G).data(u)};t.extractValue=function B(G){return c(G).data(F)};t.extractDatum=function B(G){return c(G).data(A)};r.mixin(t.prototype,g,{_render:function v(M,G){if(!this.$el){return}var L=this,I;this.$el.empty();I=G&&G.length;if(!I&&this.templates.empty){this.$el.html(H()).prepend(L.templates.header?K():null).append(L.templates.footer?J():null)}else{if(I){this.$el.html(N()).prepend(L.templates.header?K():null).append(L.templates.footer?J():null)}}this.trigger("rendered");function H(){return L.templates.empty({query:M})}function N(){var O;O=c(j.suggestions).css(i.suggestions).append(r.map(G,P));L.highlight&&d({node:O[0],pattern:M});return O;function P(S){var T,R,Q;R=L.templates.suggestion(S);Q=j.suggestion.replace("%BODY%",R);T=c(Q).data(u,L.name).data(F,S[L.valueKey]).data(A,S);T.children().each(function(){c(this).css(i.suggestionChild)});return T}}function K(){return L.templates.header({query:M,isEmpty:!I})}function J(){return L.templates.footer({query:M,isEmpty:!I})}},getRoot:function C(){return this.$el},update:function x(I){var H=this;this.query=I;this.source(I,G);function G(J){I===H.query&&H._render(I,J)}},clear:function z(){this._render(this.query||"")},isEmpty:function y(){return this.$el.is(":empty")},destroy:function D(){this.$el=null}});return t;function w(H,I){return{empty:H.empty&&r.templatify(H.empty),header:H.header&&r.templatify(H.header),footer:H.footer&&r.templatify(H.footer),suggestion:H.suggestion||G};function G(J){return"<p>"+J[I]+"</p>"}}}();var n=function(){function N(Z){var W=this,X,T,U,Y,V;Z=Z||{};if(!Z.menu){c.error("menu is required")}this.isOpen=false;this.isEmpty=true;this.isMouseOverDropdown=false;this.datasets=r.map(Z.datasets,D);X=r.bind(this._onMouseEnter,this);T=r.bind(this._onMouseLeave,this);U=r.bind(this._onSuggestionClick,this);Y=r.bind(this._onSuggestionMouseEnter,this);V=r.bind(this._onSuggestionMouseLeave,this);this.$menu=c(Z.menu).on("mouseenter.tt",X).on("mouseleave.tt",T).on("click.tt",".tt-suggestion",U).on("mouseenter.tt",".tt-suggestion",Y).on("mouseleave.tt",".tt-suggestion",V);r.each(this.datasets,function(aa){W.$menu.append(aa.getRoot());aa.onSync("rendered",W._onRendered,W)})}r.mixin(N.prototype,g,{_onMouseEnter:function F(T){this.isMouseOverDropdown=true},_onMouseLeave:function S(T){this.isMouseOverDropdown=false},_onSuggestionClick:function M(T){this.trigger("suggestionClicked",c(T.currentTarget))},_onSuggestionMouseEnter:function t(T){this._removeCursor();this._setCursor(c(T.currentTarget),true)},_onSuggestionMouseLeave:function H(T){this._removeCursor()},_onRendered:function z(){this.isEmpty=r.every(this.datasets,T);this.isEmpty?this._hide():this.isOpen&&this._show();this.trigger("datasetRendered");function T(U){return U.isEmpty()}},_hide:function(){this.$menu.hide()},_show:function(){this.$menu.css("display","block")},_getSuggestions:function y(){return this.$menu.find(".tt-suggestion")},_getCursor:function w(){return this.$menu.find(".tt-cursor").first()},_setCursor:function P(U,T){U.first().addClass("tt-cursor");!T&&this.trigger("cursorMoved")},_removeCursor:function v(){this._getCursor().removeClass("tt-cursor")},_moveCursor:function u(T){var V,U,X,W;if(!this.isOpen){return}U=this._getCursor();V=this._getSuggestions();this._removeCursor();X=V.index(U)+T;X=(X+1)%(V.length+1)-1;if(X===-1){this.trigger("cursorRemoved");return}else{if(X<-1){X=V.length-1}}this._setCursor(W=V.eq(X));this._ensureVisible(W)},_ensureVisible:function L(W){var T,V,U,X;T=W.position().top;V=T+W.outerHeight(true);U=this.$menu.scrollTop();X=this.$menu.height()+parseInt(this.$menu.css("paddingTop"),10)+parseInt(this.$menu.css("paddingBottom"),10);if(T<0){this.$menu.scrollTop(U+T)}else{if(X<V){this.$menu.scrollTop(U+(V-X))}}},close:function I(){if(this.isOpen){this.isOpen=this.isMouseOverDropdown=false;this._removeCursor();this._hide();this.trigger("closed")}},open:function G(){if(!this.isOpen){this.isOpen=true;!this.isEmpty&&this._show();this.trigger("opened")}},setLanguageDirection:function Q(T){this.$menu.css(T==="ltr"?i.ltr:i.rtl)},moveCursorUp:function A(){this._moveCursor(-1)},moveCursorDown:function R(){this._moveCursor(+1)},getDatumForSuggestion:function C(U){var T=null;if(U.length){T={raw:s.extractDatum(U),value:s.extractValue(U),datasetName:s.extractDatasetName(U)}}return T},getDatumForCursor:function x(){return this.getDatumForSuggestion(this._getCursor().first())},getDatumForTopSuggestion:function K(){return this.getDatumForSuggestion(this._getSuggestions().first())},update:function B(T){r.each(this.datasets,U);function U(V){V.update(T)}},empty:function E(){r.each(this.datasets,T);function T(U){U.clear()}},isVisible:function J(){return this.isOpen&&!this.isEmpty},destroy:function O(){this.$menu.off(".tt");this.$menu=null;r.each(this.datasets,T);function T(U){U.destroy()}}});return N;function D(T){return new s(T)}}();var l=function(){var U="ttAttrs";function C(ab){var aa,ac,Z,Y;ab=ab||{};if(!ab.input){c.error("missing input")}this.autoselect=!!ab.autoselect;this.minLength=r.isNumber(ab.minLength)?ab.minLength:1;this.$node=F(ab.input,ab.withHint);aa=this.$node.find(".tt-dropdown-menu");ac=this.$node.find(".tt-input");Z=this.$node.find(".tt-hint");this.eventBus=ab.eventBus||new b({el:ac});this.dropdown=new n({menu:aa,datasets:ab.datasets}).onSync("suggestionClicked",this._onSuggestionClicked,this).onSync("cursorMoved",this._onCursorMoved,this).onSync("cursorRemoved",this._onCursorRemoved,this).onSync("opened",this._onOpened,this).onSync("closed",this._onClosed,this).onAsync("datasetRendered",this._onDatasetRendered,this);this.input=new m({input:ac,hint:Z}).onSync("focused",this._onFocused,this).onSync("blurred",this._onBlurred,this).onSync("enterKeyed",this._onEnterKeyed,this).onSync("tabKeyed",this._onTabKeyed,this).onSync("escKeyed",this._onEscKeyed,this).onSync("upKeyed",this._onUpKeyed,this).onSync("downKeyed",this._onDownKeyed,this).onSync("leftKeyed",this._onLeftKeyed,this).onSync("rightKeyed",this._onRightKeyed,this).onSync("queryChanged",this._onQueryChanged,this).onSync("whitespaceChanged",this._onWhitespaceChanged,this);aa.on("mousedown.tt",function(ad){if(r.isMsie()&&r.isMsie()<9){ac[0].onbeforedeactivate=function(){window.event.returnValue=false;ac[0].onbeforedeactivate=null}}ad.preventDefault()})}r.mixin(C.prototype,{_onSuggestionClicked:function u(aa,Z){var Y;if(Y=this.dropdown.getDatumForSuggestion(Z)){this._select(Y)}},_onCursorMoved:function P(){var Y=this.dropdown.getDatumForCursor();this.input.clearHint();this.input.setInputValue(Y.value,true);this.eventBus.trigger("cursorchanged",Y.raw,Y.datasetName)},_onCursorRemoved:function x(){this.input.resetInputValue();this._updateHint()},_onDatasetRendered:function L(){this._updateHint()},_onOpened:function v(){this._updateHint();this.eventBus.trigger("opened")},_onClosed:function A(){this.input.clearHint();this.eventBus.trigger("closed")},_onFocused:function N(){this.dropdown.open()},_onBlurred:function O(){!this.dropdown.isMouseOverDropdown&&this.dropdown.close()},_onEnterKeyed:function I(Z,Y){var aa,ab;aa=this.dropdown.getDatumForCursor();ab=this.dropdown.getDatumForTopSuggestion();if(aa){this._select(aa);Y.preventDefault()}else{if(this.autoselect&&ab){this._select(ab);Y.preventDefault()}}},_onTabKeyed:function X(aa,Z){var Y;if(Y=this.dropdown.getDatumForCursor()){this._select(Y);Z.preventDefault()}else{this._autocomplete()}},_onEscKeyed:function S(){this.dropdown.close();this.input.resetInputValue()},_onUpKeyed:function t(){var Y=this.input.getQuery();if(!this.dropdown.isOpen&&Y.length>=this.minLength){this.dropdown.update(Y)}this.dropdown.open();this.dropdown.moveCursorUp()},_onDownKeyed:function y(){var Y=this.input.getQuery();if(!this.dropdown.isOpen&&Y.length>=this.minLength){this.dropdown.update(Y)}this.dropdown.open();this.dropdown.moveCursorDown()},_onLeftKeyed:function W(){this.dir==="rtl"&&this._autocomplete()},_onRightKeyed:function K(){this.dir==="ltr"&&this._autocomplete()},_onQueryChanged:function E(Z,Y){this.input.clearHint();this.dropdown.empty();Y.length>=this.minLength&&this.dropdown.update(Y);this.dropdown.open();this._setLanguageDirection()},_onWhitespaceChanged:function T(){this._updateHint();this.dropdown.open()},_setLanguageDirection:function R(){var Y;if(this.dir!==(Y=this.input.getLanguageDirection())){this.dir=Y;this.$node.css("direction",Y);this.dropdown.setLanguageDirection(Y)}},_updateHint:function M(){var aa,Z,ad,ac,Y,ab;aa=this.dropdown.getDatumForTopSuggestion();if(aa&&this.dropdown.isVisible()&&!this.input.hasOverflow()){Z=this.input.getInputValue();ad=m.normalizeQuery(Z);ac=r.escapeRegExChars(ad);Y=new RegExp("^(?:"+ac+")(.*$)","i");ab=Y.exec(aa.value);this.input.setHintValue(Z+(ab?ab[1]:""))}},_autocomplete:function V(){var aa,Z,Y;aa=this.input.getHintValue();Z=this.input.getQuery();if(aa&&Z!==aa&&this.input.isCursorAtEnd()){Y=this.dropdown.getDatumForTopSuggestion();Y&&this.input.setInputValue(Y.value);this.eventBus.trigger("autocompleted",Y.raw,Y.datasetName)}},_select:function G(Y){this.input.clearHint();this.input.setQuery(Y.value);this.input.setInputValue(Y.value,true);this.dropdown.empty();this._setLanguageDirection();r.defer(r.bind(this.dropdown.close,this.dropdown));this.eventBus.trigger("selected",Y.raw,Y.datasetName)},open:function B(){this.dropdown.open()},close:function D(){this.dropdown.close()},getQuery:function J(){return this.input.getQuery()},setQuery:function H(Y){this.input.setInputValue(Y)},destroy:function Q(){this.input.destroy();this.dropdown.destroy();w(this.$node);this.$node=null}});return C;function F(Y,ad){var ae,aa,ac,Z;ae=c(Y);aa=c(j.wrapper).css(i.wrapper);ac=c(j.dropdown).css(i.dropdown);Z=ae.clone().css(i.hint).css(z(ae));Z.removeData().addClass("tt-hint").removeAttr("id name placeholder").prop("disabled",true).attr({autocomplete:"off",spellcheck:"false"});ae.data(U,{dir:ae.attr("dir"),autocomplete:ae.attr("autocomplete"),spellcheck:ae.attr("spellcheck"),style:ae.attr("style")});ae.addClass("tt-input").attr({autocomplete:"off",spellcheck:false}).css(ad?i.input:i.inputWithNoHint);try{!ae.attr("dir")&&ae.attr("dir","auto")}catch(ab){}return ae.wrap(aa).parent().prepend(ad?Z:null).append(ac)}function z(Y){return{backgroundAttachment:Y.css("background-attachment"),backgroundClip:Y.css("background-clip"),backgroundColor:Y.css("background-color"),backgroundImage:Y.css("background-image"),backgroundOrigin:Y.css("background-origin"),backgroundPosition:Y.css("background-position"),backgroundRepeat:Y.css("background-repeat"),backgroundSize:Y.css("background-size")}}function w(Y){var Z=Y.find(".tt-input");r.each(Z.data(U),function(ab,aa){r.isUndefined(ab)?Z.removeAttr(aa):Z.attr(aa,ab)});Z.detach().removeData(U).removeClass("tt-input").insertAfter(Y);Y.remove()}}();(function(){var u,v;u="ttTypeahead";v={initialize:function t(C){var B=[].slice.call(arguments,1);C=C||{};return this.each(A);function A(){var G=c(this),D,F;r.each(B,function(H){H.highlight=!!C.highlight});F=new l({input:G,eventBus:D=new b({el:G}),withHint:r.isUndefined(C.hint)?true:!!C.hint,minLength:C.minLength,autoselect:C.autoselect,datasets:B});G.data(u,F);function E(H){return function(){r.defer(function(){D.trigger(H)})}}}},open:function w(){return this.each(A);function A(){var C=c(this),B;if(B=C.data(u)){B.open()}}},close:function z(){return this.each(A);function A(){var C=c(this),B;if(B=C.data(u)){B.close()}}},val:function y(B){return r.isString(B)?this.each(C):this.map(A).get();function C(){var E=c(this),D;if(D=E.data(u)){D.setQuery(B)}}function A(){var F=c(this),E,D;if(E=F.data(u)){D=E.getQuery()}return D}},destroy:function x(){return this.each(A);function A(){var C=c(this),B;if(B=C.data(u)){B.destroy();C.removeData(u)}}}};jQuery.fn.typeahead=function(A){if(v[A]){return v[A].apply(this,[].slice.call(arguments,1))}else{return v.initialize.apply(this,arguments)}}})()})(window.jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-typeahead.min.js
jquery-typeahead.min.js
(function ($) { var _ = { isMsie: function () { return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false; }, isBlankString: function (str) { return !str || /^\s*$/.test(str); }, escapeRegExChars: function (str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); }, isString: function (obj) { return typeof obj === "string"; }, isNumber: function (obj) { return typeof obj === "number"; }, isArray: $.isArray, isFunction: $.isFunction, isObject: $.isPlainObject, isUndefined: function (obj) { return typeof obj === "undefined"; }, bind: $.proxy, each: function (collection, cb) { $.each(collection, reverseArgs); function reverseArgs(index, value) { return cb(value, index); } }, map: $.map, filter: $.grep, every: function (obj, test) { var result = true; if (!obj) { return result; } $.each(obj, function (key, val) { if (!(result = test.call(null, val, key, obj))) { return false; } }); return !!result; }, some: function (obj, test) { var result = false; if (!obj) { return result; } $.each(obj, function (key, val) { if (result = test.call(null, val, key, obj)) { return false; } }); return !!result; }, mixin: $.extend, getUniqueId: function () { var counter = 0; return function () { return counter++; }; }(), templatify: function templatify(obj) { return $.isFunction(obj) ? obj : template; function template() { return String(obj); } }, defer: function (fn) { setTimeout(fn, 0); }, debounce: function (func, wait, immediate) { var timeout, result; return function () { var context = this, args = arguments, later, callNow; later = function () { timeout = null; if (!immediate) { result = func.apply(context, args); } }; callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); } return result; }; }, throttle: function (func, wait) { var context, args, timeout, result, previous, later; previous = 0; later = function () { previous = new Date(); timeout = null; result = func.apply(context, args); }; return function () { var now = new Date(), remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; }, noop: function () { } }; var VERSION = "0.10.0"; var LruCache = function (root, undefined) { function LruCache(maxSize) { this.maxSize = maxSize || 100; this.size = 0; this.hash = {}; this.list = new List(); } _.mixin(LruCache.prototype, { set: function set(key, val) { var tailItem = this.list.tail, node; if (this.size >= this.maxSize) { this.list.remove(tailItem); delete this.hash[tailItem.key]; } if (node = this.hash[key]) { node.val = val; this.list.moveToFront(node); } else { node = new Node(key, val); this.list.add(node); this.hash[key] = node; this.size++; } }, get: function get(key) { var node = this.hash[key]; if (node) { this.list.moveToFront(node); return node.val; } } }); function List() { this.head = this.tail = null; } _.mixin(List.prototype, { add: function add(node) { if (this.head) { node.next = this.head; this.head.prev = node; } this.head = node; this.tail = this.tail || node; }, remove: function remove(node) { node.prev ? node.prev.next = node.next : this.head = node.next; node.next ? node.next.prev = node.prev : this.tail = node.prev; }, moveToFront: function (node) { this.remove(node); this.add(node); } }); function Node(key, val) { this.key = key; this.val = val; this.prev = this.next = null; } return LruCache; }(this); var PersistentStorage = function () { var ls, methods; try { ls = window.localStorage; ls.setItem("~~~", "!"); ls.removeItem("~~~"); } catch (err) { ls = null; } function PersistentStorage(namespace) { this.prefix = [ "__", namespace, "__" ].join(""); this.ttlKey = "__ttl__"; this.keyMatcher = new RegExp("^" + this.prefix); } if (ls && window.JSON) { methods = { _prefix: function (key) { return this.prefix + key; }, _ttlKey: function (key) { return this._prefix(key) + this.ttlKey; }, get: function (key) { if (this.isExpired(key)) { this.remove(key); } return decode(ls.getItem(this._prefix(key))); }, set: function (key, val, ttl) { if (_.isNumber(ttl)) { ls.setItem(this._ttlKey(key), encode(now() + ttl)); } else { ls.removeItem(this._ttlKey(key)); } return ls.setItem(this._prefix(key), encode(val)); }, remove: function (key) { ls.removeItem(this._ttlKey(key)); ls.removeItem(this._prefix(key)); return this; }, clear: function () { var i, key, keys = [], len = ls.length; for (i = 0; i < len; i++) { if ((key = ls.key(i)).match(this.keyMatcher)) { keys.push(key.replace(this.keyMatcher, "")); } } for (i = keys.length; i--;) { this.remove(keys[i]); } return this; }, isExpired: function (key) { var ttl = decode(ls.getItem(this._ttlKey(key))); return _.isNumber(ttl) && now() > ttl ? true : false; } }; } else { methods = { get: _.noop, set: _.noop, remove: _.noop, clear: _.noop, isExpired: _.noop }; } _.mixin(PersistentStorage.prototype, methods); return PersistentStorage; function now() { return new Date().getTime(); } function encode(val) { return JSON.stringify(_.isUndefined(val) ? null : val); } function decode(val) { return JSON.parse(val); } }(); var Transport = function () { var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests = 6, requestCache = new LruCache(10); function Transport(o) { o = o || {}; this._send = o.send ? callbackToDeferred(o.send) : $.ajax; this._get = o.rateLimiter ? o.rateLimiter(this._get) : this._get; } Transport.setMaxPendingRequests = function setMaxPendingRequests(num) { maxPendingRequests = num; }; Transport.resetCache = function clearCache() { requestCache = new LruCache(10); }; _.mixin(Transport.prototype, { _get: function (url, o, cb) { var that = this, jqXhr; if (jqXhr = pendingRequests[url]) { jqXhr.done(done); } else if (pendingRequestsCount < maxPendingRequests) { pendingRequestsCount++; pendingRequests[url] = this._send(url, o).done(done).always(always); } else { this.onDeckRequestArgs = [].slice.call(arguments, 0); } function done(resp) { cb && cb(resp); requestCache.set(url, resp); } function always() { pendingRequestsCount--; delete pendingRequests[url]; if (that.onDeckRequestArgs) { that._get.apply(that, that.onDeckRequestArgs); that.onDeckRequestArgs = null; } } }, get: function (url, o, cb) { var that = this, resp; if (_.isFunction(o)) { cb = o; o = {}; } if (resp = requestCache.get(url)) { _.defer(function () { cb && cb(resp); }); } else { this._get(url, o, cb); } return !!resp; } }); return Transport; function callbackToDeferred(fn) { return function customSendWrapper(url, o) { var deferred = $.Deferred(); fn(url, o, onSuccess, onError); return deferred; function onSuccess(resp) { _.defer(function () { deferred.resolve(resp); }); } function onError(err) { _.defer(function () { deferred.reject(err); }); } }; } }(); var SearchIndex = function () { function SearchIndex(o) { o = o || {}; if (!o.datumTokenizer || !o.queryTokenizer) { $.error("datumTokenizer and queryTokenizer are both required"); } this.datumTokenizer = o.datumTokenizer; this.queryTokenizer = o.queryTokenizer; this.datums = []; this.trie = newNode(); } _.mixin(SearchIndex.prototype, { bootstrap: function bootstrap(o) { this.datums = o.datums; this.trie = o.trie; }, add: function (data) { var that = this; data = _.isArray(data) ? data : [ data ]; _.each(data, function (datum) { var id, tokens; id = that.datums.push(datum) - 1; tokens = normalizeTokens(that.datumTokenizer(datum)); _.each(tokens, function (token) { var node, chars, ch, ids; node = that.trie; chars = token.split(""); while (ch = chars.shift()) { node = node.children[ch] || (node.children[ch] = newNode()); node.ids.push(id); } }); }); }, get: function get(query) { var that = this, tokens, matches; tokens = normalizeTokens(this.queryTokenizer(query)); _.each(tokens, function (token) { var node, chars, ch, ids; if (matches && matches.length === 0) { return false; } node = that.trie; chars = token.split(""); while (node && (ch = chars.shift())) { node = node.children[ch]; } if (node && chars.length === 0) { ids = node.ids.slice(0); matches = matches ? getIntersection(matches, ids) : ids; } else { matches = []; return false; } }); return matches ? _.map(unique(matches), function (id) { return that.datums[id]; }) : []; }, serialize: function serialize() { return { datums: this.datums, trie: this.trie }; } }); return SearchIndex; function normalizeTokens(tokens) { tokens = _.filter(tokens, function (token) { return !!token; }); tokens = _.map(tokens, function (token) { return token.toLowerCase(); }); return tokens; } function newNode() { return { ids: [], children: {} }; } function unique(array) { var seen = {}, uniques = []; for (var i = 0; i < array.length; i++) { if (!seen[array[i]]) { seen[array[i]] = true; uniques.push(array[i]); } } return uniques; } function getIntersection(arrayA, arrayB) { var ai = 0, bi = 0, intersection = []; arrayA = arrayA.sort(compare); arrayB = arrayB.sort(compare); while (ai < arrayA.length && bi < arrayB.length) { if (arrayA[ai] < arrayB[bi]) { ai++; } else if (arrayA[ai] > arrayB[bi]) { bi++; } else { intersection.push(arrayA[ai]); ai++; bi++; } } return intersection; function compare(a, b) { return a - b; } } }(); var oParser = function () { return { local: getLocal, prefetch: getPrefetch, remote: getRemote }; function getLocal(o) { return o.local || null; } function getPrefetch(o) { var prefetch, defaults; defaults = { url: null, thumbprint: "", ttl: 24 * 60 * 60 * 1e3, filter: null, ajax: {} }; if (prefetch = o.prefetch || null) { prefetch = _.isString(prefetch) ? { url: prefetch } : prefetch; prefetch = _.mixin(defaults, prefetch); prefetch.thumbprint = VERSION + prefetch.thumbprint; prefetch.ajax.method = prefetch.ajax.method || "get"; prefetch.ajax.dataType = prefetch.ajax.dataType || "json"; !prefetch.url && $.error("prefetch requires url to be set"); } return prefetch; } function getRemote(o) { var remote, defaults; defaults = { url: null, wildcard: "%QUERY", replace: null, rateLimitBy: "debounce", rateLimitWait: 300, send: null, filter: null, ajax: {} }; if (remote = o.remote || null) { remote = _.isString(remote) ? { url: remote } : remote; remote = _.mixin(defaults, remote); remote.rateLimiter = /^throttle$/i.test(remote.rateLimitBy) ? byThrottle(remote.rateLimitWait) : byDebounce(remote.rateLimitWait); remote.ajax.method = remote.ajax.method || "get"; remote.ajax.dataType = remote.ajax.dataType || "json"; delete remote.rateLimitBy; delete remote.rateLimitWait; !remote.url && $.error("remote requires url to be set"); } return remote; function byDebounce(wait) { return function (fn) { return _.debounce(fn, wait); }; } function byThrottle(wait) { return function (fn) { return _.throttle(fn, wait); }; } } }(); var Bloodhound = window.Bloodhound = function () { var keys; keys = { data: "data", protocol: "protocol", thumbprint: "thumbprint" }; function Bloodhound(o) { if (!o || !o.local && !o.prefetch && !o.remote) { $.error("one of local, prefetch, or remote is required"); } this.limit = o.limit || 5; this.sorter = o.sorter || noSort; this.dupDetector = o.dupDetector || ignoreDuplicates; this.local = oParser.local(o); this.prefetch = oParser.prefetch(o); this.remote = oParser.remote(o); this.cacheKey = this.prefetch ? this.prefetch.cacheKey || this.prefetch.url : null; this.index = new SearchIndex({ datumTokenizer: o.datumTokenizer, queryTokenizer: o.queryTokenizer }); this.storage = this.cacheKey ? new PersistentStorage(this.cacheKey) : null; } Bloodhound.tokenizers = { whitespace: function whitespaceTokenizer(s) { return s.split(/\s+/); }, nonword: function nonwordTokenizer(s) { return s.split(/\W+/); } }; _.mixin(Bloodhound.prototype, { _loadPrefetch: function loadPrefetch(o) { var that = this, serialized, deferred; if (serialized = this._readFromStorage(o.thumbprint)) { this.index.bootstrap(serialized); deferred = $.Deferred().resolve(); } else { deferred = $.ajax(o.url, o.ajax).done(handlePrefetchResponse); } return deferred; function handlePrefetchResponse(resp) { var filtered; filtered = o.filter ? o.filter(resp) : resp; that.add(filtered); that._saveToStorage(that.index.serialize(), o.thumbprint, o.ttl); } }, _getFromRemote: function getFromRemote(query, cb) { var that = this, url, uriEncodedQuery; query = query || ""; uriEncodedQuery = encodeURIComponent(query); url = this.remote.replace ? this.remote.replace(this.remote.url, query) : this.remote.url.replace(this.remote.wildcard, uriEncodedQuery); return this.transport.get(url, this.remote.ajax, handleRemoteResponse); function handleRemoteResponse(resp) { var filtered = that.remote.filter ? that.remote.filter(resp) : resp; cb(filtered); } }, _saveToStorage: function saveToStorage(data, thumbprint, ttl) { if (this.storage) { this.storage.set(keys.data, data, ttl); this.storage.set(keys.protocol, location.protocol, ttl); this.storage.set(keys.thumbprint, thumbprint, ttl); } }, _readFromStorage: function readFromStorage(thumbprint) { var stored = {}; if (this.storage) { stored.data = this.storage.get(keys.data); stored.protocol = this.storage.get(keys.protocol); stored.thumbprint = this.storage.get(keys.thumbprint); } isExpired = stored.thumbprint !== thumbprint || stored.protocol !== location.protocol; return stored.data && !isExpired ? stored.data : null; }, initialize: function initialize() { var that = this, deferred; deferred = this.prefetch ? this._loadPrefetch(this.prefetch) : $.Deferred().resolve(); this.local && deferred.done(addLocalToIndex); this.transport = this.remote ? new Transport(this.remote) : null; this.initialize = function initialize() { return deferred.promise(); }; return deferred.promise(); function addLocalToIndex() { that.add(that.local); } }, add: function add(data) { this.index.add(data); }, get: function get(query, cb) { var that = this, matches, cacheHit = false; matches = this.index.get(query).sort(this.sorter).slice(0, this.limit); if (matches.length < this.limit && this.transport) { cacheHit = this._getFromRemote(query, returnRemoteMatches); } !cacheHit && cb && cb(matches); function returnRemoteMatches(remoteMatches) { var matchesWithBackfill = matches.slice(0); _.each(remoteMatches, function (remoteMatch) { var isDuplicate; isDuplicate = _.some(matchesWithBackfill, function (match) { return that.dupDetector(remoteMatch, match); }); !isDuplicate && matchesWithBackfill.push(remoteMatch); return matchesWithBackfill.length < that.limit; }); cb && cb(matchesWithBackfill.sort(that.sorter)); } }, ttAdapter: function ttAdapter() { return _.bind(this.get, this); } }); return Bloodhound; function noSort() { return 0; } function ignoreDuplicates() { return false; } }(); var html = { wrapper: '<span class="twitter-typeahead"></span>', dropdown: '<span class="tt-dropdown-menu"></span>', dataset: '<div class="tt-dataset-%CLASS%"></div>', suggestions: '<span class="tt-suggestions"></span>', suggestion: '<div class="tt-suggestion">%BODY%</div>' }; var css = { wrapper: { position: "relative", display: "inline-block" }, hint: { position: "absolute", top: "0", left: "0", borderColor: "transparent", boxShadow: "none" }, input: { position: "relative", verticalAlign: "top", backgroundColor: "transparent" }, inputWithNoHint: { position: "relative", verticalAlign: "top" }, dropdown: { position: "absolute", top: "100%", left: "0", zIndex: "100", display: "none" }, suggestions: { display: "block" }, suggestion: { whiteSpace: "nowrap", cursor: "pointer" }, suggestionChild: { whiteSpace: "normal" }, ltr: { left: "0", right: "auto" }, rtl: { left: "auto", right: " 0" } }; if (_.isMsie()) { _.mixin(css.input, { backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)" }); } if (_.isMsie() && _.isMsie() <= 7) { _.mixin(css.input, { marginTop: "-1px" }); } var EventBus = function () { var namespace = "typeahead:"; function EventBus(o) { if (!o || !o.el) { $.error("EventBus initialized without el"); } this.$el = $(o.el); } _.mixin(EventBus.prototype, { trigger: function (type) { var args = [].slice.call(arguments, 1); this.$el.trigger(namespace + type, args); } }); return EventBus; }(); var EventEmitter = function () { var splitter = /\s+/, nextTick = getNextTick(); return { onSync: onSync, onAsync: onAsync, off: off, trigger: trigger }; function on(method, types, cb, context) { var type; if (!cb) { return this; } types = types.split(splitter); cb = context ? bindContext(cb, context) : cb; this._callbacks = this._callbacks || {}; while (type = types.shift()) { this._callbacks[type] = this._callbacks[type] || { sync: [], async: [] }; this._callbacks[type][method].push(cb); } return this; } function onAsync(types, cb, context) { return on.call(this, "async", types, cb, context); } function onSync(types, cb, context) { return on.call(this, "sync", types, cb, context); } function off(types) { var type; if (!this._callbacks) { return this; } types = types.split(splitter); while (type = types.shift()) { delete this._callbacks[type]; } return this; } function trigger(types) { var that = this, type, callbacks, args, syncFlush, asyncFlush; if (!this._callbacks) { return this; } types = types.split(splitter); args = [].slice.call(arguments, 1); while ((type = types.shift()) && (callbacks = this._callbacks[type])) { syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args)); asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args)); syncFlush() && nextTick(asyncFlush); } return this; } function getFlush(callbacks, context, args) { return flush; function flush() { var cancelled; for (var i = 0; !cancelled && i < callbacks.length; i += 1) { cancelled = callbacks[i].apply(context, args) === false; } return !cancelled; } } function getNextTick() { var nextTickFn, messageChannel; if (window.setImmediate) { nextTickFn = function nextTickSetImmediate(fn) { setImmediate(function () { fn(); }); }; } else { nextTickFn = function nextTickSetTimeout(fn) { setTimeout(function () { fn(); }, 0); }; } return nextTickFn; } function bindContext(fn, context) { return fn.bind ? fn.bind(context) : function () { fn.apply(context, [].slice.call(arguments, 0)); }; } }(); var highlight = function (doc) { var defaults = { node: null, pattern: null, tagName: "strong", className: null, wordsOnly: false, caseSensitive: false }; return function hightlight(o) { var regex; o = _.mixin({}, defaults, o); if (!o.node || !o.pattern) { return; } o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ]; regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly); traverse(o.node, hightlightTextNode); function hightlightTextNode(textNode) { var match, patternNode; if (match = regex.exec(textNode.data)) { wrapperNode = doc.createElement(o.tagName); o.className && (wrapperNode.className = o.className); patternNode = textNode.splitText(match.index); patternNode.splitText(match[0].length); wrapperNode.appendChild(patternNode.cloneNode(true)); textNode.parentNode.replaceChild(wrapperNode, patternNode); } return !!match; } function traverse(el, hightlightTextNode) { var childNode, TEXT_NODE_TYPE = 3; for (var i = 0; i < el.childNodes.length; i++) { childNode = el.childNodes[i]; if (childNode.nodeType === TEXT_NODE_TYPE) { i += hightlightTextNode(childNode) ? 1 : 0; } else { traverse(childNode, hightlightTextNode); } } } }; function getRegex(patterns, caseSensitive, wordsOnly) { var escapedPatterns = [], regexStr; for (var i = 0; i < patterns.length; i++) { escapedPatterns.push(_.escapeRegExChars(patterns[i])); } regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")"; return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i"); } }(window.document); var Input = function () { var specialKeyCodeMap; specialKeyCodeMap = { 9: "tab", 27: "esc", 37: "left", 39: "right", 13: "enter", 38: "up", 40: "down" }; function Input(o) { var that = this, onBlur, onFocus, onKeydown, onInput; o = o || {}; if (!o.input) { $.error("input is missing"); } onBlur = _.bind(this._onBlur, this); onFocus = _.bind(this._onFocus, this); onKeydown = _.bind(this._onKeydown, this); onInput = _.bind(this._onInput, this); this.$hint = $(o.hint); this.$input = $(o.input).on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown); if (this.$hint.length === 0) { this.setHintValue = this.getHintValue = this.clearHint = _.noop; } if (!_.isMsie()) { this.$input.on("input.tt", onInput); } else { this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function ($e) { if (specialKeyCodeMap[$e.which || $e.keyCode]) { return; } _.defer(_.bind(that._onInput, that, $e)); }); } this.query = this.$input.val(); this.$overflowHelper = buildOverflowHelper(this.$input); } Input.normalizeQuery = function (str) { return (str || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " "); }; _.mixin(Input.prototype, EventEmitter, { _onBlur: function onBlur($e) { this.resetInputValue(); this.trigger("blurred"); }, _onFocus: function onFocus($e) { this.trigger("focused"); }, _onKeydown: function onKeydown($e) { var keyName = specialKeyCodeMap[$e.which || $e.keyCode]; this._managePreventDefault(keyName, $e); if (keyName && this._shouldTrigger(keyName, $e)) { this.trigger(keyName + "Keyed", $e); } }, _onInput: function onInput($e) { this._checkInputValue(); }, _managePreventDefault: function managePreventDefault(keyName, $e) { var preventDefault, hintValue, inputValue; switch (keyName) { case "tab": hintValue = this.getHintValue(); inputValue = this.getInputValue(); preventDefault = hintValue && hintValue !== inputValue && !withModifier($e); break; case "up": case "down": preventDefault = !withModifier($e); break; default: preventDefault = false; } preventDefault && $e.preventDefault(); }, _shouldTrigger: function shouldTrigger(keyName, $e) { var trigger; switch (keyName) { case "tab": trigger = !withModifier($e); break; default: trigger = true; } return trigger; }, _checkInputValue: function checkInputValue() { var inputValue, areEquivalent, hasDifferentWhitespace; inputValue = this.getInputValue(); areEquivalent = areQueriesEquivalent(inputValue, this.query); hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false; if (!areEquivalent) { this.trigger("queryChanged", this.query = inputValue); } else if (hasDifferentWhitespace) { this.trigger("whitespaceChanged", this.query); } }, focus: function focus() { this.$input.focus(); }, blur: function blur() { this.$input.blur(); }, getQuery: function getQuery() { return this.query; }, setQuery: function setQuery(query) { this.query = query; }, getInputValue: function getInputValue() { return this.$input.val(); }, setInputValue: function setInputValue(value, silent) { this.$input.val(value); !silent && this._checkInputValue(); }, getHintValue: function getHintValue() { return this.$hint.val(); }, setHintValue: function setHintValue(value) { this.$hint.val(value); }, resetInputValue: function resetInputValue() { this.$input.val(this.query); }, clearHint: function clearHint() { this.$hint.val(""); }, getLanguageDirection: function getLanguageDirection() { return (this.$input.css("direction") || "ltr").toLowerCase(); }, hasOverflow: function hasOverflow() { var constraint = this.$input.width() - 2; this.$overflowHelper.text(this.getInputValue()); return this.$overflowHelper.width() >= constraint; }, isCursorAtEnd: function () { var valueLength, selectionStart, range; valueLength = this.$input.val().length; selectionStart = this.$input[0].selectionStart; if (_.isNumber(selectionStart)) { return selectionStart === valueLength; } else if (document.selection) { range = document.selection.createRange(); range.moveStart("character", -valueLength); return valueLength === range.text.length; } return true; }, destroy: function destroy() { this.$hint.off(".tt"); this.$input.off(".tt"); this.$hint = this.$input = this.$overflowHelper = null; } }); return Input; function buildOverflowHelper($input) { return $('<pre aria-hidden="true"></pre>').css({ position: "absolute", visibility: "hidden", whiteSpace: "nowrap", fontFamily: $input.css("font-family"), fontSize: $input.css("font-size"), fontStyle: $input.css("font-style"), fontVariant: $input.css("font-variant"), fontWeight: $input.css("font-weight"), wordSpacing: $input.css("word-spacing"), letterSpacing: $input.css("letter-spacing"), textIndent: $input.css("text-indent"), textRendering: $input.css("text-rendering"), textTransform: $input.css("text-transform") }).insertAfter($input); } function areQueriesEquivalent(a, b) { return Input.normalizeQuery(a) === Input.normalizeQuery(b); } function withModifier($e) { return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey; } }(); var Dataset = function () { var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum"; function Dataset(o) { o = o || {}; o.templates = o.templates || {}; if (!o.source) { $.error("missing source"); } this.query = null; this.highlight = !!o.highlight; this.name = o.name || _.getUniqueId(); this.source = o.source; this.valueKey = o.displayKey || "value"; this.templates = getTemplates(o.templates, this.valueKey); this.$el = $(html.dataset.replace("%CLASS%", this.name)); } Dataset.extractDatasetName = function extractDatasetName(el) { return $(el).data(datasetKey); }; Dataset.extractValue = function extractDatum(el) { return $(el).data(valueKey); }; Dataset.extractDatum = function extractDatum(el) { return $(el).data(datumKey); }; _.mixin(Dataset.prototype, EventEmitter, { _render: function render(query, suggestions) { if (!this.$el) { return; } var that = this, hasSuggestions; this.$el.empty(); hasSuggestions = suggestions && suggestions.length; if (!hasSuggestions && this.templates.empty) { this.$el.html(getEmptyHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null); } else if (hasSuggestions) { this.$el.html(getSuggestionsHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null); } this.trigger("rendered"); function getEmptyHtml() { return that.templates.empty({ query: query }); } function getSuggestionsHtml() { var $suggestions; $suggestions = $(html.suggestions).css(css.suggestions).append(_.map(suggestions, getSuggestionNode)); that.highlight && highlight({ node: $suggestions[0], pattern: query }); return $suggestions; function getSuggestionNode(suggestion) { var $el, innerHtml, outerHtml; innerHtml = that.templates.suggestion(suggestion); outerHtml = html.suggestion.replace("%BODY%", innerHtml); $el = $(outerHtml).data(datasetKey, that.name).data(valueKey, suggestion[that.valueKey]).data(datumKey, suggestion); $el.children().each(function () { $(this).css(css.suggestionChild); }); return $el; } } function getHeaderHtml() { return that.templates.header({ query: query, isEmpty: !hasSuggestions }); } function getFooterHtml() { return that.templates.footer({ query: query, isEmpty: !hasSuggestions }); } }, getRoot: function getRoot() { return this.$el; }, update: function update(query) { var that = this; this.query = query; this.source(query, renderIfQueryIsSame); function renderIfQueryIsSame(suggestions) { query === that.query && that._render(query, suggestions); } }, clear: function clear() { this._render(this.query || ""); }, isEmpty: function isEmpty() { return this.$el.is(":empty"); }, destroy: function destroy() { this.$el = null; } }); return Dataset; function getTemplates(templates, valueKey) { return { empty: templates.empty && _.templatify(templates.empty), header: templates.header && _.templatify(templates.header), footer: templates.footer && _.templatify(templates.footer), suggestion: templates.suggestion || suggestionTemplate }; function suggestionTemplate(context) { return "<p>" + context[valueKey] + "</p>"; } } }(); var Dropdown = function () { function Dropdown(o) { var that = this, onMouseEnter, onMouseLeave, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave; o = o || {}; if (!o.menu) { $.error("menu is required"); } this.isOpen = false; this.isEmpty = true; this.isMouseOverDropdown = false; this.datasets = _.map(o.datasets, initializeDataset); onMouseEnter = _.bind(this._onMouseEnter, this); onMouseLeave = _.bind(this._onMouseLeave, this); onSuggestionClick = _.bind(this._onSuggestionClick, this); onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this); onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this); this.$menu = $(o.menu).on("mouseenter.tt", onMouseEnter).on("mouseleave.tt", onMouseLeave).on("click.tt", ".tt-suggestion", onSuggestionClick).on("mouseenter.tt", ".tt-suggestion", onSuggestionMouseEnter).on("mouseleave.tt", ".tt-suggestion", onSuggestionMouseLeave); _.each(this.datasets, function (dataset) { that.$menu.append(dataset.getRoot()); dataset.onSync("rendered", that._onRendered, that); }); } _.mixin(Dropdown.prototype, EventEmitter, { _onMouseEnter: function onMouseEnter($e) { this.isMouseOverDropdown = true; }, _onMouseLeave: function onMouseLeave($e) { this.isMouseOverDropdown = false; }, _onSuggestionClick: function onSuggestionClick($e) { this.trigger("suggestionClicked", $($e.currentTarget)); }, _onSuggestionMouseEnter: function onSuggestionMouseEnter($e) { this._removeCursor(); this._setCursor($($e.currentTarget), true); }, _onSuggestionMouseLeave: function onSuggestionMouseLeave($e) { this._removeCursor(); }, _onRendered: function onRendered() { this.isEmpty = _.every(this.datasets, isDatasetEmpty); this.isEmpty ? this._hide() : this.isOpen && this._show(); this.trigger("datasetRendered"); function isDatasetEmpty(dataset) { return dataset.isEmpty(); } }, _hide: function () { this.$menu.hide(); }, _show: function () { this.$menu.css("display", "block"); }, _getSuggestions: function getSuggestions() { return this.$menu.find(".tt-suggestion"); }, _getCursor: function getCursor() { return this.$menu.find(".tt-cursor").first(); }, _setCursor: function setCursor($el, silent) { $el.first().addClass("tt-cursor"); !silent && this.trigger("cursorMoved"); }, _removeCursor: function removeCursor() { this._getCursor().removeClass("tt-cursor"); }, _moveCursor: function moveCursor(increment) { var $suggestions, $oldCursor, newCursorIndex, $newCursor; if (!this.isOpen) { return; } $oldCursor = this._getCursor(); $suggestions = this._getSuggestions(); this._removeCursor(); newCursorIndex = $suggestions.index($oldCursor) + increment; newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1; if (newCursorIndex === -1) { this.trigger("cursorRemoved"); return; } else if (newCursorIndex < -1) { newCursorIndex = $suggestions.length - 1; } this._setCursor($newCursor = $suggestions.eq(newCursorIndex)); this._ensureVisible($newCursor); }, _ensureVisible: function ensureVisible($el) { var elTop, elBottom, menuScrollTop, menuHeight; elTop = $el.position().top; elBottom = elTop + $el.outerHeight(true); menuScrollTop = this.$menu.scrollTop(); menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10); if (elTop < 0) { this.$menu.scrollTop(menuScrollTop + elTop); } else if (menuHeight < elBottom) { this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight)); } }, close: function close() { if (this.isOpen) { this.isOpen = this.isMouseOverDropdown = false; this._removeCursor(); this._hide(); this.trigger("closed"); } }, open: function open() { if (!this.isOpen) { this.isOpen = true; !this.isEmpty && this._show(); this.trigger("opened"); } }, setLanguageDirection: function setLanguageDirection(dir) { this.$menu.css(dir === "ltr" ? css.ltr : css.rtl); }, moveCursorUp: function moveCursorUp() { this._moveCursor(-1); }, moveCursorDown: function moveCursorDown() { this._moveCursor(+1); }, getDatumForSuggestion: function getDatumForSuggestion($el) { var datum = null; if ($el.length) { datum = { raw: Dataset.extractDatum($el), value: Dataset.extractValue($el), datasetName: Dataset.extractDatasetName($el) }; } return datum; }, getDatumForCursor: function getDatumForCursor() { return this.getDatumForSuggestion(this._getCursor().first()); }, getDatumForTopSuggestion: function getDatumForTopSuggestion() { return this.getDatumForSuggestion(this._getSuggestions().first()); }, update: function update(query) { _.each(this.datasets, updateDataset); function updateDataset(dataset) { dataset.update(query); } }, empty: function empty() { _.each(this.datasets, clearDataset); function clearDataset(dataset) { dataset.clear(); } }, isVisible: function isVisible() { return this.isOpen && !this.isEmpty; }, destroy: function destroy() { this.$menu.off(".tt"); this.$menu = null; _.each(this.datasets, destroyDataset); function destroyDataset(dataset) { dataset.destroy(); } } }); return Dropdown; function initializeDataset(oDataset) { return new Dataset(oDataset); } }(); var Typeahead = function () { var attrsKey = "ttAttrs"; function Typeahead(o) { var $menu, $input, $hint, datasets; o = o || {}; if (!o.input) { $.error("missing input"); } this.autoselect = !!o.autoselect; this.minLength = _.isNumber(o.minLength) ? o.minLength : 1; this.$node = buildDomStructure(o.input, o.withHint); $menu = this.$node.find(".tt-dropdown-menu"); $input = this.$node.find(".tt-input"); $hint = this.$node.find(".tt-hint"); this.eventBus = o.eventBus || new EventBus({ el: $input }); this.dropdown = new Dropdown({ menu: $menu, datasets: o.datasets }).onSync("suggestionClicked", this._onSuggestionClicked, this).onSync("cursorMoved", this._onCursorMoved, this).onSync("cursorRemoved", this._onCursorRemoved, this).onSync("opened", this._onOpened, this).onSync("closed", this._onClosed, this).onAsync("datasetRendered", this._onDatasetRendered, this); this.input = new Input({ input: $input, hint: $hint }).onSync("focused", this._onFocused, this).onSync("blurred", this._onBlurred, this).onSync("enterKeyed", this._onEnterKeyed, this).onSync("tabKeyed", this._onTabKeyed, this).onSync("escKeyed", this._onEscKeyed, this).onSync("upKeyed", this._onUpKeyed, this).onSync("downKeyed", this._onDownKeyed, this).onSync("leftKeyed", this._onLeftKeyed, this).onSync("rightKeyed", this._onRightKeyed, this).onSync("queryChanged", this._onQueryChanged, this).onSync("whitespaceChanged", this._onWhitespaceChanged, this); $menu.on("mousedown.tt", function ($e) { if (_.isMsie() && _.isMsie() < 9) { $input[0].onbeforedeactivate = function () { window.event.returnValue = false; $input[0].onbeforedeactivate = null; }; } $e.preventDefault(); }); } _.mixin(Typeahead.prototype, { _onSuggestionClicked: function onSuggestionClicked(type, $el) { var datum; if (datum = this.dropdown.getDatumForSuggestion($el)) { this._select(datum); } }, _onCursorMoved: function onCursorMoved() { var datum = this.dropdown.getDatumForCursor(); this.input.clearHint(); this.input.setInputValue(datum.value, true); this.eventBus.trigger("cursorchanged", datum.raw, datum.datasetName); }, _onCursorRemoved: function onCursorRemoved() { this.input.resetInputValue(); this._updateHint(); }, _onDatasetRendered: function onDatasetRendered() { this._updateHint(); }, _onOpened: function onOpened() { this._updateHint(); this.eventBus.trigger("opened"); }, _onClosed: function onClosed() { this.input.clearHint(); this.eventBus.trigger("closed"); }, _onFocused: function onFocused() { this.dropdown.open(); }, _onBlurred: function onBlurred() { !this.dropdown.isMouseOverDropdown && this.dropdown.close(); }, _onEnterKeyed: function onEnterKeyed(type, $e) { var cursorDatum, topSuggestionDatum; cursorDatum = this.dropdown.getDatumForCursor(); topSuggestionDatum = this.dropdown.getDatumForTopSuggestion(); if (cursorDatum) { this._select(cursorDatum); $e.preventDefault(); } else if (this.autoselect && topSuggestionDatum) { this._select(topSuggestionDatum); $e.preventDefault(); } }, _onTabKeyed: function onTabKeyed(type, $e) { var datum; if (datum = this.dropdown.getDatumForCursor()) { this._select(datum); $e.preventDefault(); } else { this._autocomplete(); } }, _onEscKeyed: function onEscKeyed() { this.dropdown.close(); this.input.resetInputValue(); }, _onUpKeyed: function onUpKeyed() { var query = this.input.getQuery(); if (!this.dropdown.isOpen && query.length >= this.minLength) { this.dropdown.update(query); } this.dropdown.open(); this.dropdown.moveCursorUp(); }, _onDownKeyed: function onDownKeyed() { var query = this.input.getQuery(); if (!this.dropdown.isOpen && query.length >= this.minLength) { this.dropdown.update(query); } this.dropdown.open(); this.dropdown.moveCursorDown(); }, _onLeftKeyed: function onLeftKeyed() { this.dir === "rtl" && this._autocomplete(); }, _onRightKeyed: function onRightKeyed() { this.dir === "ltr" && this._autocomplete(); }, _onQueryChanged: function onQueryChanged(e, query) { this.input.clearHint(); this.dropdown.empty(); query.length >= this.minLength && this.dropdown.update(query); this.dropdown.open(); this._setLanguageDirection(); }, _onWhitespaceChanged: function onWhitespaceChanged() { this._updateHint(); this.dropdown.open(); }, _setLanguageDirection: function setLanguageDirection() { var dir; if (this.dir !== (dir = this.input.getLanguageDirection())) { this.dir = dir; this.$node.css("direction", dir); this.dropdown.setLanguageDirection(dir); } }, _updateHint: function updateHint() { var datum, inputValue, query, escapedQuery, frontMatchRegEx, match; datum = this.dropdown.getDatumForTopSuggestion(); if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) { inputValue = this.input.getInputValue(); query = Input.normalizeQuery(inputValue); escapedQuery = _.escapeRegExChars(query); frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.*$)", "i"); match = frontMatchRegEx.exec(datum.value); this.input.setHintValue(inputValue + (match ? match[1] : "")); } }, _autocomplete: function autocomplete() { var hint, query, datum; hint = this.input.getHintValue(); query = this.input.getQuery(); if (hint && query !== hint && this.input.isCursorAtEnd()) { datum = this.dropdown.getDatumForTopSuggestion(); datum && this.input.setInputValue(datum.value); this.eventBus.trigger("autocompleted", datum.raw, datum.datasetName); } }, _select: function select(datum) { this.input.clearHint(); this.input.setQuery(datum.value); this.input.setInputValue(datum.value, true); this.dropdown.empty(); this._setLanguageDirection(); _.defer(_.bind(this.dropdown.close, this.dropdown)); this.eventBus.trigger("selected", datum.raw, datum.datasetName); }, open: function open() { this.dropdown.open(); }, close: function close() { this.dropdown.close(); }, getQuery: function getQuery() { return this.input.getQuery(); }, setQuery: function setQuery(val) { this.input.setInputValue(val); }, destroy: function destroy() { this.input.destroy(); this.dropdown.destroy(); destroyDomStructure(this.$node); this.$node = null; } }); return Typeahead; function buildDomStructure(input, withHint) { var $input, $wrapper, $dropdown, $hint; $input = $(input); $wrapper = $(html.wrapper).css(css.wrapper); $dropdown = $(html.dropdown).css(css.dropdown); $hint = $input.clone().css(css.hint).css(getBackgroundStyles($input)); $hint.removeData().addClass("tt-hint").removeAttr("id name placeholder").prop("disabled", true).attr({ autocomplete: "off", spellcheck: "false" }); $input.data(attrsKey, { dir: $input.attr("dir"), autocomplete: $input.attr("autocomplete"), spellcheck: $input.attr("spellcheck"), style: $input.attr("style") }); $input.addClass("tt-input").attr({ autocomplete: "off", spellcheck: false }).css(withHint ? css.input : css.inputWithNoHint); try { !$input.attr("dir") && $input.attr("dir", "auto"); } catch (e) { } return $input.wrap($wrapper).parent().prepend(withHint ? $hint : null).append($dropdown); } function getBackgroundStyles($el) { return { backgroundAttachment: $el.css("background-attachment"), backgroundClip: $el.css("background-clip"), backgroundColor: $el.css("background-color"), backgroundImage: $el.css("background-image"), backgroundOrigin: $el.css("background-origin"), backgroundPosition: $el.css("background-position"), backgroundRepeat: $el.css("background-repeat"), backgroundSize: $el.css("background-size") }; } function destroyDomStructure($node) { var $input = $node.find(".tt-input"); _.each($input.data(attrsKey), function (val, key) { _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val); }); $input.detach().removeData(attrsKey).removeClass("tt-input").insertAfter($node); $node.remove(); } }(); (function () { var typeaheadKey, methods; typeaheadKey = "ttTypeahead"; methods = { initialize: function initialize(o) { var datasets = [].slice.call(arguments, 1); o = o || {}; return this.each(attach); function attach() { var $input = $(this), eventBus, typeahead; _.each(datasets, function (d) { d.highlight = !!o.highlight; }); typeahead = new Typeahead({ input: $input, eventBus: eventBus = new EventBus({ el: $input }), withHint: _.isUndefined(o.hint) ? true : !!o.hint, minLength: o.minLength, autoselect: o.autoselect, datasets: datasets }); $input.data(typeaheadKey, typeahead); function trigger(eventName) { return function () { _.defer(function () { eventBus.trigger(eventName); }); }; } } }, open: function open() { return this.each(openTypeahead); function openTypeahead() { var $input = $(this), typeahead; if (typeahead = $input.data(typeaheadKey)) { typeahead.open(); } } }, close: function close() { return this.each(closeTypeahead); function closeTypeahead() { var $input = $(this), typeahead; if (typeahead = $input.data(typeaheadKey)) { typeahead.close(); } } }, val: function val(newVal) { return _.isString(newVal) ? this.each(setQuery) : this.map(getQuery).get(); function setQuery() { var $input = $(this), typeahead; if (typeahead = $input.data(typeaheadKey)) { typeahead.setQuery(newVal); } } function getQuery() { var $input = $(this), typeahead, query; if (typeahead = $input.data(typeaheadKey)) { query = typeahead.getQuery(); } return query; } }, destroy: function destroy() { return this.each(unattach); function unattach() { var $input = $(this), typeahead; if (typeahead = $input.data(typeaheadKey)) { typeahead.destroy(); $input.removeData(typeaheadKey); } } } }; jQuery.fn.typeahead = function (method) { if (methods[method]) { return methods[method].apply(this, [].slice.call(arguments, 1)); } else { return methods.initialize.apply(this, arguments); } }; })(); })(window.jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-typeahead.js
jquery-typeahead.js
(function($) { var Slider = function(element, options) { this.element = $(element); this.picker = $('<div class="slider">'+ '<div class="slider-track">'+ '<div class="slider-selection"></div>'+ '<div class="slider-handle"></div>'+ '<div class="slider-handle"></div>'+ '</div>'+ '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'+ '</div>') .insertBefore(this.element) .prepend(this.element); this.id = this.element.data('slider-id')||options.id; if (this.id) { this.picker[0].id = this.id; } if (typeof Modernizr !== 'undefined' && Modernizr.touch) { this.touchCapable = true; } var tooltip = this.element.data('slider-tooltip')||options.tooltip; this.tooltip = this.picker.find('.tooltip'); this.tooltipInner = this.tooltip.find('div.tooltip-inner'); this.orientation = this.element.data('slider-orientation')||options.orientation; switch(this.orientation) { case 'vertical': this.picker.addClass('slider-vertical'); this.stylePos = 'top'; this.mousePos = 'pageY'; this.sizePos = 'offsetHeight'; this.tooltip.addClass('right')[0].style.left = '100%'; break; default: this.picker .addClass('slider-horizontal') .css('width', this.element.outerWidth()); this.orientation = 'horizontal'; this.stylePos = 'left'; this.mousePos = 'pageX'; this.sizePos = 'offsetWidth'; this.tooltip.addClass('top')[0].style.top = -this.tooltip.outerHeight() - 14 + 'px'; break; } this.min = this.element.data('slider-min')||options.min; this.max = this.element.data('slider-max')||options.max; this.step = this.element.data('slider-step')||options.step; this.value = this.element.data('slider-value')||options.value; if (this.value[1]) { this.range = true; } this.selection = this.element.data('slider-selection')||options.selection; this.selectionEl = this.picker.find('.slider-selection'); if (this.selection === 'none') { this.selectionEl.addClass('hide'); } this.selectionElStyle = this.selectionEl[0].style; this.handle1 = this.picker.find('.slider-handle:first'); this.handle1Stype = this.handle1[0].style; this.handle2 = this.picker.find('.slider-handle:last'); this.handle2Stype = this.handle2[0].style; var handle = this.element.data('slider-handle')||options.handle; switch(handle) { case 'round': this.handle1.addClass('round'); this.handle2.addClass('round'); break case 'triangle': this.handle1.addClass('triangle'); this.handle2.addClass('triangle'); break } if (this.range) { this.value[0] = Math.max(this.min, Math.min(this.max, this.value[0])); this.value[1] = Math.max(this.min, Math.min(this.max, this.value[1])); } else { this.value = [ Math.max(this.min, Math.min(this.max, this.value))]; this.handle2.addClass('hide'); if (this.selection === 'after') { this.value[1] = this.max; } else { this.value[1] = this.min; } } this.diff = this.max - this.min; this.percentage = [ (this.value[0]-this.min)*100/this.diff, (this.value[1]-this.min)*100/this.diff, this.step*100/this.diff ]; this.offset = this.picker.offset(); this.size = this.picker[0][this.sizePos]; this.formater = options.formater; this.layout(); if (this.touchCapable) { // Touch: Bind touch events: this.picker.on({ touchstart: $.proxy(this.mousedown, this) }); } else { this.picker.on({ mousedown: $.proxy(this.mousedown, this) }); } if (tooltip === 'show') { this.picker.on({ mouseenter: $.proxy(this.showTooltip, this), mouseleave: $.proxy(this.hideTooltip, this) }); } else { this.tooltip.addClass('hide'); } }; Slider.prototype = { constructor: Slider, over: false, inDrag: false, showTooltip: function(){ this.tooltip.addClass('in'); //var left = Math.round(this.percent*this.width); //this.tooltip.css('left', left - this.tooltip.outerWidth()/2); this.over = true; }, hideTooltip: function(){ if (this.inDrag === false) { this.tooltip.removeClass('in'); } this.over = false; }, layout: function(){ this.handle1Stype[this.stylePos] = this.percentage[0]+'%'; this.handle2Stype[this.stylePos] = this.percentage[1]+'%'; if (this.orientation === 'vertical') { this.selectionElStyle.top = Math.min(this.percentage[0], this.percentage[1]) +'%'; this.selectionElStyle.height = Math.abs(this.percentage[0] - this.percentage[1]) +'%'; } else { this.selectionElStyle.left = Math.min(this.percentage[0], this.percentage[1]) +'%'; this.selectionElStyle.width = Math.abs(this.percentage[0] - this.percentage[1]) +'%'; } if (this.range) { this.tooltipInner.text( this.formater(this.value[0]) + ' : ' + this.formater(this.value[1]) ); this.tooltip[0].style[this.stylePos] = this.size * (this.percentage[0] + (this.percentage[1] - this.percentage[0])/2)/100 - (this.orientation === 'vertical' ? this.tooltip.outerHeight()/2 : this.tooltip.outerWidth()/2) +'px'; } else { this.tooltipInner.text( this.formater(this.value[0]) ); this.tooltip[0].style[this.stylePos] = this.size * this.percentage[0]/100 - (this.orientation === 'vertical' ? this.tooltip.outerHeight()/2 : this.tooltip.outerWidth()/2) +'px'; } }, mousedown: function(ev) { // Touch: Get the original event: if (this.touchCapable && ev.type === 'touchstart') { ev = ev.originalEvent; } this.offset = this.picker.offset(); this.size = this.picker[0][this.sizePos]; var percentage = this.getPercentage(ev); if (this.range) { var diff1 = Math.abs(this.percentage[0] - percentage); var diff2 = Math.abs(this.percentage[1] - percentage); this.dragged = (diff1 < diff2) ? 0 : 1; } else { this.dragged = 0; } this.percentage[this.dragged] = percentage; this.layout(); if (this.touchCapable) { // Touch: Bind touch events: $(document).on({ touchmove: $.proxy(this.mousemove, this), touchend: $.proxy(this.mouseup, this) }); } else { $(document).on({ mousemove: $.proxy(this.mousemove, this), mouseup: $.proxy(this.mouseup, this) }); } this.inDrag = true; var val = this.calculateValue(); this.element.trigger({ type: 'slideStart', value: val }).trigger({ type: 'slide', value: val }); return false; }, mousemove: function(ev) { // Touch: Get the original event: if (this.touchCapable && ev.type === 'touchmove') { ev = ev.originalEvent; } var percentage = this.getPercentage(ev); if (this.range) { if (this.dragged === 0 && this.percentage[1] < percentage) { this.percentage[0] = this.percentage[1]; this.dragged = 1; } else if (this.dragged === 1 && this.percentage[0] > percentage) { this.percentage[1] = this.percentage[0]; this.dragged = 0; } } this.percentage[this.dragged] = percentage; this.layout(); var val = this.calculateValue(); this.element .trigger({ type: 'slide', value: val }) .data('value', val) .prop('value', val); return false; }, mouseup: function(ev) { if (this.touchCapable) { // Touch: Bind touch events: $(document).off({ touchmove: this.mousemove, touchend: this.mouseup }); } else { $(document).off({ mousemove: this.mousemove, mouseup: this.mouseup }); } this.inDrag = false; if (this.over == false) { this.hideTooltip(); } this.element; var val = this.calculateValue(); this.element .trigger({ type: 'slideStop', value: val }) .data('value', val) .prop('value', val); return false; }, calculateValue: function() { var val; if (this.range) { val = [ (this.min + Math.round((this.diff * this.percentage[0]/100)/this.step)*this.step), (this.min + Math.round((this.diff * this.percentage[1]/100)/this.step)*this.step) ]; this.value = val; } else { val = (this.min + Math.round((this.diff * this.percentage[0]/100)/this.step)*this.step); this.value = [val, this.value[1]]; } return val; }, getPercentage: function(ev) { if (this.touchCapable) { ev = ev.touches[0]; } var percentage = (ev[this.mousePos] - this.offset[this.stylePos])*100/this.size; percentage = Math.round(percentage/this.percentage[2])*this.percentage[2]; return Math.max(0, Math.min(100, percentage)); }, getValue: function() { if (this.range) { return this.value; } return this.value[0]; }, setValue: function(val) { this.value = val; if (this.range) { this.value[0] = Math.max(this.min, Math.min(this.max, this.value[0])); this.value[1] = Math.max(this.min, Math.min(this.max, this.value[1])); } else { this.value = [ Math.max(this.min, Math.min(this.max, this.value))]; this.handle2.addClass('hide'); if (this.selection === 'after') { this.value[1] = this.max; } else { this.value[1] = this.min; } } this.diff = this.max - this.min; this.percentage = [ (this.value[0]-this.min)*100/this.diff, (this.value[1]-this.min)*100/this.diff, this.step*100/this.diff ]; this.layout(); } }; $.fn.slider = function ( option, val ) { return this.each(function () { var $this = $(this), data = $this.data('slider'), options = typeof option === 'object' && option; if (!data) { $this.data('slider', (data = new Slider(this, $.extend({}, $.fn.slider.defaults,options)))); } if (typeof option === 'string') { data[option](val); } }); }; $.fn.slider.defaults = { min: 0, max: 10, step: 1, orientation: 'horizontal', value: 5, selection: 'before', tooltip: 'show', handle: 'round', formater: function(value) { return value; } }; $.fn.slider.Constructor = Slider; // Used by MyAMS to avoid conflict with JQuery-UI slider $.fn.BS_slider = $.fn.slider; })(window.jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/bootstrap-slider-2.0.0.js
bootstrap-slider-2.0.0.js
(function (B) { B.color = {}; B.color.make = function (F, E, C, D) { var G = {}; G.r = F || 0; G.g = E || 0; G.b = C || 0; G.a = D != null ? D : 1; G.add = function (J, I) { for (var H = 0; H < J.length; ++H) { G[J.charAt(H)] += I } return G.normalize() }; G.scale = function (J, I) { for (var H = 0; H < J.length; ++H) { G[J.charAt(H)] *= I } return G.normalize() }; G.toString = function () { if (G.a >= 1) { return"rgb(" + [G.r, G.g, G.b].join(",") + ")" } else { return"rgba(" + [G.r, G.g, G.b, G.a].join(",") + ")" } }; G.normalize = function () { function H(J, K, I) { return K < J ? J : (K > I ? I : K) } G.r = H(0, parseInt(G.r), 255); G.g = H(0, parseInt(G.g), 255); G.b = H(0, parseInt(G.b), 255); G.a = H(0, G.a, 1); return G }; G.clone = function () { return B.color.make(G.r, G.b, G.g, G.a) }; return G.normalize() }; B.color.extract = function (D, C) { var E; do { E = D.css(C).toLowerCase(); if (E != "" && E != "transparent") { break } D = D.parent() } while (!B.nodeName(D.get(0), "body")); if (E == "rgba(0, 0, 0, 0)") { E = "transparent" } return B.color.parse(E) }; B.color.parse = function (F) { var E, C = B.color.make; if (E = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)) { return C(parseInt(E[1], 10), parseInt(E[2], 10), parseInt(E[3], 10)) } if (E = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)) { return C(parseInt(E[1], 10), parseInt(E[2], 10), parseInt(E[3], 10), parseFloat(E[4])) } if (E = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)) { return C(parseFloat(E[1]) * 2.55, parseFloat(E[2]) * 2.55, parseFloat(E[3]) * 2.55) } if (E = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)) { return C(parseFloat(E[1]) * 2.55, parseFloat(E[2]) * 2.55, parseFloat(E[3]) * 2.55, parseFloat(E[4])) } if (E = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)) { return C(parseInt(E[1], 16), parseInt(E[2], 16), parseInt(E[3], 16)) } if (E = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)) { return C(parseInt(E[1] + E[1], 16), parseInt(E[2] + E[2], 16), parseInt(E[3] + E[3], 16)) } var D = B.trim(F).toLowerCase(); if (D == "transparent") { return C(255, 255, 255, 0) } else { E = A[D] || [0, 0, 0]; return C(E[0], E[1], E[2]) } }; var A = {aqua: [0, 255, 255], azure: [240, 255, 255], beige: [245, 245, 220], black: [0, 0, 0], blue: [0, 0, 255], brown: [165, 42, 42], cyan: [0, 255, 255], darkblue: [0, 0, 139], darkcyan: [0, 139, 139], darkgrey: [169, 169, 169], darkgreen: [0, 100, 0], darkkhaki: [189, 183, 107], darkmagenta: [139, 0, 139], darkolivegreen: [85, 107, 47], darkorange: [255, 140, 0], darkorchid: [153, 50, 204], darkred: [139, 0, 0], darksalmon: [233, 150, 122], darkviolet: [148, 0, 211], fuchsia: [255, 0, 255], gold: [255, 215, 0], green: [0, 128, 0], indigo: [75, 0, 130], khaki: [240, 230, 140], lightblue: [173, 216, 230], lightcyan: [224, 255, 255], lightgreen: [144, 238, 144], lightgrey: [211, 211, 211], lightpink: [255, 182, 193], lightyellow: [255, 255, 224], lime: [0, 255, 0], magenta: [255, 0, 255], maroon: [128, 0, 0], navy: [0, 0, 128], olive: [128, 128, 0], orange: [255, 165, 0], pink: [255, 192, 203], purple: [128, 0, 128], violet: [128, 0, 128], red: [255, 0, 0], silver: [192, 192, 192], white: [255, 255, 255], yellow: [255, 255, 0]} })(jQuery); // the actual Flot code (function ($) { function Plot(placeholder, data_, options_, plugins) { // data is on the form: // [ series1, series2 ... ] // where series is either just the data as [ [x1, y1], [x2, y2], ... ] // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... } var myRetinaMdo = (window.devicePixelRatio > 1), series = [], options = { // the color theme used for graphs colors: ["#931313", "#638167", "#65596B", "#60747C", "#B09B5B"], legend: { show: true, noColumns: 0, // number of colums in legend table labelFormatter: null, // fn: string -> string labelBoxBorderColor: "", // border color for the little label boxes container: null, // container (as jQuery object) to put legend in, null means default on top of graph position: "ne", // position of default legend container within plot margin: [-5, -32], // distance from grid edge to default legend container within plot backgroundColor: "", // null means auto-detect backgroundOpacity: 1 // set to 0 to avoid background }, xaxis: { show: null, // null = auto-detect, true = always, false = never position: "bottom", // or "top" mode: null, // null or "time" color: null, // base color, labels, ticks tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)" transform: null, // null or f: number -> number to transform axis inverseTransform: null, // if transform is set, this should be the inverse function min: null, // min. value to show, null means set automatically max: null, // max. value to show, null means set automatically autoscaleMargin: null, // margin in % to add if auto-setting min/max ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks tickFormatter: null, // fn: number -> string labelWidth: null, // size of tick labels in pixels labelHeight: null, reserveSpace: null, // whether to reserve space even if axis isn't shown tickLength: null, // size in pixels of ticks, or "full" for whole line alignTicksWithAxis: null, // axis number or null for no sync // mode specific options tickDecimals: null, // no. of decimals, null means auto tickSize: null, // number or [number, "unit"] minTickSize: null, // number or [number, "unit"] monthNames: null, // list of names of months timeformat: null, // format string to use twelveHourClock: false // 12 or 24 time in time mode }, yaxis: { autoscaleMargin: 0.02, position: "left" // or "right" }, xaxes: [], yaxes: [], series: { points: { show: false, radius: 3, lineWidth: 2, // in pixels fill: true, fillColor: "#ffffff", symbol: "circle" // or callback }, lines: { // we don't put in show: false so we can see // whether lines were actively disabled lineWidth: 2, // in pixels fill: false, fillColor: null, steps: false }, bars: { show: false, lineWidth: 1, // in pixels barWidth: 1, // in units of the x axis fill: true, fillColor: { colors: [ { opacity: 0.7 }, { opacity: 1 } ] }, align: "left", // or "center" horizontal: false }, shadowSize: 0 }, grid: { show: true, aboveData: false, color: "#545454", // primary color used for outline and labels backgroundColor: null, // null for transparent, else color borderColor: "#efefef", // set if different from the grid color tickColor: "rgba(0,0,0,0.06)", // color for the ticks, e.g. "rgba(0,0,0,0.15)" labelMargin: 10, // in pixels axisMargin: 8, // in pixels borderWidth: 0, // in pixels minBorderMargin: 10, // in pixels, null means taken from points radius markings: null, // array of ranges or fn: axes -> array of ranges markingsColor: "#f4f4f4", markingsLineWidth: 2, // interactive stuff clickable: false, hoverable: false, autoHighlight: true, // highlight in case mouse is near mouseActiveRadius: 5 // how far the mouse can be away to activate an item }, hooks: {} }, canvas = null, // the canvas for the plot itself overlay = null, // canvas for interactive stuff on top of plot eventHolder = null, // jQuery object that events should be bound to ctx = null, octx = null, xaxes = [], yaxes = [], plotOffset = { left: 0, right: 0, top: 0, bottom: 0}, canvasWidth = 0, canvasHeight = 0, plotWidth = 0, plotHeight = 0, hooks = { processOptions: [], processRawData: [], processDatapoints: [], drawSeries: [], draw: [], bindEvents: [], drawOverlay: [], shutdown: [] }, plot = this; // public functions plot.setData = setData; plot.setupGrid = setupGrid; plot.draw = draw; plot.getPlaceholder = function () { return placeholder; }; plot.getCanvas = function () { return canvas; }; plot.getPlotOffset = function () { return plotOffset; }; plot.width = function () { return plotWidth; }; plot.height = function () { return plotHeight; }; plot.offset = function () { var o = eventHolder.offset(); o.left += plotOffset.left; o.top += plotOffset.top; return o; }; plot.getData = function () { return series; }; plot.getAxes = function () { var res = {}, i; $.each(xaxes.concat(yaxes), function (_, axis) { if (axis) res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis; }); return res; }; plot.getXAxes = function () { return xaxes; }; plot.getYAxes = function () { return yaxes; }; plot.c2p = canvasToAxisCoords; plot.p2c = axisToCanvasCoords; plot.getOptions = function () { return options; }; plot.highlight = highlight; plot.unhighlight = unhighlight; plot.triggerRedrawOverlay = triggerRedrawOverlay; plot.pointOffset = function (point) { return { left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left), top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top) }; }; plot.shutdown = shutdown; plot.resize = function () { getCanvasDimensions(); resizeCanvas(canvas); resizeCanvas(overlay); }; // public attributes plot.hooks = hooks; // initialize initPlugins(plot); parseOptions(options_); setupCanvases(); setData(data_); setupGrid(); draw(); bindEvents(); function executeHooks(hook, args) { args = [plot].concat(args); for (var i = 0; i < hook.length; ++i) hook[i].apply(this, args); } function initPlugins() { for (var i = 0; i < plugins.length; ++i) { var p = plugins[i]; p.init(plot); if (p.options) $.extend(true, options, p.options); } } function parseOptions(opts) { var i; $.extend(true, options, opts); if (options.xaxis.color == null) options.xaxis.color = options.grid.color; if (options.yaxis.color == null) options.yaxis.color = options.grid.color; if (options.xaxis.tickColor == null) // backwards-compatibility options.xaxis.tickColor = options.grid.tickColor; if (options.yaxis.tickColor == null) // backwards-compatibility options.yaxis.tickColor = options.grid.tickColor; if (options.grid.borderColor == null) options.grid.borderColor = options.grid.color; if (options.grid.tickColor == null) options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString(); // fill in defaults in axes, copy at least always the // first as the rest of the code assumes it'll be there for (i = 0; i < Math.max(1, options.xaxes.length); ++i) options.xaxes[i] = $.extend(true, {}, options.xaxis, options.xaxes[i]); for (i = 0; i < Math.max(1, options.yaxes.length); ++i) options.yaxes[i] = $.extend(true, {}, options.yaxis, options.yaxes[i]); // backwards compatibility, to be removed in future if (options.xaxis.noTicks && options.xaxis.ticks == null) options.xaxis.ticks = options.xaxis.noTicks; if (options.yaxis.noTicks && options.yaxis.ticks == null) options.yaxis.ticks = options.yaxis.noTicks; if (options.x2axis) { options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis); options.xaxes[1].position = "top"; } if (options.y2axis) { options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis); options.yaxes[1].position = "right"; } if (options.grid.coloredAreas) options.grid.markings = options.grid.coloredAreas; if (options.grid.coloredAreasColor) options.grid.markingsColor = options.grid.coloredAreasColor; if (options.lines) $.extend(true, options.series.lines, options.lines); if (options.points) $.extend(true, options.series.points, options.points); if (options.bars) $.extend(true, options.series.bars, options.bars); if (options.shadowSize != null) options.series.shadowSize = options.shadowSize; // save options on axes for future reference for (i = 0; i < options.xaxes.length; ++i) getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i]; for (i = 0; i < options.yaxes.length; ++i) getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i]; // add hooks from options for (var n in hooks) if (options.hooks[n] && options.hooks[n].length) hooks[n] = hooks[n].concat(options.hooks[n]); executeHooks(hooks.processOptions, [options]); } function setData(d) { series = parseData(d); fillInSeriesOptions(); processData(); } function parseData(d) { var res = []; for (var i = 0; i < d.length; ++i) { var s = $.extend(true, {}, options.series); if (d[i].data != null) { s.data = d[i].data; // move the data instead of deep-copy delete d[i].data; $.extend(true, s, d[i]); d[i].data = s.data; } else s.data = d[i]; res.push(s); } return res; } function axisNumber(obj, coord) { var a = obj[coord + "axis"]; if (typeof a == "object") // if we got a real axis, extract number a = a.n; if (typeof a != "number") a = 1; // default to first axis return a; } function allAxes() { // return flat array without annoying null entries return $.grep(xaxes.concat(yaxes), function (a) { return a; }); } function canvasToAxisCoords(pos) { // return an object with x/y corresponding to all used axes var res = {}, i, axis; for (i = 0; i < xaxes.length; ++i) { axis = xaxes[i]; if (axis && axis.used) res["x" + axis.n] = axis.c2p(pos.left); } for (i = 0; i < yaxes.length; ++i) { axis = yaxes[i]; if (axis && axis.used) res["y" + axis.n] = axis.c2p(pos.top); } if (res.x1 !== undefined) res.x = res.x1; if (res.y1 !== undefined) res.y = res.y1; return res; } function axisToCanvasCoords(pos) { // get canvas coords from the first pair of x/y found in pos var res = {}, i, axis, key; for (i = 0; i < xaxes.length; ++i) { axis = xaxes[i]; if (axis && axis.used) { key = "x" + axis.n; if (pos[key] == null && axis.n == 1) key = "x"; if (pos[key] != null) { res.left = axis.p2c(pos[key]); break; } } } for (i = 0; i < yaxes.length; ++i) { axis = yaxes[i]; if (axis && axis.used) { key = "y" + axis.n; if (pos[key] == null && axis.n == 1) key = "y"; if (pos[key] != null) { res.top = axis.p2c(pos[key]); break; } } } return res; } function getOrCreateAxis(axes, number) { if (!axes[number - 1]) axes[number - 1] = { n: number, // save the number for future reference direction: axes == xaxes ? "x" : "y", options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis) }; return axes[number - 1]; } function fillInSeriesOptions() { var i; // collect what we already got of colors var neededColors = series.length, usedColors = [], assignedColors = []; for (i = 0; i < series.length; ++i) { var sc = series[i].color; if (sc != null) { --neededColors; if (typeof sc == "number") assignedColors.push(sc); else usedColors.push($.color.parse(series[i].color)); } } // we might need to generate more colors if higher indices // are assigned for (i = 0; i < assignedColors.length; ++i) { neededColors = Math.max(neededColors, assignedColors[i] + 1); } // produce colors as needed var colors = [], variation = 0; i = 0; while (colors.length < neededColors) { var c; if (options.colors.length == i) // check degenerate case c = $.color.make(100, 100, 100); else c = $.color.parse(options.colors[i]); // vary color if needed var sign = variation % 2 == 1 ? -1 : 1; c.scale('rgb', 1 + sign * Math.ceil(variation / 2) * 0.2) // FIXME: if we're getting to close to something else, // we should probably skip this one colors.push(c); ++i; if (i >= options.colors.length) { i = 0; ++variation; } } // fill in the options var colori = 0, s; for (i = 0; i < series.length; ++i) { s = series[i]; // assign colors if (s.color == null) { s.color = colors[colori].toString(); ++colori; } else if (typeof s.color == "number") s.color = colors[s.color].toString(); // turn on lines automatically in case nothing is set if (s.lines.show == null) { var v, show = true; for (v in s) if (s[v] && s[v].show) { show = false; break; } if (show) s.lines.show = true; } // setup axes s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x")); s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y")); } } function processData() { var topSentry = Number.POSITIVE_INFINITY, bottomSentry = Number.NEGATIVE_INFINITY, fakeInfinity = Number.MAX_VALUE, i, j, k, m, length, s, points, ps, x, y, axis, val, f, p; function updateAxis(axis, min, max) { if (min < axis.datamin && min != -fakeInfinity) axis.datamin = min; if (max > axis.datamax && max != fakeInfinity) axis.datamax = max; } $.each(allAxes(), function (_, axis) { // init axis axis.datamin = topSentry; axis.datamax = bottomSentry; axis.used = false; }); for (i = 0; i < series.length; ++i) { s = series[i]; s.datapoints = { points: [] }; executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]); } // first pass: clean and copy data for (i = 0; i < series.length; ++i) { s = series[i]; var data = s.data, format = s.datapoints.format; if (!format) { format = []; // find out how to copy format.push({ x: true, number: true, required: true }); format.push({ y: true, number: true, required: true }); if (s.bars.show || (s.lines.show && s.lines.fill)) { format.push({ y: true, number: true, required: false, defaultValue: 0 }); if (s.bars.horizontal) { delete format[format.length - 1].y; format[format.length - 1].x = true; } } s.datapoints.format = format; } if (s.datapoints.pointsize != null) continue; // already filled in s.datapoints.pointsize = format.length; ps = s.datapoints.pointsize; points = s.datapoints.points; insertSteps = s.lines.show && s.lines.steps; s.xaxis.used = s.yaxis.used = true; for (j = k = 0; j < data.length; ++j, k += ps) { p = data[j]; var nullify = p == null; if (!nullify) { for (m = 0; m < ps; ++m) { val = p[m]; f = format[m]; if (f) { if (f.number && val != null) { val = +val; // convert to number if (isNaN(val)) val = null; else if (val == Infinity) val = fakeInfinity; else if (val == -Infinity) val = -fakeInfinity; } if (val == null) { if (f.required) nullify = true; if (f.defaultValue != null) val = f.defaultValue; } } points[k + m] = val; } } if (nullify) { for (m = 0; m < ps; ++m) { val = points[k + m]; if (val != null) { f = format[m]; // extract min/max info if (f.x) updateAxis(s.xaxis, val, val); if (f.y) updateAxis(s.yaxis, val, val); } points[k + m] = null; } } else { // a little bit of line specific stuff that // perhaps shouldn't be here, but lacking // better means... if (insertSteps && k > 0 && points[k - ps] != null && points[k - ps] != points[k] && points[k - ps + 1] != points[k + 1]) { // copy the point to make room for a middle point for (m = 0; m < ps; ++m) points[k + ps + m] = points[k + m]; // middle point has same y points[k + 1] = points[k - ps + 1]; // we've added a point, better reflect that k += ps; } } } } // give the hooks a chance to run for (i = 0; i < series.length; ++i) { s = series[i]; executeHooks(hooks.processDatapoints, [ s, s.datapoints]); } // second pass: find datamax/datamin for auto-scaling for (i = 0; i < series.length; ++i) { s = series[i]; points = s.datapoints.points, ps = s.datapoints.pointsize; var xmin = topSentry, ymin = topSentry, xmax = bottomSentry, ymax = bottomSentry; for (j = 0; j < points.length; j += ps) { if (points[j] == null) continue; for (m = 0; m < ps; ++m) { val = points[j + m]; f = format[m]; if (!f || val == fakeInfinity || val == -fakeInfinity) continue; if (f.x) { if (val < xmin) xmin = val; if (val > xmax) xmax = val; } if (f.y) { if (val < ymin) ymin = val; if (val > ymax) ymax = val; } } } if (s.bars.show) { // make sure we got room for the bar on the dancing floor var delta = s.bars.align == "left" ? 0 : -s.bars.barWidth / 2; if (s.bars.horizontal) { ymin += delta; ymax += delta + s.bars.barWidth; } else { xmin += delta; xmax += delta + s.bars.barWidth; } } updateAxis(s.xaxis, xmin, xmax); updateAxis(s.yaxis, ymin, ymax); } $.each(allAxes(), function (_, axis) { if (axis.datamin == topSentry) axis.datamin = null; if (axis.datamax == bottomSentry) axis.datamax = null; }); } function makeCanvas(skipPositioning, cls) { var c = document.createElement('canvas'); c.className = cls; c.width = canvasWidth; c.height = canvasHeight; if (!skipPositioning) $(c).css({ position: 'absolute', left: 0, top: 0 }); $(c).appendTo(placeholder); if (myRetinaMdo) { c.width = canvasWidth * 2; c.height = canvasHeight * 2; c.style.width = '' + canvasWidth + 'px'; c.style.height = '' + canvasHeight + 'px'; } if (!c.getContext) // excanvas hack c = window.G_vmlCanvasManager.initElement(c); // used for resetting in case we get replotted c.getContext("2d").save(); if (myRetinaMdo) { c.getContext("2d").scale(2, 2); } return c; } function getCanvasDimensions() { canvasWidth = placeholder.width(); canvasHeight = placeholder.height(); if (canvasWidth <= 0 || canvasHeight <= 0) throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight; } function resizeCanvas(c) { // resizing should reset the state (excanvas seems to be // buggy though) if (c.width != canvasWidth) { c.width = canvasWidth; if (myRetinaMdo) { c.width = canvasWidth * 2; } c.style.width = '' + canvasWidth + 'px'; } if (c.height != canvasHeight) { c.height = canvasHeight; if (myRetinaMdo) { c.height = canvasHeight * 2; } c.style.height = '' + canvasHeight + 'px'; } // so try to get back to the initial state (even if it's // gone now, this should be safe according to the spec) var cctx = c.getContext("2d"); cctx.restore(); // and save again cctx.save(); if (myRetinaMdo) { cctx.scale(2, 2); } } function setupCanvases() { var reused, existingCanvas = placeholder.children("canvas.base"), existingOverlay = placeholder.children("canvas.overlay"); if (existingCanvas.length == 0 || existingOverlay == 0) { // init everything placeholder.html(""); // make sure placeholder is clear placeholder.css({ padding: 0 }); // padding messes up the positioning if (placeholder.css("position") == 'static') placeholder.css("position", "relative"); // for positioning labels and overlay getCanvasDimensions(); canvas = makeCanvas(true, "base"); overlay = makeCanvas(false, "overlay"); // overlay canvas for interactive features reused = false; } else { // reuse existing elements canvas = existingCanvas.get(0); overlay = existingOverlay.get(0); reused = true; } ctx = canvas.getContext("2d"); octx = overlay.getContext("2d"); // we include the canvas in the event holder too, because IE 7 // sometimes has trouble with the stacking order eventHolder = $([overlay, canvas]); if (reused) { // run shutdown in the old plot object placeholder.data("plot").shutdown(); // reset reused canvases plot.resize(); // make sure overlay pixels are cleared (canvas is cleared when we redraw) octx.clearRect(0, 0, canvasWidth, canvasHeight); // then whack any remaining obvious garbage left eventHolder.unbind(); placeholder.children().not([canvas, overlay]).remove(); } // save in case we get replotted placeholder.data("plot", plot); } function bindEvents() { // bind events if (options.grid.hoverable) { eventHolder.mousemove(onMouseMove); eventHolder.mouseleave(onMouseLeave); } if (options.grid.clickable) eventHolder.click(onClick); executeHooks(hooks.bindEvents, [eventHolder]); } function shutdown() { if (redrawTimeout) clearTimeout(redrawTimeout); eventHolder.unbind("mousemove", onMouseMove); eventHolder.unbind("mouseleave", onMouseLeave); eventHolder.unbind("click", onClick); executeHooks(hooks.shutdown, [eventHolder]); } function setTransformationHelpers(axis) { // set helper functions on the axis, assumes plot area // has been computed already function identity(x) { return x; } var s, m, t = axis.options.transform || identity, it = axis.options.inverseTransform; // precompute how much the axis is scaling a point // in canvas space if (axis.direction == "x") { s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min)); m = Math.min(t(axis.max), t(axis.min)); } else { s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min)); s = -s; m = Math.max(t(axis.max), t(axis.min)); } // data point to canvas coordinate if (t == identity) // slight optimization axis.p2c = function (p) { return (p - m) * s; }; else axis.p2c = function (p) { return (t(p) - m) * s; }; // canvas coordinate to data point if (!it) axis.c2p = function (c) { return m + c / s; }; else axis.c2p = function (c) { return it(m + c / s); }; } function measureTickLabels(axis) { var opts = axis.options, i, ticks = axis.ticks || [], labels = [], l, w = opts.labelWidth, h = opts.labelHeight, dummyDiv; function makeDummyDiv(labels, width) { return $('<div style="position:absolute;top:-10000px;' + width + 'font-size:smaller">' + '<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis">' + labels.join("") + '</div></div>') .appendTo(placeholder); } if (axis.direction == "x") { // to avoid measuring the widths of the labels (it's slow), we // construct fixed-size boxes and put the labels inside // them, we don't need the exact figures and the // fixed-size box content is easy to center if (w == null) w = Math.floor(canvasWidth / (ticks.length > 0 ? ticks.length : 1)); // measure x label heights if (h == null) { labels = []; for (i = 0; i < ticks.length; ++i) { l = ticks[i].label; if (l) labels.push('<div class="tickLabel" style="float:left;width:' + w + 'px">' + l + '</div>'); } if (labels.length > 0) { // stick them all in the same div and measure // collective height labels.push('<div style="clear:left"></div>'); dummyDiv = makeDummyDiv(labels, "width:10000px;"); h = dummyDiv.height(); dummyDiv.remove(); } } } else if (w == null || h == null) { // calculate y label dimensions for (i = 0; i < ticks.length; ++i) { l = ticks[i].label; if (l) labels.push('<div class="tickLabel">' + l + '</div>'); } if (labels.length > 0) { dummyDiv = makeDummyDiv(labels, ""); if (w == null) w = dummyDiv.children().width(); if (h == null) h = dummyDiv.find("div.tickLabel").height(); dummyDiv.remove(); } } if (w == null) w = 0; if (h == null) h = 0; axis.labelWidth = w; axis.labelHeight = h; } function allocateAxisBoxFirstPhase(axis) { // find the bounding box of the axis by looking at label // widths/heights and ticks, make room by diminishing the // plotOffset var lw = axis.labelWidth, lh = axis.labelHeight, pos = axis.options.position, tickLength = axis.options.tickLength, axismargin = options.grid.axisMargin, padding = options.grid.labelMargin, all = axis.direction == "x" ? xaxes : yaxes, index; // determine axis margin var samePosition = $.grep(all, function (a) { return a && a.options.position == pos && a.reserveSpace; }); if ($.inArray(axis, samePosition) == samePosition.length - 1) axismargin = 0; // outermost // determine tick length - if we're innermost, we can use "full" if (tickLength == null) tickLength = "full"; var sameDirection = $.grep(all, function (a) { return a && a.reserveSpace; }); var innermost = $.inArray(axis, sameDirection) == 0; if (!innermost && tickLength == "full") tickLength = 5; if (!isNaN(+tickLength)) padding += +tickLength; // compute box if (axis.direction == "x") { lh += padding; if (pos == "bottom") { plotOffset.bottom += lh + axismargin; axis.box = { top: canvasHeight - plotOffset.bottom, height: lh }; } else { axis.box = { top: plotOffset.top + axismargin, height: lh }; plotOffset.top += lh + axismargin; } } else { lw += padding; if (pos == "left") { axis.box = { left: plotOffset.left + axismargin, width: lw }; plotOffset.left += lw + axismargin; } else { plotOffset.right += lw + axismargin; axis.box = { left: canvasWidth - plotOffset.right, width: lw }; } } // save for future reference axis.position = pos; axis.tickLength = tickLength; axis.box.padding = padding; axis.innermost = innermost; } function allocateAxisBoxSecondPhase(axis) { // set remaining bounding box coordinates if (axis.direction == "x") { axis.box.left = plotOffset.left; axis.box.width = plotWidth; } else { axis.box.top = plotOffset.top; axis.box.height = plotHeight; } } function setupGrid() { var i, axes = allAxes(); // first calculate the plot and axis box dimensions $.each(axes, function (_, axis) { axis.show = axis.options.show; if (axis.show == null) axis.show = axis.used; // by default an axis is visible if it's got data axis.reserveSpace = axis.show || axis.options.reserveSpace; setRange(axis); }); allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; }); plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = 0; if (options.grid.show) { $.each(allocatedAxes, function (_, axis) { // make the ticks setupTickGeneration(axis); setTicks(axis); snapRangeToTicks(axis, axis.ticks); // find labelWidth/Height for axis measureTickLabels(axis); }); // with all dimensions in house, we can compute the // axis boxes, start from the outside (reverse order) for (i = allocatedAxes.length - 1; i >= 0; --i) allocateAxisBoxFirstPhase(allocatedAxes[i]); // make sure we've got enough space for things that // might stick out var minMargin = options.grid.minBorderMargin; if (minMargin == null) { minMargin = 0; for (i = 0; i < series.length; ++i) minMargin = Math.max(minMargin, series[i].points.radius + series[i].points.lineWidth / 2); } for (var a in plotOffset) { plotOffset[a] += options.grid.borderWidth; plotOffset[a] = Math.max(minMargin, plotOffset[a]); } } plotWidth = canvasWidth - plotOffset.left - plotOffset.right; plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top; // now we got the proper plotWidth/Height, we can compute the scaling $.each(axes, function (_, axis) { setTransformationHelpers(axis); }); if (options.grid.show) { $.each(allocatedAxes, function (_, axis) { allocateAxisBoxSecondPhase(axis); }); insertAxisLabels(); } insertLegend(); } function setRange(axis) { var opts = axis.options, min = +(opts.min != null ? opts.min : axis.datamin), max = +(opts.max != null ? opts.max : axis.datamax), delta = max - min; if (delta == 0.0) { // degenerate case var widen = max == 0 ? 1 : 0.01; if (opts.min == null) min -= widen; // always widen max if we couldn't widen min to ensure we // don't fall into min == max which doesn't work if (opts.max == null || opts.min != null) max += widen; } else { // consider autoscaling var margin = opts.autoscaleMargin; if (margin != null) { if (opts.min == null) { min -= delta * margin; // make sure we don't go below zero if all values // are positive if (min < 0 && axis.datamin != null && axis.datamin >= 0) min = 0; } if (opts.max == null) { max += delta * margin; if (max > 0 && axis.datamax != null && axis.datamax <= 0) max = 0; } } } axis.min = min; axis.max = max; } function setupTickGeneration(axis) { var opts = axis.options; // estimate number of ticks var noTicks; if (typeof opts.ticks == "number" && opts.ticks > 0) noTicks = opts.ticks; else // heuristic based on the model a*sqrt(x) fitted to // some data points that seemed reasonable noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? canvasWidth : canvasHeight); var delta = (axis.max - axis.min) / noTicks, size, generator, unit, formatter, i, magn, norm; if (opts.mode == "time") { // pretty handling of time // map of app. size of time units in milliseconds var timeUnitSize = { "second": 1000, "minute": 60 * 1000, "hour": 60 * 60 * 1000, "day": 24 * 60 * 60 * 1000, "month": 30 * 24 * 60 * 60 * 1000, "year": 365.2425 * 24 * 60 * 60 * 1000 }; // the allowed tick sizes, after 1 year we use // an integer algorithm var spec = [ [1, "second"], [2, "second"], [5, "second"], [10, "second"], [30, "second"], [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], [30, "minute"], [1, "hour"], [2, "hour"], [4, "hour"], [8, "hour"], [12, "hour"], [1, "day"], [2, "day"], [3, "day"], [0.25, "month"], [0.5, "month"], [1, "month"], [2, "month"], [3, "month"], [6, "month"], [1, "year"] ]; var minSize = 0; if (opts.minTickSize != null) { if (typeof opts.tickSize == "number") minSize = opts.tickSize; else minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]]; } for (var i = 0; i < spec.length - 1; ++i) if (delta < (spec[i][0] * timeUnitSize[spec[i][1]] + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2 && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) break; size = spec[i][0]; unit = spec[i][1]; // special-case the possibility of several years if (unit == "year") { magn = Math.pow(10, Math.floor(Math.log(delta / timeUnitSize.year) / Math.LN10)); norm = (delta / timeUnitSize.year) / magn; if (norm < 1.5) size = 1; else if (norm < 3) size = 2; else if (norm < 7.5) size = 5; else size = 10; size *= magn; } axis.tickSize = opts.tickSize || [size, unit]; generator = function (axis) { var ticks = [], tickSize = axis.tickSize[0], unit = axis.tickSize[1], d = new Date(axis.min); var step = tickSize * timeUnitSize[unit]; if (unit == "second") d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize)); if (unit == "minute") d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize)); if (unit == "hour") d.setUTCHours(floorInBase(d.getUTCHours(), tickSize)); if (unit == "month") d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize)); if (unit == "year") d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize)); // reset smaller components d.setUTCMilliseconds(0); if (step >= timeUnitSize.minute) d.setUTCSeconds(0); if (step >= timeUnitSize.hour) d.setUTCMinutes(0); if (step >= timeUnitSize.day) d.setUTCHours(0); if (step >= timeUnitSize.day * 4) d.setUTCDate(1); if (step >= timeUnitSize.year) d.setUTCMonth(0); var carry = 0, v = Number.NaN, prev; do { prev = v; v = d.getTime(); ticks.push(v); if (unit == "month") { if (tickSize < 1) { // a bit complicated - we'll divide the month // up but we need to take care of fractions // so we don't end up in the middle of a day d.setUTCDate(1); var start = d.getTime(); d.setUTCMonth(d.getUTCMonth() + 1); var end = d.getTime(); d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize); carry = d.getUTCHours(); d.setUTCHours(0); } else d.setUTCMonth(d.getUTCMonth() + tickSize); } else if (unit == "year") { d.setUTCFullYear(d.getUTCFullYear() + tickSize); } else d.setTime(v + step); } while (v < axis.max && v != prev); return ticks; }; formatter = function (v, axis) { var d = new Date(v); // first check global format if (opts.timeformat != null) return $.plot.formatDate(d, opts.timeformat, opts.monthNames); var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]]; var span = axis.max - axis.min; var suffix = (opts.twelveHourClock) ? " %p" : ""; if (t < timeUnitSize.minute) fmt = "%h:%M:%S" + suffix; else if (t < timeUnitSize.day) { if (span < 2 * timeUnitSize.day) fmt = "%h:%M" + suffix; else fmt = "%b %d %h:%M" + suffix; } else if (t < timeUnitSize.month) fmt = "%b %d"; else if (t < timeUnitSize.year) { if (span < timeUnitSize.year) fmt = "%b"; else fmt = "%b %y"; } else fmt = "%y"; return $.plot.formatDate(d, fmt, opts.monthNames); }; } else { // pretty rounding of base-10 numbers var maxDec = opts.tickDecimals; var dec = -Math.floor(Math.log(delta) / Math.LN10); if (maxDec != null && dec > maxDec) dec = maxDec; magn = Math.pow(10, -dec); norm = delta / magn; // norm is between 1.0 and 10.0 if (norm < 1.5) size = 1; else if (norm < 3) { size = 2; // special case for 2.5, requires an extra decimal if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) { size = 2.5; ++dec; } } else if (norm < 7.5) size = 5; else size = 10; size *= magn; if (opts.minTickSize != null && size < opts.minTickSize) size = opts.minTickSize; axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec); axis.tickSize = opts.tickSize || size; generator = function (axis) { var ticks = []; // spew out all possible ticks var start = floorInBase(axis.min, axis.tickSize), i = 0, v = Number.NaN, prev; do { prev = v; v = start + i * axis.tickSize; ticks.push(v); ++i; } while (v < axis.max && v != prev); return ticks; }; formatter = function (v, axis) { return v.toFixed(axis.tickDecimals); }; } if (opts.alignTicksWithAxis != null) { var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1]; if (otherAxis && otherAxis.used && otherAxis != axis) { // consider snapping min/max to outermost nice ticks var niceTicks = generator(axis); if (niceTicks.length > 0) { if (opts.min == null) axis.min = Math.min(axis.min, niceTicks[0]); if (opts.max == null && niceTicks.length > 1) axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]); } generator = function (axis) { // copy ticks, scaled to this axis var ticks = [], v, i; for (i = 0; i < otherAxis.ticks.length; ++i) { v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min); v = axis.min + v * (axis.max - axis.min); ticks.push(v); } return ticks; }; // we might need an extra decimal since forced // ticks don't necessarily fit naturally if (axis.mode != "time" && opts.tickDecimals == null) { var extraDec = Math.max(0, -Math.floor(Math.log(delta) / Math.LN10) + 1), ts = generator(axis); // only proceed if the tick interval rounded // with an extra decimal doesn't give us a // zero at end if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec)))) axis.tickDecimals = extraDec; } } } axis.tickGenerator = generator; if ($.isFunction(opts.tickFormatter)) axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); }; else axis.tickFormatter = formatter; } function setTicks(axis) { var oticks = axis.options.ticks, ticks = []; if (oticks == null || (typeof oticks == "number" && oticks > 0)) ticks = axis.tickGenerator(axis); else if (oticks) { if ($.isFunction(oticks)) // generate the ticks ticks = oticks({ min: axis.min, max: axis.max }); else ticks = oticks; } // clean up/labelify the supplied ticks, copy them over var i, v; axis.ticks = []; for (i = 0; i < ticks.length; ++i) { var label = null; var t = ticks[i]; if (typeof t == "object") { v = +t[0]; if (t.length > 1) label = t[1]; } else v = +t; if (label == null) label = axis.tickFormatter(v, axis); if (!isNaN(v)) axis.ticks.push({ v: v, label: label }); } } function snapRangeToTicks(axis, ticks) { if (axis.options.autoscaleMargin && ticks.length > 0) { // snap to ticks if (axis.options.min == null) axis.min = Math.min(axis.min, ticks[0].v); if (axis.options.max == null && ticks.length > 1) axis.max = Math.max(axis.max, ticks[ticks.length - 1].v); } } function draw() { ctx.clearRect(0, 0, canvasWidth, canvasHeight); var grid = options.grid; // draw background, if any if (grid.show && grid.backgroundColor) drawBackground(); if (grid.show && !grid.aboveData) drawGrid(); for (var i = 0; i < series.length; ++i) { executeHooks(hooks.drawSeries, [ctx, series[i]]); drawSeries(series[i]); } executeHooks(hooks.draw, [ctx]); if (grid.show && grid.aboveData) drawGrid(); } function extractRange(ranges, coord) { var axis, from, to, key, axes = allAxes(); for (i = 0; i < axes.length; ++i) { axis = axes[i]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis if (ranges[key]) { from = ranges[key].from; to = ranges[key].to; break; } } } // backwards-compat stuff - to be removed in future if (!ranges[key]) { axis = coord == "x" ? xaxes[0] : yaxes[0]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) { var tmp = from; from = to; to = tmp; } return { from: from, to: to, axis: axis }; } function drawBackground() { ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)"); ctx.fillRect(0, 0, plotWidth, plotHeight); ctx.restore(); } function drawGrid() { var i; ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); // draw markings var markings = options.grid.markings; if (markings) { if ($.isFunction(markings)) { var axes = plot.getAxes(); // xmin etc. is backwards compatibility, to be // removed in the future axes.xmin = axes.xaxis.min; axes.xmax = axes.xaxis.max; axes.ymin = axes.yaxis.min; axes.ymax = axes.yaxis.max; markings = markings(axes); } for (i = 0; i < markings.length; ++i) { var m = markings[i], xrange = extractRange(m, "x"), yrange = extractRange(m, "y"); // fill in missing if (xrange.from == null) xrange.from = xrange.axis.min; if (xrange.to == null) xrange.to = xrange.axis.max; if (yrange.from == null) yrange.from = yrange.axis.min; if (yrange.to == null) yrange.to = yrange.axis.max; // clip if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max || yrange.to < yrange.axis.min || yrange.from > yrange.axis.max) continue; xrange.from = Math.max(xrange.from, xrange.axis.min); xrange.to = Math.min(xrange.to, xrange.axis.max); yrange.from = Math.max(yrange.from, yrange.axis.min); yrange.to = Math.min(yrange.to, yrange.axis.max); if (xrange.from == xrange.to && yrange.from == yrange.to) continue; // then draw xrange.from = xrange.axis.p2c(xrange.from); xrange.to = xrange.axis.p2c(xrange.to); yrange.from = yrange.axis.p2c(yrange.from); yrange.to = yrange.axis.p2c(yrange.to); if (xrange.from == xrange.to || yrange.from == yrange.to) { // draw line ctx.beginPath(); ctx.strokeStyle = m.color || options.grid.markingsColor; ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth; ctx.moveTo(xrange.from, yrange.from); ctx.lineTo(xrange.to, yrange.to); ctx.stroke(); } else { // fill area ctx.fillStyle = m.color || options.grid.markingsColor; ctx.fillRect(xrange.from, yrange.to, xrange.to - xrange.from, yrange.from - yrange.to); } } } // draw the ticks var axes = allAxes(), bw = options.grid.borderWidth; for (var j = 0; j < axes.length; ++j) { var axis = axes[j], box = axis.box, t = axis.tickLength, x, y, xoff, yoff; if (!axis.show || axis.ticks.length == 0) continue ctx.strokeStyle = axis.options.tickColor || $.color.parse(axis.options.color).scale('a', 0.22).toString(); ctx.lineWidth = 1; // find the edges if (axis.direction == "x") { x = 0; if (t == "full") y = (axis.position == "top" ? 0 : plotHeight); else y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0); } else { y = 0; if (t == "full") x = (axis.position == "left" ? 0 : plotWidth); else x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0); } // draw tick bar if (!axis.innermost) { ctx.beginPath(); xoff = yoff = 0; if (axis.direction == "x") xoff = plotWidth; else yoff = plotHeight; if (ctx.lineWidth == 1) { x = Math.floor(x) + 0.5; y = Math.floor(y) + 0.5; } ctx.moveTo(x, y); ctx.lineTo(x + xoff, y + yoff); ctx.stroke(); } // draw ticks ctx.beginPath(); for (i = 0; i < axis.ticks.length; ++i) { var v = axis.ticks[i].v; xoff = yoff = 0; if (v < axis.min || v > axis.max // skip those lying on the axes if we got a border || (t == "full" && bw > 0 && (v == axis.min || v == axis.max))) continue; if (axis.direction == "x") { x = axis.p2c(v); yoff = t == "full" ? -plotHeight : t; if (axis.position == "top") yoff = -yoff; } else { y = axis.p2c(v); xoff = t == "full" ? -plotWidth : t; if (axis.position == "left") xoff = -xoff; } if (ctx.lineWidth == 1) { if (axis.direction == "x") x = Math.floor(x) + 0.5; else y = Math.floor(y) + 0.5; } ctx.moveTo(x, y); ctx.lineTo(x + xoff, y + yoff); } ctx.stroke(); } // draw border if (bw) { ctx.lineWidth = bw; ctx.strokeStyle = options.grid.borderColor; ctx.strokeRect(-bw / 2, -bw / 2, plotWidth + bw, plotHeight + bw); } ctx.restore(); } function insertAxisLabels() { placeholder.find(".tickLabels").remove(); var html = ['<div class="tickLabels" style="font-size:smaller">']; var axes = allAxes(); for (var j = 0; j < axes.length; ++j) { var axis = axes[j], box = axis.box; if (!axis.show) continue; //debug: html.push('<div style="position:absolute;opacity:0.10;background-color:red;left:' + box.left + 'px;top:' + box.top + 'px;width:' + box.width + 'px;height:' + box.height + 'px"></div>') html.push('<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis" style="color:' + axis.options.color + '">'); for (var i = 0; i < axis.ticks.length; ++i) { var tick = axis.ticks[i]; if (!tick.label || tick.v < axis.min || tick.v > axis.max) continue; var pos = {}, align; if (axis.direction == "x") { align = "center"; pos.left = Math.round(plotOffset.left + axis.p2c(tick.v) - axis.labelWidth / 2); if (axis.position == "bottom") pos.top = box.top + box.padding; else pos.bottom = canvasHeight - (box.top + box.height - box.padding); } else { pos.top = Math.round(plotOffset.top + axis.p2c(tick.v) - axis.labelHeight / 2); if (axis.position == "left") { pos.right = canvasWidth - (box.left + box.width - box.padding) align = "right"; } else { pos.left = box.left + box.padding; align = "left"; } } pos.width = axis.labelWidth; var style = ["position:absolute", "text-align:" + align ]; for (var a in pos) style.push(a + ":" + pos[a] + "px") html.push('<div class="tickLabel" style="' + style.join(';') + '">' + tick.label + '</div>'); } html.push('</div>'); } html.push('</div>'); placeholder.append(html.join("")); } function drawSeries(series) { if (series.lines.show) drawSeriesLines(series); if (series.bars.show) drawSeriesBars(series); if (series.points.show) drawSeriesPoints(series); } function drawSeriesLines(series) { function plotLine(datapoints, xoffset, yoffset, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, prevx = null, prevy = null; ctx.beginPath(); for (var i = ps; i < points.length; i += ps) { var x1 = points[i - ps], y1 = points[i - ps + 1], x2 = points[i], y2 = points[i + 1]; if (x1 == null || x2 == null) continue; // clip with ymin if (y1 <= y2 && y1 < axisy.min) { if (y2 < axisy.min) continue; // line segment is outside // compute new intersection point x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min) { if (y1 < axisy.min) continue; x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max) { if (y2 > axisy.max) continue; x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max) { if (y1 > axisy.max) continue; x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (x1 != prevx || y1 != prevy) ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset); prevx = x2; prevy = y2; ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset); } ctx.stroke(); } function plotLineArea(datapoints, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, bottom = Math.min(Math.max(0, axisy.min), axisy.max), i = 0, top, areaOpen = false, ypos = 1, segmentStart = 0, segmentEnd = 0; // we process each segment in two turns, first forward // direction to sketch out top, then once we hit the // end we go backwards to sketch the bottom while (true) { if (ps > 0 && i > points.length + ps) break; i += ps; // ps is negative if going backwards var x1 = points[i - ps], y1 = points[i - ps + ypos], x2 = points[i], y2 = points[i + ypos]; if (areaOpen) { if (ps > 0 && x1 != null && x2 == null) { // at turning point segmentEnd = i; ps = -ps; ypos = 2; continue; } if (ps < 0 && i == segmentStart + ps) { // done with the reverse sweep ctx.fill(); areaOpen = false; ps = -ps; ypos = 1; i = segmentStart = segmentEnd + ps; continue; } } if (x1 == null || x2 == null) continue; // clip x values // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (!areaOpen) { // open area ctx.beginPath(); ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom)); areaOpen = true; } // now first check the case where both is outside if (y1 >= axisy.max && y2 >= axisy.max) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max)); continue; } else if (y1 <= axisy.min && y2 <= axisy.min) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min)); continue; } // else it's a bit more complicated, there might // be a flat maxed out rectangle first, then a // triangular cutout or reverse; to find these // keep track of the current x values var x1old = x1, x2old = x2; // clip the y values, without shortcutting, we // go through all cases in turn // clip with ymin if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) { x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) { x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) { x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) { x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // if the x value was changed we got a rectangle // to fill if (x1 != x1old) { ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1)); // it goes to (x1, y1), but we fill that below } // fill triangular section, this sometimes result // in redundant points if (x1, y1) hasn't changed // from previous line to, but we just ignore that ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); // fill the other rectangle if it's there if (x2 != x2old) { ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2)); } } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.lineJoin = "round"; var lw = series.lines.lineWidth, sw = series.shadowSize; // FIXME: consider another form of shadow when filling is turned on if (lw > 0 && sw > 0) { // draw shadow as a thick and thin line with transparency ctx.lineWidth = sw; ctx.strokeStyle = "rgba(0,0,0,0.1)"; // position shadow at angle from the mid of line var angle = Math.PI / 18; plotLine(series.datapoints, Math.sin(angle) * (lw / 2 + sw / 2), Math.cos(angle) * (lw / 2 + sw / 2), series.xaxis, series.yaxis); ctx.lineWidth = sw / 2; plotLine(series.datapoints, Math.sin(angle) * (lw / 2 + sw / 4), Math.cos(angle) * (lw / 2 + sw / 4), series.xaxis, series.yaxis); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight); if (fillStyle) { ctx.fillStyle = fillStyle; plotLineArea(series.datapoints, series.xaxis, series.yaxis); } if (lw > 0) plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis); ctx.restore(); } function drawSeriesPoints(series) { function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { var x = points[i], y = points[i + 1]; if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) continue; ctx.beginPath(); x = axisx.p2c(x); y = axisy.p2c(y) + offset; if (symbol == "circle") ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false); else symbol(ctx, x, y, radius, shadow); ctx.closePath(); if (fillStyle) { ctx.fillStyle = fillStyle; ctx.fill(); } ctx.stroke(); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); var lw = series.points.lineWidth, sw = series.shadowSize, radius = series.points.radius, symbol = series.points.symbol; if (lw > 0 && sw > 0) { // draw shadow in two steps var w = sw / 2; ctx.lineWidth = w; ctx.strokeStyle = "rgba(0,0,0,0.1)"; plotPoints(series.datapoints, radius, null, w + w / 2, true, series.xaxis, series.yaxis, symbol); ctx.strokeStyle = "rgba(0,0,0,0.2)"; plotPoints(series.datapoints, radius, null, w / 2, true, series.xaxis, series.yaxis, symbol); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; plotPoints(series.datapoints, radius, getFillStyle(series.points, series.color), 0, false, series.xaxis, series.yaxis, symbol); ctx.restore(); } function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) { var left, right, bottom, top, drawLeft, drawRight, drawTop, drawBottom, tmp; // in horizontal mode, we start the bar from the left // instead of from the bottom so it appears to be // horizontal rather than vertical if (horizontal) { drawBottom = drawRight = drawTop = true; drawLeft = false; left = b; right = x; top = y + barLeft; bottom = y + barRight; // account for negative bars if (right < left) { tmp = right; right = left; left = tmp; drawLeft = true; drawRight = false; } } else { drawLeft = drawRight = drawTop = true; drawBottom = false; left = x + barLeft; right = x + barRight; bottom = b; top = y; // account for negative bars if (top < bottom) { tmp = top; top = bottom; bottom = tmp; drawBottom = true; drawTop = false; } } // clip if (right < axisx.min || left > axisx.max || top < axisy.min || bottom > axisy.max) return; if (left < axisx.min) { left = axisx.min; drawLeft = false; } if (right > axisx.max) { right = axisx.max; drawRight = false; } if (bottom < axisy.min) { bottom = axisy.min; drawBottom = false; } if (top > axisy.max) { top = axisy.max; drawTop = false; } left = axisx.p2c(left); bottom = axisy.p2c(bottom); right = axisx.p2c(right); top = axisy.p2c(top); // fill the bar if (fillStyleCallback) { c.beginPath(); c.moveTo(left, bottom); c.lineTo(left, top); c.lineTo(right, top); c.lineTo(right, bottom); c.fillStyle = fillStyleCallback(bottom, top); c.fill(); } // draw outline if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) { c.beginPath(); // FIXME: inline moveTo is buggy with excanvas c.moveTo(left, bottom + offset); if (drawLeft) c.lineTo(left, top + offset); else c.moveTo(left, top + offset); if (drawTop) c.lineTo(right, top + offset); else c.moveTo(right, top + offset); if (drawRight) c.lineTo(right, bottom + offset); else c.moveTo(right, bottom + offset); if (drawBottom) c.lineTo(left, bottom + offset); else c.moveTo(left, bottom + offset); c.stroke(); } } function drawSeriesBars(series) { function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { if (points[i] == null) continue; drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); // FIXME: figure out a way to add shadows (for instance along the right edge) ctx.lineWidth = series.bars.lineWidth; ctx.strokeStyle = series.color; var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth / 2; var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null; plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis); ctx.restore(); } function getFillStyle(filloptions, seriesColor, bottom, top) { var fill = filloptions.fill; if (!fill) return null; if (filloptions.fillColor) return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor); var c = $.color.parse(seriesColor); c.a = typeof fill == "number" ? fill : 0.4; c.normalize(); return c.toString(); } function insertLegend() { placeholder.find(".legend").remove(); if (!options.legend.show) return; var fragments = [], rowStarted = false, lf = options.legend.labelFormatter, s, label; for (var i = 0; i < series.length; ++i) { s = series[i]; label = s.label; if (!label) continue; if (i % options.legend.noColumns == 0) { if (rowStarted) fragments.push('</tr>'); fragments.push('<tr>'); rowStarted = true; } if (lf) label = lf(label, s); fragments.push( '<td class="legendColorBox"><div style="' + options.legend.labelBoxBorderColor + '"><div style="border:2px solid ' + s.color + ';overflow:hidden"></div></div></td>' + '<td class="legendLabel"><span>' + label + '</span></td>'); } if (rowStarted) fragments.push('</tr>'); if (fragments.length == 0) return; var table = '<table style="font-size: 11px; color:' + options.grid.color + '">' + fragments.join("") + '</table>'; if (options.legend.container != null) $(options.legend.container).html(table); else { var pos = "", p = options.legend.position, m = options.legend.margin; if (m[0] == null) m = [m, m]; if (p.charAt(0) == "n") pos += 'top:' + (m[1] + plotOffset.top) + 'px;'; else if (p.charAt(0) == "s") pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;'; if (p.charAt(1) == "e") pos += 'right:' + (m[0] + plotOffset.right) + 'px;'; else if (p.charAt(1) == "w") pos += 'left:' + (m[0] + plotOffset.left) + 'px;'; var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos + ';') + '</div>').appendTo(placeholder); if (options.legend.backgroundOpacity != 0.0) { // put in the transparent background // separately to avoid blended labels and // label boxes var c = options.legend.backgroundColor; if (c == null) { c = options.grid.backgroundColor; if (c && typeof c == "string") c = $.color.parse(c); else c = $.color.extract(legend, 'background-color'); c.a = 1; c = c.toString(); } var div = legend.children(); $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos + 'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity); } } } // interactive features var highlights = [], redrawTimeout = null; // returns the data item the mouse is over, or null if none is found function findNearbyItem(mouseX, mouseY, seriesFilter) { var maxDistance = options.grid.mouseActiveRadius, smallestDistance = maxDistance * maxDistance + 1, item = null, foundPoint = false, i, j; for (i = series.length - 1; i >= 0; --i) { if (!seriesFilter(series[i])) continue; var s = series[i], axisx = s.xaxis, axisy = s.yaxis, points = s.datapoints.points, ps = s.datapoints.pointsize, mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster my = axisy.c2p(mouseY), maxx = maxDistance / axisx.scale, maxy = maxDistance / axisy.scale; // with inverse transforms, we can't use the maxx/maxy // optimization, sadly if (axisx.options.inverseTransform) maxx = Number.MAX_VALUE; if (axisy.options.inverseTransform) maxy = Number.MAX_VALUE; if (s.lines.show || s.points.show) { for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1]; if (x == null) continue; // For points and lines, the cursor must be within a // certain distance to the data point if (x - mx > maxx || x - mx < -maxx || y - my > maxy || y - my < -maxy) continue; // We have to calculate distances in pixels, not in // data units, because the scales of the axes may be different var dx = Math.abs(axisx.p2c(x) - mouseX), dy = Math.abs(axisy.p2c(y) - mouseY), dist = dx * dx + dy * dy; // we save the sqrt // use <= to ensure last point takes precedence // (last generally means on top of) if (dist < smallestDistance) { smallestDistance = dist; item = [i, j / ps]; } } } if (s.bars.show && !item) { // no other point can be nearby var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth / 2, barRight = barLeft + s.bars.barWidth; for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1], b = points[j + 2]; if (x == null) continue; // for a bar graph, the cursor must be inside the bar if (series[i].bars.horizontal ? (mx <= Math.max(b, x) && mx >= Math.min(b, x) && my >= y + barLeft && my <= y + barRight) : (mx >= x + barLeft && mx <= x + barRight && my >= Math.min(b, y) && my <= Math.max(b, y))) item = [i, j / ps]; } } } if (item) { i = item[0]; j = item[1]; ps = series[i].datapoints.pointsize; return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps), dataIndex: j, series: series[i], seriesIndex: i }; } return null; } function onMouseMove(e) { if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) { return s["hoverable"] != false; }); } function onMouseLeave(e) { if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) { return false; }); } function onClick(e) { triggerClickHoverEvent("plotclick", e, function (s) { return s["clickable"] != false; }); } // trigger click or hover event (they send the same parameters // so we share their code) function triggerClickHoverEvent(eventname, event, seriesFilter) { var offset = eventHolder.offset(), canvasX = event.pageX - offset.left - plotOffset.left, canvasY = event.pageY - offset.top - plotOffset.top, pos = canvasToAxisCoords({ left: canvasX, top: canvasY }); pos.pageX = event.pageX; pos.pageY = event.pageY; var item = findNearbyItem(canvasX, canvasY, seriesFilter); if (item) { // fill in mouse pos for any listeners out there item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left); item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top); } if (options.grid.autoHighlight) { // clear auto-highlights for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.auto == eventname && !(item && h.series == item.series && h.point[0] == item.datapoint[0] && h.point[1] == item.datapoint[1])) unhighlight(h.series, h.point); } if (item) highlight(item.series, item.datapoint, eventname); } placeholder.trigger(eventname, [ pos, item ]); } function triggerRedrawOverlay() { if (!redrawTimeout) redrawTimeout = setTimeout(drawOverlay, 30); } function drawOverlay() { redrawTimeout = null; // draw highlights octx.save(); octx.clearRect(0, 0, canvasWidth, canvasHeight); octx.translate(plotOffset.left, plotOffset.top); var i, hi; for (i = 0; i < highlights.length; ++i) { hi = highlights[i]; if (hi.series.bars.show) drawBarHighlight(hi.series, hi.point); else drawPointHighlight(hi.series, hi.point); } octx.restore(); executeHooks(hooks.drawOverlay, [octx]); } function highlight(s, point, auto) { if (typeof s == "number") s = series[s]; if (typeof point == "number") { var ps = s.datapoints.pointsize; point = s.datapoints.points.slice(ps * point, ps * (point + 1)); } var i = indexOfHighlight(s, point); if (i == -1) { highlights.push({ series: s, point: point, auto: auto }); triggerRedrawOverlay(); } else if (!auto) highlights[i].auto = false; } function unhighlight(s, point) { if (s == null && point == null) { highlights = []; triggerRedrawOverlay(); } if (typeof s == "number") s = series[s]; if (typeof point == "number") point = s.data[point]; var i = indexOfHighlight(s, point); if (i != -1) { highlights.splice(i, 1); triggerRedrawOverlay(); } } function indexOfHighlight(s, p) { for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.series == s && h.point[0] == p[0] && h.point[1] == p[1]) return i; } return -1; } function drawPointHighlight(series, point) { var x = point[0], y = point[1], axisx = series.xaxis, axisy = series.yaxis; if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) return; var pointRadius = series.points.radius + series.points.lineWidth / 2; octx.lineWidth = pointRadius; octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString(); var radius = 1.5 * pointRadius, x = axisx.p2c(x), y = axisy.p2c(y); octx.beginPath(); if (series.points.symbol == "circle") octx.arc(x, y, radius, 0, 2 * Math.PI, false); else series.points.symbol(octx, x, y, radius, false); octx.closePath(); octx.stroke(); } function drawBarHighlight(series, point) { octx.lineWidth = series.bars.lineWidth; octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString(); var fillStyle = $.color.parse(series.color).scale('a', 0.5).toString(); var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth / 2; drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth, 0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth); } function getColorOrGradient(spec, bottom, top, defaultColor) { if (typeof spec == "string") return spec; else { // assume this is a gradient spec; IE currently only // supports a simple vertical gradient properly, so that's // what we support too var gradient = ctx.createLinearGradient(0, top, 0, bottom); for (var i = 0, l = spec.colors.length; i < l; ++i) { var c = spec.colors[i]; if (typeof c != "string") { var co = $.color.parse(defaultColor); if (c.brightness != null) co = co.scale('rgb', c.brightness) if (c.opacity != null) co.a *= c.opacity; c = co.toString(); } gradient.addColorStop(i / (l - 1), c); } return gradient; } } } $.plot = function (placeholder, data, options) { //var t0 = new Date(); var plot = new Plot($(placeholder), data, options, $.plot.plugins); //(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime())); return plot; }; $.plot.version = "0.7"; $.plot.plugins = []; // returns a string with the date d formatted according to fmt $.plot.formatDate = function (d, fmt, monthNames) { var leftPad = function (n) { n = "" + n; return n.length == 1 ? "0" + n : n; }; var r = []; var escape = false, padNext = false; var hours = d.getUTCHours(); var isAM = hours < 12; if (monthNames == null) monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; if (fmt.search(/%p|%P/) != -1) { if (hours > 12) { hours = hours - 12; } else if (hours == 0) { hours = 12; } } for (var i = 0; i < fmt.length; ++i) { var c = fmt.charAt(i); if (escape) { switch (c) { case 'h': c = "" + hours; break; case 'H': c = leftPad(hours); break; case 'M': c = leftPad(d.getUTCMinutes()); break; case 'S': c = leftPad(d.getUTCSeconds()); break; case 'd': c = "" + d.getUTCDate(); break; case 'm': c = "" + (d.getUTCMonth() + 1); break; case 'y': c = "" + d.getUTCFullYear(); break; case 'b': c = "" + monthNames[d.getUTCMonth()]; break; case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break; case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break; case '0': c = ""; padNext = true; break; } if (c && padNext) { c = leftPad(c); padNext = false; } r.push(c); if (!padNext) escape = false; } else { if (c == "%") escape = true; else r.push(c); } } return r.join(""); }; // round to nearby lower multiple of base function floorInBase(n, base) { return base * Math.floor(n / base); } })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-plot-0.7.js
jquery-plot-0.7.js
(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) { if (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; } // Add novalidate tag if HTML5. this.attr("novalidate", "novalidate"); validator = new $.validator(options, this[0]); $.data(this[0], "validator", validator); if (validator.settings.onsubmit) { this.validateDelegate(":submit", "click", function (event) { if (validator.settings.submitHandler) { validator.submitButton = event.target; } // allow suppressing validation by adding a cancel class to the submit button if ($(event.target).hasClass("cancel")) { validator.cancelSubmit = true; } // allow suppressing validation by adding the html5 formnovalidate attribute to the submit button if ($(event.target).attr("formnovalidate") !== undefined) { validator.cancelSubmit = true; } }); // 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() { var hidden; if (validator.settings.submitHandler) { if (validator.submitButton) { // insert a hidden input as a replacement for the missing submit button hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val($(validator.submitButton).val()).appendTo(validator.currentForm); } validator.settings.submitHandler.call(validator, validator.currentForm, event); 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 = 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)); // remove messages from rules, but allow them to be set separetely delete existingRules.messages; staticRules[element.name] = existingRules; if (argument.messages) { settings.messages[element.name] = $.extend(settings.messages[element.name], argument.messages); } break; case "remove": if (!argument) { delete staticRules[element.name]; 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.classRules(element), $.validator.attributeRules(element), $.validator.dataRules(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).val()); }, // http://docs.jquery.com/Plugins/Validation/filled filled: function (a) { return !!$.trim("" + $(a).val()); }, // http://docs.jquery.com/Plugins/Validation/unchecked unchecked: function (a) { return !$(a).prop("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"), function () { return n; }); }); return source; }; $.extend($.validator, { defaults: { messages: {}, groups: {}, rules: {}, errorClass: "error", validClass: "valid", errorElement: "label", focusInvalid: true, errorContainer: $([]), errorLabelContainer: $([]), onsubmit: true, ignore: ":hidden", ignoreTitle: false, onfocusin: function (element, event) { this.lastActive = element; // hide error label and remove error class on focus if enabled if (this.settings.focusCleanup && !this.blockFocusCleanup) { if (this.settings.unhighlight) { this.settings.unhighlight.call(this, element, this.settings.errorClass, this.settings.validClass); } this.addWrapper(this.errorsFor(element)).hide(); } }, onfocusout: function (element, event) { if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) { this.element(element); } }, onkeyup: function (element, event) { if (event.which === 9 && this.elementValue(element) === "") { return; } else if (element.name in this.submitted || element === this.lastElement) { this.element(element); } }, onclick: function (element, event) { // click on selects, radiobuttons and checkboxes if (element.name 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) { if (element.type === "radio") { this.findByName(element.name).addClass(errorClass).removeClass(validClass); } else { $(element).addClass(errorClass).removeClass(validClass); } }, unhighlight: function (element, errorClass, validClass) { if (element.type === "radio") { this.findByName(element.name).removeClass(errorClass).addClass(validClass); } else { $(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.", 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) { if (typeof value === "string") { value = value.split(/\s/); } $.each(value, 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/, ""); if (validator.settings[eventType]) { validator.settings[eventType].call(validator, this[0], event); } } $(this.currentForm) .validateDelegate(":text, [type='password'], [type='file'], select, textarea, " + "[type='number'], [type='search'] ,[type='tel'], [type='url'], " + "[type='email'], [type='datetime'], [type='date'], [type='month'], " + "[type='week'], [type='time'], [type='datetime-local'], " + "[type='range'], [type='color'] ", "focusin focusout keyup", delegate) .validateDelegate("[type='radio'], [type='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.validationTargetFor(this.clean(element)); this.lastElement = element; this.prepareElement(element); this.currentElements = $(element); var result = this.check(element) !== false; if (result) { delete this.invalid[element.name]; } else { this.invalid[element.name] = 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.name in errors); }); } if (this.settings.showErrors) { this.settings.showErrors.call(this, this.errorMap, this.errorList); } else { this.defaultShowErrors(); } }, // http://docs.jquery.com/Plugins/Validation/Validator/resetForm resetForm: function () { if ($.fn.resetForm) { $(this.currentForm).resetForm(); } this.submitted = {}; this.lastElement = null; this.prepareForm(); this.hideErrors(); this.elements().removeClass(this.settings.errorClass).removeData("previousValue"); }, 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.name === lastActive.name; }).length === 1 && lastActive; }, elements: function () { var validator = this, rulesCache = {}; // select all valid inputs inside the form (no submit or reset buttons) return $(this.currentForm) .find("input, select, textarea") .not(":submit, :reset, :image, [disabled]") .not(this.settings.ignore) .filter(function () { if (!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 () { var errorClass = this.settings.errorClass.replace(" ", "."); return $(this.settings.errorElement + "." + 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); }, elementValue: function (element) { var type = $(element).attr("type"), val = $(element).val(); if (type === "radio" || type === "checkbox") { return $("input[name='" + $(element).attr("name") + "']:checked").val(); } if (typeof val === "string") { return val.replace(/\r/g, ""); } return val; }, check: function (element) { element = this.validationTargetFor(this.clean(element)); var rules = $(element).rules(); var dependencyMismatch = false; var val = this.elementValue(element); var result; for (var method in rules) { var rule = { method: method, parameters: rules[method] }; try { result = $.validator.methods[method].call(this, val, 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) { if (this.settings.debug && window.console) { console.log("Exception occurred 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 HTML5 data attribute customDataMessage: function (element, method) { return $(element).data("msg-" + method.toLowerCase()) || (element.attributes && $(element).attr("data-msg-" + method.toLowerCase())); }, // 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.name, method), this.customDataMessage(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.name + "</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 = $.validator.format(message.replace(theregex, "{$1}"), rule.parameters); } this.errorList.push({ message: message, element: element }); this.errorMap[element.name] = message; this.submitted[element.name] = message; }, addWrapper: function (toToggle) { if (this.settings.wrapper) { toToggle = toToggle.add(toToggle.parent(this.settings.wrapper)); } return toToggle; }, defaultShowErrors: function () { var i, elements; for (i = 0; this.errorList[i]; i++) { var error = this.errorList[i]; if (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 (i = 0; this.successList[i]; i++) { this.showLabel(this.successList[i]); } } if (this.settings.unhighlight) { for (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(this.settings.validClass).addClass(this.settings.errorClass); // replace message on existing label label.html(message); } else { // create label label = $("<" + this.settings.errorElement + ">") .attr("for", this.idOrName(element)) .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) { if (this.settings.errorPlacement) { this.settings.errorPlacement(label, $(element)); } else { label.insertAfter(element); } } } if (!message && this.settings.success) { label.text(""); if (typeof this.settings.success === "string") { label.addClass(this.settings.success); } else { this.settings.success(label, element); } } 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.name] || (this.checkable(element) ? element.name : element.id || element.name); }, validationTargetFor: function (element) { // if radio/checkbox, validate first element in group instead if (this.checkable(element)) { element = this.findByName(element.name).not(this.settings.ignore)[0]; } return element; }, checkable: function (element) { return (/radio|checkbox/i).test(element.type); }, findByName: function (name) { return $(this.currentForm).find("[name='" + name + "']"); }, 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.name).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) { var val = this.elementValue(element); return !$.validator.methods.required.call(this, val, element) && "dependency-mismatch"; }, startRequest: function (element) { if (!this.pending[element.name]) { this.pendingRequest++; this.pending[element.name] = 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.name]; 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}, number: {number: true}, digits: {digits: true}, creditcard: {creditcard: true} }, addClassRules: function (className, rules) { if (className.constructor === String) { this.classRuleSettings[className] = rules; } else { $.extend(this.classRuleSettings, className); } }, classRules: function (element) { var rules = {}; var classes = $(element).attr("class"); if (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); var type = $element[0].getAttribute("type"); for (var method in $.validator.methods) { var value; // support for <input required> in both html5 and older browsers if (method === "required") { value = $element.get(0).getAttribute(method); // Some browsers return an empty string for the required attribute // and non-HTML5 browsers might have required="" markup if (value === "") { value = true; } // force non-HTML5 browsers to return bool value = !!value; } else { value = $element.attr(method); } // convert the value to a number for number inputs, and for text for backwards compability // allows type="date" and others to be compared as strings if (/min|max/.test(method) && ( type === null || /number|range|text/.test(type) )) { value = Number(value); } if (value) { rules[method] = value; } else if (type === method && type !== 'range') { // exception: the jquery validate 'range' method // does not test for the html5 'range' type rules[method] = true; } } // 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; }, dataRules: function (element) { var method, value, rules = {}, $element = $(element); for (method in $.validator.methods) { value = $element.data("rule-" + method.toLowerCase()); if (value !== undefined) { rules[method] = value; } } return rules; }, staticRules: function (element) { var rules = {}; var validator = $.data(element.form, "validator"); if (validator.settings.rules) { rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {}; } 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'], function () { if (rules[this]) { rules[this] = Number(rules[this]); } }); $.each(['rangelength', 'range'], function () { var parts; if (rules[this]) { if ($.isArray(rules[this])) { rules[this] = [Number(rules[this][0]), Number(rules[this][1])]; } else if (typeof rules[this] === "string") { parts = rules[this].split(/[\s,]+/); rules[this] = [Number(parts[0]), Number(parts[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; } } 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"; } if (element.nodeName.toLowerCase() === "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; } if (this.checkable(element)) { return this.getLength(value, element) > 0; } return $.trim(value).length > 0; }, // 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?|s?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).toString()); }, // 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 spaces, 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); 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/minlength minlength: function (value, element, param) { var length = $.isArray(value) ? value.length : this.getLength($.trim(value), element); return this.optional(element) || length >= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/maxlength maxlength: function (value, element, param) { var length = $.isArray(value) ? value.length : this.getLength($.trim(value), element); return this.optional(element) || length <= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/rangelength rangelength: function (value, element, param) { var length = $.isArray(value) ? value.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/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); if (this.settings.onfocusout) { target.unbind(".validate-equalTo").bind("blur.validate-equalTo", function () { $(element).valid(); }); } return value === target.val(); }, // 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.name]) { this.settings.messages[element.name] = {}; } previous.originalMessage = this.settings.messages[element.name].remote; this.settings.messages[element.name].remote = previous.message; param = typeof param === "string" && {url: param} || param; if (previous.old === value) { return previous.valid; } previous.old = value; var validator = this; this.startRequest(element); var data = {}; data[element.name] = value; $.ajax($.extend(true, { url: param, mode: "abort", port: "validate" + element.name, dataType: "json", data: data, success: function (response) { validator.settings.messages[element.name].remote = previous.originalMessage; var valid = response === true || response === "true"; if (valid) { var submitted = validator.formSubmitted; validator.prepareElement(element); validator.formSubmitted = submitted; validator.successList.push(element); delete validator.invalid[element.name]; validator.showErrors(); } else { var errors = {}; var message = response || validator.defaultMessage(element, "remote"); errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message; validator.invalid[element.name] = true; validator.showErrors(errors); } previous.valid = valid; validator.stopRequest(element, valid); } }, param)); return "pending"; } } }); // 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(); } pendingRequests[port] = ajax.apply(this, arguments); return pendingRequests[port]; } return ajax.apply(this, arguments); }; } }(jQuery)); // 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 ($) { $.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));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-validate-1.11.1.js
jquery-validate-1.11.1.js
(function(a){a.fn.makeEditable=function(B){var k=0;function f(ab){return c.fnGetRowID(a(ab.parentNode))}function E(ac,ad,ab){if(ab){ac.attr("id",ad)}else{if(ac.attr("id")==null||ac.attr("id")==""){ac.attr("id",ad)}}}function n(ab){return ab.attr("id")}function aa(ab,ac){a("td:first",ab).html(ac)}function H(ab){return a("td:first",ab).html()}var z;var h,x,Y,X;var j;var c;function g(ab,ac){alert(ab)}function T(){if(z.fnSettings().oFeatures.bProcessing){a(".dataTables_processing").css("visibility","visible")}}function S(){if(z.fnSettings().oFeatures.bProcessing){a(".dataTables_processing").css("visibility","hidden")}}var J,y,o;function M(ah){if(c.bDisableEditing){return}var ag={event:"dblclick",onsubmit:function(an,al){J=al.revert;y=null;sNewCellDisplayValue=null;k=b();if(an.type=="text"||an.type=="select"||an.type=="textarea"){var ak=a("input,select,textarea",this);y=a("input,select,textarea",a(this)).val();if(ak.length==1){var am=ak[0];if(am.nodeName.toLowerCase()=="select"||am.tagName.toLowerCase()=="select"){sNewCellDisplayValue=a("option:selected",am).text()}else{sNewCellDisplayValue=y}}if(!c.fnOnEditing(ak,an,al.revert,f(al))){return false}var aj=an;if(an.oValidationOptions!=null){ak.parents("form").validate(an.oValidationOptions)}if(an.cssclass!=null){ak.addClass(an.cssclass)}if(an.cssclass==null&&an.oValidationOptions==null){return true}else{if(!ak.valid()||0==ak.valid()){return false}else{return true}}}c.fnStartProcessingMode()},submitdata:function(an,al){var aq=f(this);var ap=z.fnGetPosition(this)[0];var ao=z.fnGetPosition(this)[1];var am=z.fnGetPosition(this)[2];var ak=z.fnSettings().aoColumns[am].sName;if(ak==null||ak==""){ak=z.fnSettings().aoColumns[am].sTitle}var aj=null;if(c.aoColumns==null||c.aoColumns[am]==null){aj=a.extend({},c.oUpdateParameters,{id:aq,rowId:ap,columnPosition:ao,columnId:am,columnName:ak})}else{aj=a.extend({},c.oUpdateParameters,c.aoColumns[am].oUpdateParameters,{id:aq,rowId:ap,columnPosition:ao,columnId:am,columnName:ak})}return aj},callback:function(ao,al){c.fnEndProcessingMode();var ak="";var aj=z.fnGetPosition(this);var an=!N.oFeatures.bServerSide;a("td.last-updated-cell",z.fnGetNodes()).removeClass("last-updated-cell");if(ao.indexOf(c.sFailureResponsePrefix)>-1){z.fnUpdate(J,aj[0],aj[2],an);a("td.last-updated-cell",z).removeClass("last-updated-cell");a(this).addClass("last-updated-cell");c.fnShowError(ao.replace(c.sFailureResponsePrefix,"").trim(),"update");ak="failure"}else{if(c.sSuccessResponse=="IGNORE"||(c.aoColumns!=null&&c.aoColumns[aj[2]]!=null&&c.aoColumns[aj[2]].sSuccessResponse=="IGNORE")||(y==null)||(y==ao)||c.sSuccessResponse==ao){if(sNewCellDisplayValue==null){z.fnUpdate(ao,aj[0],aj[2],an)}else{z.fnUpdate(sNewCellDisplayValue,aj[0],aj[2],an)}a("td.last-updated-cell",z).removeClass("last-updated-cell");a(this).addClass("last-updated-cell");ak="success"}else{z.fnUpdate(J,aj[0],aj[2],an);c.fnShowError(ao,"update");ak="failure"}}c.fnOnEdited(ak,J,sNewCellDisplayValue,aj[0],aj[1],aj[2]);if(al.fnOnCellUpdated!=null){al.fnOnCellUpdated(ak,ao,aj[0],aj[2],al)}r();if(c.bUseKeyTable){var am=z.keys;setTimeout(function(){am.block=false},0)}},onerror:function(){c.fnEndProcessingMode();c.fnShowError("Cell cannot be updated","update");c.fnOnEdited("failure")},onreset:function(){if(c.bUseKeyTable){var aj=z.keys;setTimeout(function(){aj.block=false},0)}},height:c.sEditorHeight,width:c.sEditorWidth};var ac=null;if(c.aoColumns!=null){for(var af=0,ai=0;af<N.aoColumns.length;af++){if(N.aoColumns[af].bVisible){if(c.aoColumns[ai]==null){ai++;continue}ac=a("td:nth-child("+(ai+1)+")",ah);var ae=ag;ae=a.extend({},ag,c.oEditableSettings,c.aoColumns[ai]);ai++;var ab=c.sUpdateURL;try{if(ae.sUpdateURL!=null){ab=ae.sUpdateURL}}catch(ad){}ac.each(function(){if(!a(this).hasClass(c.sReadOnlyCellClass)){a(this).editable(ab,ae)}})}}}else{ac=a("td:not(."+c.sReadOnlyCellClass+")",ah);ac.editable(c.sUpdateURL,a.extend({},ag,c.oEditableSettings))}}function l(ab){if(c.fnOnAdding()){if(j.valid()){k=b();c.fnStartProcessingMode();if(c.bUseFormsPlugin){a(j).ajaxSubmit({dataType:"xml",success:function(ad,ae,af){if(af.responseText.toLowerCase().indexOf("error")!=-1){c.fnEndProcessingMode();c.fnShowError(af.responseText.replace("Error",""),"add");c.fnOnAdded("failure")}else{e(af.responseText)}},error:function(ad){c.fnEndProcessingMode();c.fnShowError(ad.responseText,"add");c.fnOnAdded("failure")}})}else{var ac=j.serialize();a.ajax({url:c.sAddURL,data:ac,type:c.sAddHttpMethod,dataType:c.sAddDataType,success:e,error:function(ad){c.fnEndProcessingMode();c.fnShowError(ad.responseText,"add");c.fnOnAdded("failure")}})}}}ab.stopPropagation();ab.preventDefault()}function s(ab){return true}function e(af){c.fnEndProcessingMode();if(c.fnOnNewRowPosted(af)){var ag=z.fnSettings();if(!ag.oFeatures.bServerSide){jQuery.data(j,"DT_RowId",af);var ab=d(j);var ae;if(ag.aoColumns!=null&&isNaN(parseInt(ag.aoColumns[0].mDataProp))){ae=z.fnAddData(rowData)}else{ae=z.fnAddData(ab)}var ac=z.fnGetNodes(ae);c.fnSetRowID(a(ac),af,true);M(ac);a("tr.last-added-row",z).removeClass("last-added-row");a(ac).addClass("last-added-row")}j.dialog("close");a(j)[0].reset();a(".error",a(j)).html("");r();c.fnOnAdded("success");if(c.bUseKeyTable){var ad=z.keys;setTimeout(function(){ad.block=false},0)}}}function O(ab){a(j).validate().resetForm();a(j)[0].reset();a(".error",a(j)).html("");a(".error",a(j)).hide();j.dialog("close");ab.stopPropagation();ab.preventDefault()}function V(){if(c.bUseKeyTable){return}if(c.oDeleteRowButtonOptions!=null){x.button("option","disabled",true)}else{x.attr("disabled","true")}}function m(){if(c.oDeleteRowButtonOptions!=null){x.button("option","disabled",false)}else{x.removeAttr("disabled")}}var W,K;var p;function q(ac){var ab=a(this).attr("href");if(ab==null||ab==""){ab=c.sDeleteURL}ac.preventDefault();ac.stopPropagation();k=b();K=(a(this).parents("td"))[0];jSelectedRow=(a(this).parents("tr"));W=jSelectedRow[0];jSelectedRow.addClass(c.sSelectedRowClass);var ad=f(K);if(c.fnOnDeleting(jSelectedRow,ad,v)){v(ad,ab)}}function C(ac){ac.preventDefault();ac.stopPropagation();k=b();W=null;K=null;if(!c.bUseKeyTable){if(a("tr."+c.sSelectedRowClass+" td",z).length==0){_fnDisableDeleteButton();return}K=a("tr."+c.sSelectedRowClass+" td",z)[0]}else{K=a("td.focus",z)[0]}if(K==null){V();return}if(c.bUseKeyTable){p=z.keys.fnGetCurrentPosition()}var ad=f(K);var ab=a(K).parent("tr");W=ab[0];if(c.fnOnDeleting(ab,ad,v)){v(ad)}}function Z(ac,ad,ab){return confirm("Are you sure that you want to delete this record?")}function v(ae,ab){var ad=ab;if(ab==null){ad=c.sDeleteURL}c.fnStartProcessingMode();var ac=a.extend(c.oDeleteParameters,{id:ae});a.ajax({url:ad,type:c.sDeleteHttpMethod,data:ac,success:A,dataType:c.sDeleteDataType,error:function(af){c.fnEndProcessingMode();c.fnShowError(af.responseText,"delete");c.fnOnDeleted("failure")}})}function A(ab){c.fnEndProcessingMode();var ac=W;if(ab==c.sSuccessResponse||ab==""){z.fnDeleteRow(ac);V();r();if(c.bUseKeyTable){z.keys.fnSetPosition(p[0],p[1])}c.fnOnDeleted("success")}else{c.fnShowError(ab,"delete");c.fnOnDeleted("failure")}}function G(ab){}function t(ab){return true}function U(ab,ad,ag,af,ac,ae){}function F(){return true}function w(ab){}var N;function b(){return N._iDisplayStart}function r(){N._iDisplayStart=k;N.oApi._fnCalculateEnd(N);N.oApi._fnDraw(N)}function P(ab){return true}function u(ab){}function D(ab){if(c.aoTableAction){c.fnShowError("Configuration error - aoTableAction setting are not set",ab)}var ac=0;for(ac=0;ac<c.aoTableActions.length;ac++){if(c.aoTableActions[ac].sAction==ab){return c.aoTableActions[ac]}}c.fnShowError("Cannot find action configuration settings",ab)}function I(af,ac){var ae=z.fnGetPosition(ac);var ag=c.fnGetRowID(a(ac));a(af).validate().resetForm();jQuery.data(a(af)[0],"DT_RowId",ag);a("input.DT_RowId",a(af)).val(ag);jQuery.data(a(af)[0],"ROWID",ae);a("input.ROWID",a(af)).val(ae);var ad=z.fnSettings();var ab=ad.aoColumns.length;a("input:text[rel],input:radio[rel][checked],input:hidden[rel],select[rel],textarea[rel],input:checkbox[rel]",a(af)).each(function(){var ah=a(this).attr("rel");if(ah>=ab){c.fnShowError("In the form is placed input element with the name '"+a(this).attr("name")+"' with the 'rel' attribute that must be less than a column count - "+ab,"action")}else{var ai=z.fnGetData(ac)[ah];if(this.nodeName.toLowerCase()=="select"||this.tagName.toLowerCase()=="select"){if(this.multiple==true){var aj=new Array();aoCellValues=ai.split(",");for(i=0;i<=this.options.length-1;i++){if(jQuery.inArray(this.options[i].text.toLowerCase().trim(),aoCellValues)!=-1){aj.push(this.options[i].value)}}a(this).val(aj)}else{for(i=0;i<=this.options.length-1;i++){if(this.options[i].text.toLowerCase()==ai.toLowerCase()){a(this).val(this.options[i].value)}}}}else{if(this.nodeName.toLowerCase()=="span"||this.tagName.toLowerCase()=="span"){a(this).html(ai)}else{if(this.type=="checkbox"){if(ai=="true"){a(this).attr("checked",true)}}else{if(this.type=="radio"){if(this.value==ai){this.checked=true}}else{this.value=ai}}}}}})}function d(af){var ad=jQuery.data(af,"DT_RowId");var ac=N.aoColumns.length;var ab=new Array();var ae=new Object();a("input:text[rel],input:radio[rel][checked],input:hidden[rel],select[rel],textarea[rel],span.datafield[rel],input:checkbox[rel]",af).each(function(){var ag=a(this).attr("rel");var ah="";if(ag>=ac){c.fnShowError("In the add form is placed input element with the name '"+a(this).attr("name")+"' with the 'rel' attribute that must be less than a column count - "+ac,"add")}else{if(this.nodeName.toLowerCase()=="select"||this.tagName.toLowerCase()=="select"){ah=a.map(a.makeArray(a("option:selected",this)),function(aj,ai){return a(aj).text()}).join(",")}else{if(this.nodeName.toLowerCase()=="span"||this.tagName.toLowerCase()=="span"){ah=a(this).html()}else{if(this.type=="checkbox"){if(this.checked){ah=(this.value!="on")?this.value:"true"}else{ah=(this.value!="on")?"":"false"}}else{ah=this.value}}}ah=ah.replace("DATAROWID",ad);ah=ah.replace(c.sIDToken,ad);if(N.aoColumns!=null&&N.aoColumns[ag]!=null&&isNaN(parseInt(N.aoColumns[0].mDataProp))){ae[N.aoColumns[ag].mDataProp]=ah}else{ab[ag]=ah}}});if(N.aoColumns!=null&&isNaN(parseInt(N.aoColumns[0].mDataProp))){return ae}else{return ab}}function Q(af){var ad=a(af);var ab=ad.attr("id");ab=ab.replace("form","");var ac=ad.attr("action");if(c.fnOnBeforeAction(ab)){if(ad.valid()){k=b();c.fnStartProcessingMode();if(c.bUseFormsPlugin){var ae={success:function(ai,aj,ak){c.fnEndProcessingMode();if(ai.toLowerCase().indexOf("error")!=-1||aj!="success"){c.fnShowError(ai,ab);c.fnOnActionCompleted("failure")}else{R(af);c.fnOnActionCompleted("success")}},error:function(ai){c.fnEndProcessingMode();c.fnShowError(ai.responseText,ab);c.fnOnActionCompleted("failure")}};var ag=D(ab);ae=a.extend({},c.oAjaxSubmitOptions,ae);a(oActionForm).ajaxSubmit(ae)}else{var ah=ad.serialize();a.ajax({url:ac,data:ah,type:c.sAddHttpMethod,dataType:c.sAddDataType,success:function(ai){c.fnEndProcessingMode();R(af);c.fnOnActionCompleted("success")},error:function(ai){c.fnEndProcessingMode();c.fnShowError(ai.responseText,ab);c.fnOnActionCompleted("failure")}})}}}}function R(ad){var ac=d(ad);var ag=jQuery.data(ad,"ROWID");var af=z.fnSettings();var ae=af.aoColumns.length;for(var ab=0;ab<ae;ab++){if(af.aoColumns!=null&&af.aoColumns[ab]!=null&&isNaN(parseInt(af.aoColumns[0].mDataProp))){sCellValue=rowData[af.aoColumns[ab].mDataProp]}else{sCellValue=ac[ab]}if(sCellValue!=undefined){z.fnUpdate(sCellValue,ag,ab)}}r();a(ad).dialog("close");return}z=this;var L={sUpdateURL:"UpdateData",sAddURL:"AddData",sDeleteURL:"DeleteData",sAddNewRowFormId:"formAddNewRow",oAddNewRowFormOptions:{autoOpen:false,modal:true},sAddNewRowButtonId:"btnAddNewRow",oAddNewRowButtonOptions:null,sAddNewRowOkButtonId:"btnAddNewRowOk",sAddNewRowCancelButtonId:"btnAddNewRowCancel",oAddNewRowOkButtonOptions:{label:"Ok"},oAddNewRowCancelButtonOptions:{label:"Cancel"},sDeleteRowButtonId:"btnDeleteRow",oDeleteRowButtonOptions:null,sSelectedRowClass:"row_selected",sReadOnlyCellClass:"read_only",sAddDeleteToolbarSelector:".add_delete_toolbar",fnShowError:g,fnStartProcessingMode:T,fnEndProcessingMode:S,aoColumns:null,fnOnDeleting:Z,fnOnDeleted:G,fnOnAdding:F,fnOnNewRowPosted:s,fnOnAdded:w,fnOnEditing:t,fnOnEdited:U,sAddHttpMethod:"POST",sAddDataType:"text",sDeleteHttpMethod:"POST",sDeleteDataType:"text",fnGetRowID:n,fnSetRowID:E,sEditorHeight:"100%",sEditorWidth:"100%",bDisableEditing:false,oEditableSettings:null,oDeleteParameters:{},oUpdateParameters:{},sIDToken:"DT_RowId",aoTableActions:null,fnOnBeforeAction:P,bUseFormsPlugin:false,fnOnActionCompleted:u,sSuccessResponse:"ok",sFailureResponsePrefix:"ERROR",oKeyTable:null};c=a.extend(L,B);N=z.fnSettings();c.bUseKeyTable=(c.oKeyTable!=null);return this.each(function(){var ae=z.dataTableSettings[0].sTableId;if(c.bUseKeyTable){var ao=new KeyTable({table:document.getElementById(ae),datatable:z});z.keys=ao;ao.event.action(null,null,function(ap){if(a(ap).hasClass(c.sReadOnlyCellClass)){return}ao.block=true;setTimeout(function(){a(ap).dblclick()},0)})}if(z.fnSettings().sAjaxSource!=null){z.fnSettings().aoDrawCallback.push({fn:function(){M(z.fnGetNodes());a(z.fnGetNodes()).each(function(){var ap=z.fnGetPosition(this);var aq=z.fnGetData(ap)[0];c.fnSetRowID(a(this),aq)})},sName:"fnApplyEditable"})}else{M(z.fnGetNodes())}j=a("#"+c.sAddNewRowFormId);if(j.length!=0){var ac=z.fnSettings();var an=ac.aoColumns.length;for(ai=0;ai<an;ai++){if(a("[rel="+ai+"]",j).length==0){c.fnShowError("In the form that is used for adding new records cannot be found an input element with rel="+ai+" that will be bound to the value in the column "+ai+". See http://code.google.com/p/jquery-datatables-editable/wiki/AddingNewRecords#Add_new_record_form for more details","init")}}if(c.oAddNewRowFormOptions!=null){c.oAddNewRowFormOptions.autoOpen=false}else{c.oAddNewRowFormOptions={autoOpen:false}}j.dialog(c.oAddNewRowFormOptions);h=a("#"+c.sAddNewRowButtonId);if(h.length!=0){if(h.data("add-event-attached")!="true"){h.click(function(){j.dialog("open")});h.data("add-event-attached","true")}}else{if(a(c.sAddDeleteToolbarSelector).length==0){throw"Cannot find a button with an id '"+c.sAddNewRowButtonId+"', or placeholder with an id '"+c.sAddDeleteToolbarSelector+"' that should be used for adding new row although form for adding new record is specified"}else{h=null}}if(j[0].nodeName.toLowerCase()=="form"){j.unbind("submit");j.submit(function(ap){l(ap);return false})}else{a("form",j[0]).unbind("submit");a("form",j[0]).submit(function(ap){l(ap);return false})}var ab=[];Y=a("#"+c.sAddNewRowOkButtonId,j);if(Y.length==0){if(c.oAddNewRowOkButtonOptions.text==null||c.oAddNewRowOkButtonOptions.text==""){c.oAddNewRowOkButtonOptions.text="Ok"}c.oAddNewRowOkButtonOptions.click=l;c.oAddNewRowOkButtonOptions.id=c.sAddNewRowOkButtonId;ab.push(c.oAddNewRowOkButtonOptions)}else{Y.click(l)}X=a("#"+c.sAddNewRowCancelButtonId);if(X.length==0){if(c.oAddNewRowCancelButtonOptions.text==null||c.oAddNewRowCancelButtonOptions.text==""){c.oAddNewRowCancelButtonOptions.text="Cancel"}c.oAddNewRowCancelButtonOptions.click=O;c.oAddNewRowCancelButtonOptions.id=c.sAddNewRowCancelButtonId;ab.push(c.oAddNewRowCancelButtonOptions)}else{X.click(O)}if(ab.length>0){j.dialog("option","buttons",ab)}Y=a("#"+c.sAddNewRowOkButtonId);X=a("#"+c.sAddNewRowCancelButtonId);if(c.oAddNewRowFormValidation!=null){j.validate(c.oAddNewRowFormValidation)}}else{j=null}x=a("#"+c.sDeleteRowButtonId);if(x.length!=0){if(x.data("delete-event-attached")!="true"){x.click(C);x.data("delete-event-attached","true")}}else{x=null}oAddDeleteToolbar=a(c.sAddDeleteToolbarSelector);if(oAddDeleteToolbar.length!=0){if(h==null&&c.sAddNewRowButtonId!=""&&j!=null){oAddDeleteToolbar.append("<button id='"+c.sAddNewRowButtonId+"' class='add_row'>Add</button>");h=a("#"+c.sAddNewRowButtonId);h.click(function(){j.dialog("open")})}if(x==null&&c.sDeleteRowButtonId!=""){oAddDeleteToolbar.append("<button id='"+c.sDeleteRowButtonId+"' class='delete_row'>Delete</button>");x=a("#"+c.sDeleteRowButtonId);x.click(C)}}if(x!=null){if(c.oDeleteRowButtonOptions!=null){x.button(c.oDeleteRowButtonOptions)}V()}if(h!=null){if(c.oAddNewRowButtonOptions!=null){h.button(c.oAddNewRowButtonOptions)}}if(Y!=null){if(c.oAddNewRowOkButtonOptions!=null){Y.button(c.oAddNewRowOkButtonOptions)}}if(X!=null){if(c.oAddNewRowCancelButtonOptions!=null){X.button(c.oAddNewRowCancelButtonOptions)}}a(".table-action-deletelink",z).live("click",q);if(!c.bUseKeyTable){a("tbody",z).click(function(ap){if(a(ap.target.parentNode).hasClass(c.sSelectedRowClass)){a(ap.target.parentNode).removeClass(c.sSelectedRowClass);if(x!=null){V()}}else{a(z.fnSettings().aoData).each(function(){a(this.nTr).removeClass(c.sSelectedRowClass)});a(ap.target.parentNode).addClass(c.sSelectedRowClass);if(x!=null){m()}}})}else{z.keys.event.focus(null,null,function(aq,ap,ar){})}if(c.aoTableActions!=null){for(var ai=0;ai<c.aoTableActions.length;ai++){var ah=a.extend({sType:"edit"},c.aoTableActions[ai]);var al=ah.sAction;var af=ah.sActionFormId;var aj=a("#form"+al);if(aj.length!=0){var ak={autoOpen:false,modal:true};ak=a.extend({},ah.oFormOptions,ak);aj.dialog(ak);aj.data("action-options",ah);var am=a(".table-action-"+al);if(am.length!=0){am.live("click",function(){var av=this.className;var au=av.split(/\s+/);var ar="";var ap="";for(ai=0;ai<au.length;ai++){if(au[ai].indexOf("table-action-")>-1){ap=au[ai].replace("table-action-","");ar="#form"+ap}}if(ar==""){c.fnShowError("Cannot find a form with an id "+ar+" that should be associated to the action - "+ap,ap)}var at=a(ar).data("action-options");if(at.sType=="edit"){var aq=(a(this).parents("tr"))[0];I(aj,aq)}a(aj).dialog("open")})}aj.submit(function(ap){Q(this);return false});var ad=new Array();var ag=a("#form"+al+"Cancel",aj);if(ag.length!=0){ad.push(ag);ag.click(function(){var ap=a(this).parents("form")[0];a(ap).validate().resetForm();a(ap)[0].reset();a(".error",a(ap)).html("");a(".error",a(ap)).hide();a(ap).dialog("close")})}a("button",aj).button()}}}})}})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-editable.min.js
jquery-dataTables-editable.min.js
(function ($) { if(typeof $.fn.each2 == "undefined") { $.extend($.fn, { /* * 4-10 times faster .each replacement * use it carefully, as it overrides jQuery context of element on each iteration */ each2 : function (c) { var j = $([0]), i = -1, l = this.length; while ( ++i < l && (j.context = j[0] = this[i]) && c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object ); return this; } }); } })(jQuery); (function ($, undefined) { "use strict"; /*global document, window, jQuery, console */ if (window.Select2 !== undefined) { return; } var AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer, lastMousePosition={x:0,y:0}, $document, scrollBarDimensions, KEY = { TAB: 9, ENTER: 13, ESC: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, SHIFT: 16, CTRL: 17, ALT: 18, PAGE_UP: 33, PAGE_DOWN: 34, HOME: 36, END: 35, BACKSPACE: 8, DELETE: 46, isArrow: function (k) { k = k.which ? k.which : k; switch (k) { case KEY.LEFT: case KEY.RIGHT: case KEY.UP: case KEY.DOWN: return true; } return false; }, isControl: function (e) { var k = e.which; switch (k) { case KEY.SHIFT: case KEY.CTRL: case KEY.ALT: return true; } if (e.metaKey) return true; return false; }, isFunctionKey: function (k) { k = k.which ? k.which : k; return k >= 112 && k <= 123; } }, MEASURE_SCROLLBAR_TEMPLATE = "<div class='select2-measure-scrollbar'></div>", DIACRITICS = {"\u24B6":"A","\uFF21":"A","\u00C0":"A","\u00C1":"A","\u00C2":"A","\u1EA6":"A","\u1EA4":"A","\u1EAA":"A","\u1EA8":"A","\u00C3":"A","\u0100":"A","\u0102":"A","\u1EB0":"A","\u1EAE":"A","\u1EB4":"A","\u1EB2":"A","\u0226":"A","\u01E0":"A","\u00C4":"A","\u01DE":"A","\u1EA2":"A","\u00C5":"A","\u01FA":"A","\u01CD":"A","\u0200":"A","\u0202":"A","\u1EA0":"A","\u1EAC":"A","\u1EB6":"A","\u1E00":"A","\u0104":"A","\u023A":"A","\u2C6F":"A","\uA732":"AA","\u00C6":"AE","\u01FC":"AE","\u01E2":"AE","\uA734":"AO","\uA736":"AU","\uA738":"AV","\uA73A":"AV","\uA73C":"AY","\u24B7":"B","\uFF22":"B","\u1E02":"B","\u1E04":"B","\u1E06":"B","\u0243":"B","\u0182":"B","\u0181":"B","\u24B8":"C","\uFF23":"C","\u0106":"C","\u0108":"C","\u010A":"C","\u010C":"C","\u00C7":"C","\u1E08":"C","\u0187":"C","\u023B":"C","\uA73E":"C","\u24B9":"D","\uFF24":"D","\u1E0A":"D","\u010E":"D","\u1E0C":"D","\u1E10":"D","\u1E12":"D","\u1E0E":"D","\u0110":"D","\u018B":"D","\u018A":"D","\u0189":"D","\uA779":"D","\u01F1":"DZ","\u01C4":"DZ","\u01F2":"Dz","\u01C5":"Dz","\u24BA":"E","\uFF25":"E","\u00C8":"E","\u00C9":"E","\u00CA":"E","\u1EC0":"E","\u1EBE":"E","\u1EC4":"E","\u1EC2":"E","\u1EBC":"E","\u0112":"E","\u1E14":"E","\u1E16":"E","\u0114":"E","\u0116":"E","\u00CB":"E","\u1EBA":"E","\u011A":"E","\u0204":"E","\u0206":"E","\u1EB8":"E","\u1EC6":"E","\u0228":"E","\u1E1C":"E","\u0118":"E","\u1E18":"E","\u1E1A":"E","\u0190":"E","\u018E":"E","\u24BB":"F","\uFF26":"F","\u1E1E":"F","\u0191":"F","\uA77B":"F","\u24BC":"G","\uFF27":"G","\u01F4":"G","\u011C":"G","\u1E20":"G","\u011E":"G","\u0120":"G","\u01E6":"G","\u0122":"G","\u01E4":"G","\u0193":"G","\uA7A0":"G","\uA77D":"G","\uA77E":"G","\u24BD":"H","\uFF28":"H","\u0124":"H","\u1E22":"H","\u1E26":"H","\u021E":"H","\u1E24":"H","\u1E28":"H","\u1E2A":"H","\u0126":"H","\u2C67":"H","\u2C75":"H","\uA78D":"H","\u24BE":"I","\uFF29":"I","\u00CC":"I","\u00CD":"I","\u00CE":"I","\u0128":"I","\u012A":"I","\u012C":"I","\u0130":"I","\u00CF":"I","\u1E2E":"I","\u1EC8":"I","\u01CF":"I","\u0208":"I","\u020A":"I","\u1ECA":"I","\u012E":"I","\u1E2C":"I","\u0197":"I","\u24BF":"J","\uFF2A":"J","\u0134":"J","\u0248":"J","\u24C0":"K","\uFF2B":"K","\u1E30":"K","\u01E8":"K","\u1E32":"K","\u0136":"K","\u1E34":"K","\u0198":"K","\u2C69":"K","\uA740":"K","\uA742":"K","\uA744":"K","\uA7A2":"K","\u24C1":"L","\uFF2C":"L","\u013F":"L","\u0139":"L","\u013D":"L","\u1E36":"L","\u1E38":"L","\u013B":"L","\u1E3C":"L","\u1E3A":"L","\u0141":"L","\u023D":"L","\u2C62":"L","\u2C60":"L","\uA748":"L","\uA746":"L","\uA780":"L","\u01C7":"LJ","\u01C8":"Lj","\u24C2":"M","\uFF2D":"M","\u1E3E":"M","\u1E40":"M","\u1E42":"M","\u2C6E":"M","\u019C":"M","\u24C3":"N","\uFF2E":"N","\u01F8":"N","\u0143":"N","\u00D1":"N","\u1E44":"N","\u0147":"N","\u1E46":"N","\u0145":"N","\u1E4A":"N","\u1E48":"N","\u0220":"N","\u019D":"N","\uA790":"N","\uA7A4":"N","\u01CA":"NJ","\u01CB":"Nj","\u24C4":"O","\uFF2F":"O","\u00D2":"O","\u00D3":"O","\u00D4":"O","\u1ED2":"O","\u1ED0":"O","\u1ED6":"O","\u1ED4":"O","\u00D5":"O","\u1E4C":"O","\u022C":"O","\u1E4E":"O","\u014C":"O","\u1E50":"O","\u1E52":"O","\u014E":"O","\u022E":"O","\u0230":"O","\u00D6":"O","\u022A":"O","\u1ECE":"O","\u0150":"O","\u01D1":"O","\u020C":"O","\u020E":"O","\u01A0":"O","\u1EDC":"O","\u1EDA":"O","\u1EE0":"O","\u1EDE":"O","\u1EE2":"O","\u1ECC":"O","\u1ED8":"O","\u01EA":"O","\u01EC":"O","\u00D8":"O","\u01FE":"O","\u0186":"O","\u019F":"O","\uA74A":"O","\uA74C":"O","\u01A2":"OI","\uA74E":"OO","\u0222":"OU","\u24C5":"P","\uFF30":"P","\u1E54":"P","\u1E56":"P","\u01A4":"P","\u2C63":"P","\uA750":"P","\uA752":"P","\uA754":"P","\u24C6":"Q","\uFF31":"Q","\uA756":"Q","\uA758":"Q","\u024A":"Q","\u24C7":"R","\uFF32":"R","\u0154":"R","\u1E58":"R","\u0158":"R","\u0210":"R","\u0212":"R","\u1E5A":"R","\u1E5C":"R","\u0156":"R","\u1E5E":"R","\u024C":"R","\u2C64":"R","\uA75A":"R","\uA7A6":"R","\uA782":"R","\u24C8":"S","\uFF33":"S","\u1E9E":"S","\u015A":"S","\u1E64":"S","\u015C":"S","\u1E60":"S","\u0160":"S","\u1E66":"S","\u1E62":"S","\u1E68":"S","\u0218":"S","\u015E":"S","\u2C7E":"S","\uA7A8":"S","\uA784":"S","\u24C9":"T","\uFF34":"T","\u1E6A":"T","\u0164":"T","\u1E6C":"T","\u021A":"T","\u0162":"T","\u1E70":"T","\u1E6E":"T","\u0166":"T","\u01AC":"T","\u01AE":"T","\u023E":"T","\uA786":"T","\uA728":"TZ","\u24CA":"U","\uFF35":"U","\u00D9":"U","\u00DA":"U","\u00DB":"U","\u0168":"U","\u1E78":"U","\u016A":"U","\u1E7A":"U","\u016C":"U","\u00DC":"U","\u01DB":"U","\u01D7":"U","\u01D5":"U","\u01D9":"U","\u1EE6":"U","\u016E":"U","\u0170":"U","\u01D3":"U","\u0214":"U","\u0216":"U","\u01AF":"U","\u1EEA":"U","\u1EE8":"U","\u1EEE":"U","\u1EEC":"U","\u1EF0":"U","\u1EE4":"U","\u1E72":"U","\u0172":"U","\u1E76":"U","\u1E74":"U","\u0244":"U","\u24CB":"V","\uFF36":"V","\u1E7C":"V","\u1E7E":"V","\u01B2":"V","\uA75E":"V","\u0245":"V","\uA760":"VY","\u24CC":"W","\uFF37":"W","\u1E80":"W","\u1E82":"W","\u0174":"W","\u1E86":"W","\u1E84":"W","\u1E88":"W","\u2C72":"W","\u24CD":"X","\uFF38":"X","\u1E8A":"X","\u1E8C":"X","\u24CE":"Y","\uFF39":"Y","\u1EF2":"Y","\u00DD":"Y","\u0176":"Y","\u1EF8":"Y","\u0232":"Y","\u1E8E":"Y","\u0178":"Y","\u1EF6":"Y","\u1EF4":"Y","\u01B3":"Y","\u024E":"Y","\u1EFE":"Y","\u24CF":"Z","\uFF3A":"Z","\u0179":"Z","\u1E90":"Z","\u017B":"Z","\u017D":"Z","\u1E92":"Z","\u1E94":"Z","\u01B5":"Z","\u0224":"Z","\u2C7F":"Z","\u2C6B":"Z","\uA762":"Z","\u24D0":"a","\uFF41":"a","\u1E9A":"a","\u00E0":"a","\u00E1":"a","\u00E2":"a","\u1EA7":"a","\u1EA5":"a","\u1EAB":"a","\u1EA9":"a","\u00E3":"a","\u0101":"a","\u0103":"a","\u1EB1":"a","\u1EAF":"a","\u1EB5":"a","\u1EB3":"a","\u0227":"a","\u01E1":"a","\u00E4":"a","\u01DF":"a","\u1EA3":"a","\u00E5":"a","\u01FB":"a","\u01CE":"a","\u0201":"a","\u0203":"a","\u1EA1":"a","\u1EAD":"a","\u1EB7":"a","\u1E01":"a","\u0105":"a","\u2C65":"a","\u0250":"a","\uA733":"aa","\u00E6":"ae","\u01FD":"ae","\u01E3":"ae","\uA735":"ao","\uA737":"au","\uA739":"av","\uA73B":"av","\uA73D":"ay","\u24D1":"b","\uFF42":"b","\u1E03":"b","\u1E05":"b","\u1E07":"b","\u0180":"b","\u0183":"b","\u0253":"b","\u24D2":"c","\uFF43":"c","\u0107":"c","\u0109":"c","\u010B":"c","\u010D":"c","\u00E7":"c","\u1E09":"c","\u0188":"c","\u023C":"c","\uA73F":"c","\u2184":"c","\u24D3":"d","\uFF44":"d","\u1E0B":"d","\u010F":"d","\u1E0D":"d","\u1E11":"d","\u1E13":"d","\u1E0F":"d","\u0111":"d","\u018C":"d","\u0256":"d","\u0257":"d","\uA77A":"d","\u01F3":"dz","\u01C6":"dz","\u24D4":"e","\uFF45":"e","\u00E8":"e","\u00E9":"e","\u00EA":"e","\u1EC1":"e","\u1EBF":"e","\u1EC5":"e","\u1EC3":"e","\u1EBD":"e","\u0113":"e","\u1E15":"e","\u1E17":"e","\u0115":"e","\u0117":"e","\u00EB":"e","\u1EBB":"e","\u011B":"e","\u0205":"e","\u0207":"e","\u1EB9":"e","\u1EC7":"e","\u0229":"e","\u1E1D":"e","\u0119":"e","\u1E19":"e","\u1E1B":"e","\u0247":"e","\u025B":"e","\u01DD":"e","\u24D5":"f","\uFF46":"f","\u1E1F":"f","\u0192":"f","\uA77C":"f","\u24D6":"g","\uFF47":"g","\u01F5":"g","\u011D":"g","\u1E21":"g","\u011F":"g","\u0121":"g","\u01E7":"g","\u0123":"g","\u01E5":"g","\u0260":"g","\uA7A1":"g","\u1D79":"g","\uA77F":"g","\u24D7":"h","\uFF48":"h","\u0125":"h","\u1E23":"h","\u1E27":"h","\u021F":"h","\u1E25":"h","\u1E29":"h","\u1E2B":"h","\u1E96":"h","\u0127":"h","\u2C68":"h","\u2C76":"h","\u0265":"h","\u0195":"hv","\u24D8":"i","\uFF49":"i","\u00EC":"i","\u00ED":"i","\u00EE":"i","\u0129":"i","\u012B":"i","\u012D":"i","\u00EF":"i","\u1E2F":"i","\u1EC9":"i","\u01D0":"i","\u0209":"i","\u020B":"i","\u1ECB":"i","\u012F":"i","\u1E2D":"i","\u0268":"i","\u0131":"i","\u24D9":"j","\uFF4A":"j","\u0135":"j","\u01F0":"j","\u0249":"j","\u24DA":"k","\uFF4B":"k","\u1E31":"k","\u01E9":"k","\u1E33":"k","\u0137":"k","\u1E35":"k","\u0199":"k","\u2C6A":"k","\uA741":"k","\uA743":"k","\uA745":"k","\uA7A3":"k","\u24DB":"l","\uFF4C":"l","\u0140":"l","\u013A":"l","\u013E":"l","\u1E37":"l","\u1E39":"l","\u013C":"l","\u1E3D":"l","\u1E3B":"l","\u017F":"l","\u0142":"l","\u019A":"l","\u026B":"l","\u2C61":"l","\uA749":"l","\uA781":"l","\uA747":"l","\u01C9":"lj","\u24DC":"m","\uFF4D":"m","\u1E3F":"m","\u1E41":"m","\u1E43":"m","\u0271":"m","\u026F":"m","\u24DD":"n","\uFF4E":"n","\u01F9":"n","\u0144":"n","\u00F1":"n","\u1E45":"n","\u0148":"n","\u1E47":"n","\u0146":"n","\u1E4B":"n","\u1E49":"n","\u019E":"n","\u0272":"n","\u0149":"n","\uA791":"n","\uA7A5":"n","\u01CC":"nj","\u24DE":"o","\uFF4F":"o","\u00F2":"o","\u00F3":"o","\u00F4":"o","\u1ED3":"o","\u1ED1":"o","\u1ED7":"o","\u1ED5":"o","\u00F5":"o","\u1E4D":"o","\u022D":"o","\u1E4F":"o","\u014D":"o","\u1E51":"o","\u1E53":"o","\u014F":"o","\u022F":"o","\u0231":"o","\u00F6":"o","\u022B":"o","\u1ECF":"o","\u0151":"o","\u01D2":"o","\u020D":"o","\u020F":"o","\u01A1":"o","\u1EDD":"o","\u1EDB":"o","\u1EE1":"o","\u1EDF":"o","\u1EE3":"o","\u1ECD":"o","\u1ED9":"o","\u01EB":"o","\u01ED":"o","\u00F8":"o","\u01FF":"o","\u0254":"o","\uA74B":"o","\uA74D":"o","\u0275":"o","\u01A3":"oi","\u0223":"ou","\uA74F":"oo","\u24DF":"p","\uFF50":"p","\u1E55":"p","\u1E57":"p","\u01A5":"p","\u1D7D":"p","\uA751":"p","\uA753":"p","\uA755":"p","\u24E0":"q","\uFF51":"q","\u024B":"q","\uA757":"q","\uA759":"q","\u24E1":"r","\uFF52":"r","\u0155":"r","\u1E59":"r","\u0159":"r","\u0211":"r","\u0213":"r","\u1E5B":"r","\u1E5D":"r","\u0157":"r","\u1E5F":"r","\u024D":"r","\u027D":"r","\uA75B":"r","\uA7A7":"r","\uA783":"r","\u24E2":"s","\uFF53":"s","\u00DF":"s","\u015B":"s","\u1E65":"s","\u015D":"s","\u1E61":"s","\u0161":"s","\u1E67":"s","\u1E63":"s","\u1E69":"s","\u0219":"s","\u015F":"s","\u023F":"s","\uA7A9":"s","\uA785":"s","\u1E9B":"s","\u24E3":"t","\uFF54":"t","\u1E6B":"t","\u1E97":"t","\u0165":"t","\u1E6D":"t","\u021B":"t","\u0163":"t","\u1E71":"t","\u1E6F":"t","\u0167":"t","\u01AD":"t","\u0288":"t","\u2C66":"t","\uA787":"t","\uA729":"tz","\u24E4":"u","\uFF55":"u","\u00F9":"u","\u00FA":"u","\u00FB":"u","\u0169":"u","\u1E79":"u","\u016B":"u","\u1E7B":"u","\u016D":"u","\u00FC":"u","\u01DC":"u","\u01D8":"u","\u01D6":"u","\u01DA":"u","\u1EE7":"u","\u016F":"u","\u0171":"u","\u01D4":"u","\u0215":"u","\u0217":"u","\u01B0":"u","\u1EEB":"u","\u1EE9":"u","\u1EEF":"u","\u1EED":"u","\u1EF1":"u","\u1EE5":"u","\u1E73":"u","\u0173":"u","\u1E77":"u","\u1E75":"u","\u0289":"u","\u24E5":"v","\uFF56":"v","\u1E7D":"v","\u1E7F":"v","\u028B":"v","\uA75F":"v","\u028C":"v","\uA761":"vy","\u24E6":"w","\uFF57":"w","\u1E81":"w","\u1E83":"w","\u0175":"w","\u1E87":"w","\u1E85":"w","\u1E98":"w","\u1E89":"w","\u2C73":"w","\u24E7":"x","\uFF58":"x","\u1E8B":"x","\u1E8D":"x","\u24E8":"y","\uFF59":"y","\u1EF3":"y","\u00FD":"y","\u0177":"y","\u1EF9":"y","\u0233":"y","\u1E8F":"y","\u00FF":"y","\u1EF7":"y","\u1E99":"y","\u1EF5":"y","\u01B4":"y","\u024F":"y","\u1EFF":"y","\u24E9":"z","\uFF5A":"z","\u017A":"z","\u1E91":"z","\u017C":"z","\u017E":"z","\u1E93":"z","\u1E95":"z","\u01B6":"z","\u0225":"z","\u0240":"z","\u2C6C":"z","\uA763":"z","\u0386":"\u0391","\u0388":"\u0395","\u0389":"\u0397","\u038A":"\u0399","\u03AA":"\u0399","\u038C":"\u039F","\u038E":"\u03A5","\u03AB":"\u03A5","\u038F":"\u03A9","\u03AC":"\u03B1","\u03AD":"\u03B5","\u03AE":"\u03B7","\u03AF":"\u03B9","\u03CA":"\u03B9","\u0390":"\u03B9","\u03CC":"\u03BF","\u03CD":"\u03C5","\u03CB":"\u03C5","\u03B0":"\u03C5","\u03C9":"\u03C9","\u03C2":"\u03C3"}; $document = $(document); nextUid=(function() { var counter=1; return function() { return counter++; }; }()); function reinsertElement(element) { var placeholder = $(document.createTextNode('')); element.before(placeholder); placeholder.before(element); placeholder.remove(); } function stripDiacritics(str) { // Used 'uni range + named function' from http://jsperf.com/diacritics/18 function match(a) { return DIACRITICS[a] || a; } return str.replace(/[^\u0000-\u007E]/g, match); } function indexOf(value, array) { var i = 0, l = array.length; for (; i < l; i = i + 1) { if (equal(value, array[i])) return i; } return -1; } function measureScrollbar () { var $template = $( MEASURE_SCROLLBAR_TEMPLATE ); $template.appendTo(document.body); var dim = { width: $template.width() - $template[0].clientWidth, height: $template.height() - $template[0].clientHeight }; $template.remove(); return dim; } /** * Compares equality of a and b * @param a * @param b */ function equal(a, b) { if (a === b) return true; if (a === undefined || b === undefined) return false; if (a === null || b === null) return false; // Check whether 'a' or 'b' is a string (primitive or object). // The concatenation of an empty string (+'') converts its argument to a string's primitive. if (a.constructor === String) return a+'' === b+''; // a+'' - in case 'a' is a String object if (b.constructor === String) return b+'' === a+''; // b+'' - in case 'b' is a String object return false; } /** * Splits the string into an array of values, transforming each value. An empty array is returned for nulls or empty * strings * @param string * @param separator */ function splitVal(string, separator, transform) { var val, i, l; if (string === null || string.length < 1) return []; val = string.split(separator); for (i = 0, l = val.length; i < l; i = i + 1) val[i] = transform(val[i]); return val; } function getSideBorderPadding(element) { return element.outerWidth(false) - element.width(); } function installKeyUpChangeEvent(element) { var key="keyup-change-value"; element.on("keydown", function () { if ($.data(element, key) === undefined) { $.data(element, key, element.val()); } }); element.on("keyup", function () { var val= $.data(element, key); if (val !== undefined && element.val() !== val) { $.removeData(element, key); element.trigger("keyup-change"); } }); } /** * filters mouse events so an event is fired only if the mouse moved. * * filters out mouse events that occur when mouse is stationary but * the elements under the pointer are scrolled. */ function installFilteredMouseMove(element) { element.on("mousemove", function (e) { var lastpos = lastMousePosition; if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) { $(e.target).trigger("mousemove-filtered", e); } }); } /** * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made * within the last quietMillis milliseconds. * * @param quietMillis number of milliseconds to wait before invoking fn * @param fn function to be debounced * @param ctx object to be used as this reference within fn * @return debounced version of fn */ function debounce(quietMillis, fn, ctx) { ctx = ctx || undefined; var timeout; return function () { var args = arguments; window.clearTimeout(timeout); timeout = window.setTimeout(function() { fn.apply(ctx, args); }, quietMillis); }; } function installDebouncedScroll(threshold, element) { var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);}); element.on("scroll", function (e) { if (indexOf(e.target, element.get()) >= 0) notify(e); }); } function focus($el) { if ($el[0] === document.activeElement) return; /* set the focus in a 0 timeout - that way the focus is set after the processing of the current event has finished - which seems like the only reliable way to set focus */ window.setTimeout(function() { var el=$el[0], pos=$el.val().length, range; $el.focus(); /* make sure el received focus so we do not error out when trying to manipulate the caret. sometimes modals or others listeners may steal it after its set */ var isVisible = (el.offsetWidth > 0 || el.offsetHeight > 0); if (isVisible && el === document.activeElement) { /* after the focus is set move the caret to the end, necessary when we val() just before setting focus */ if(el.setSelectionRange) { el.setSelectionRange(pos, pos); } else if (el.createTextRange) { range = el.createTextRange(); range.collapse(false); range.select(); } } }, 0); } function getCursorInfo(el) { el = $(el)[0]; var offset = 0; var length = 0; if ('selectionStart' in el) { offset = el.selectionStart; length = el.selectionEnd - offset; } else if ('selection' in document) { el.focus(); var sel = document.selection.createRange(); length = document.selection.createRange().text.length; sel.moveStart('character', -el.value.length); offset = sel.text.length - length; } return { offset: offset, length: length }; } function killEvent(event) { event.preventDefault(); event.stopPropagation(); } function killEventImmediately(event) { event.preventDefault(); event.stopImmediatePropagation(); } function measureTextWidth(e) { if (!sizer){ var style = e[0].currentStyle || window.getComputedStyle(e[0], null); sizer = $(document.createElement("div")).css({ position: "absolute", left: "-10000px", top: "-10000px", display: "none", fontSize: style.fontSize, fontFamily: style.fontFamily, fontStyle: style.fontStyle, fontWeight: style.fontWeight, letterSpacing: style.letterSpacing, textTransform: style.textTransform, whiteSpace: "nowrap" }); sizer.attr("class","select2-sizer"); $(document.body).append(sizer); } sizer.text(e.val()); return sizer.width(); } function syncCssClasses(dest, src, adapter) { var classes, replacements = [], adapted; classes = $.trim(dest.attr("class")); if (classes) { classes = '' + classes; // for IE which returns object $(classes.split(/\s+/)).each2(function() { if (this.indexOf("select2-") === 0) { replacements.push(this); } }); } classes = $.trim(src.attr("class")); if (classes) { classes = '' + classes; // for IE which returns object $(classes.split(/\s+/)).each2(function() { if (this.indexOf("select2-") !== 0) { adapted = adapter(this); if (adapted) { replacements.push(adapted); } } }); } dest.attr("class", replacements.join(" ")); } function markMatch(text, term, markup, escapeMarkup) { var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())), tl=term.length; if (match<0) { markup.push(escapeMarkup(text)); return; } markup.push(escapeMarkup(text.substring(0, match))); markup.push("<span class='select2-match'>"); markup.push(escapeMarkup(text.substring(match, match + tl))); markup.push("</span>"); markup.push(escapeMarkup(text.substring(match + tl, text.length))); } function defaultEscapeMarkup(markup) { var replace_map = { '\\': '&#92;', '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', "/": '&#47;' }; return String(markup).replace(/[&<>"'\/\\]/g, function (match) { return replace_map[match]; }); } /** * Produces an ajax-based query function * * @param options object containing configuration parameters * @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax * @param options.url url for the data * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url. * @param options.dataType request data type: ajax, jsonp, other datatypes supported by jQuery's $.ajax function or the transport function if specified * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often * @param options.results a function(remoteData, pageNumber, query) that converts data returned form the remote request to the format expected by Select2. * The expected format is an object containing the following keys: * results array of objects that will be used as choices * more (optional) boolean indicating whether there are more results available * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true} */ function ajax(options) { var timeout, // current scheduled but not yet executed request handler = null, quietMillis = options.quietMillis || 100, ajaxUrl = options.url, self = this; return function (query) { window.clearTimeout(timeout); timeout = window.setTimeout(function () { var data = options.data, // ajax data function url = ajaxUrl, // ajax url string or function transport = options.transport || $.fn.select2.ajaxDefaults.transport, // deprecated - to be removed in 4.0 - use params instead deprecated = { type: options.type || 'GET', // set type of request (GET or POST) cache: options.cache || false, jsonpCallback: options.jsonpCallback||undefined, dataType: options.dataType||"json" }, params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated); data = data ? data.call(self, query.term, query.page, query.context) : null; url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url; if (handler && typeof handler.abort === "function") { handler.abort(); } if (options.params) { if ($.isFunction(options.params)) { $.extend(params, options.params.call(self)); } else { $.extend(params, options.params); } } $.extend(params, { url: url, dataType: options.dataType, data: data, success: function (data) { // TODO - replace query.page with query so users have access to term, page, etc. // added query as third paramter to keep backwards compatibility var results = options.results(data, query.page, query); query.callback(results); }, error: function(jqXHR, textStatus, errorThrown){ var results = { hasError: true, jqXHR: jqXHR, textStatus: textStatus, errorThrown: errorThrown }; query.callback(results); } }); handler = transport.call(self, params); }, quietMillis); }; } /** * Produces a query function that works with a local array * * @param options object containing configuration parameters. The options parameter can either be an array or an * object. * * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys. * * If the object form is used it is assumed that it contains 'data' and 'text' keys. The 'data' key should contain * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text' * key can either be a String in which case it is expected that each element in the 'data' array has a key with the * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract * the text. */ function local(options) { var data = options, // data elements dataText, tmp, text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search if ($.isArray(data)) { tmp = data; data = { results: tmp }; } if ($.isFunction(data) === false) { tmp = data; data = function() { return tmp; }; } var dataItem = data(); if (dataItem.text) { text = dataItem.text; // if text is not a function we assume it to be a key name if (!$.isFunction(text)) { dataText = dataItem.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available text = function (item) { return item[dataText]; }; } } return function (query) { var t = query.term, filtered = { results: [] }, process; if (t === "") { query.callback(data()); return; } process = function(datum, collection) { var group, attr; datum = datum[0]; if (datum.children) { group = {}; for (attr in datum) { if (datum.hasOwnProperty(attr)) group[attr]=datum[attr]; } group.children=[]; $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); }); if (group.children.length || query.matcher(t, text(group), datum)) { collection.push(group); } } else { if (query.matcher(t, text(datum), datum)) { collection.push(datum); } } }; $(data().results).each2(function(i, datum) { process(datum, filtered.results); }); query.callback(filtered); }; } // TODO javadoc function tags(data) { var isFunc = $.isFunction(data); return function (query) { var t = query.term, filtered = {results: []}; var result = isFunc ? data(query) : data; if ($.isArray(result)) { $(result).each(function () { var isObject = this.text !== undefined, text = isObject ? this.text : this; if (t === "" || query.matcher(t, text)) { filtered.results.push(isObject ? this : {id: this, text: this}); } }); query.callback(filtered); } }; } /** * Checks if the formatter function should be used. * * Throws an error if it is not a function. Returns true if it should be used, * false if no formatting should be performed. * * @param formatter */ function checkFormatter(formatter, formatterName) { if ($.isFunction(formatter)) return true; if (!formatter) return false; if (typeof(formatter) === 'string') return true; throw new Error(formatterName +" must be a string, function, or falsy value"); } /** * Returns a given value * If given a function, returns its output * * @param val string|function * @param context value of "this" to be passed to function * @returns {*} */ function evaluate(val, context) { if ($.isFunction(val)) { var args = Array.prototype.slice.call(arguments, 2); return val.apply(context, args); } return val; } function countResults(results) { var count = 0; $.each(results, function(i, item) { if (item.children) { count += countResults(item.children); } else { count++; } }); return count; } /** * Default tokenizer. This function uses breaks the input on substring match of any string from the * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those * two options have to be defined in order for the tokenizer to work. * * @param input text user has typed so far or pasted into the search field * @param selection currently selected choices * @param selectCallback function(choice) callback tho add the choice to selection * @param opts select2's opts * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value */ function defaultTokenizer(input, selection, selectCallback, opts) { var original = input, // store the original so we can compare and know if we need to tell the search to update its text dupe = false, // check for whether a token we extracted represents a duplicate selected choice token, // token index, // position at which the separator was found i, l, // looping variables separator; // the matched separator if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined; while (true) { index = -1; for (i = 0, l = opts.tokenSeparators.length; i < l; i++) { separator = opts.tokenSeparators[i]; index = input.indexOf(separator); if (index >= 0) break; } if (index < 0) break; // did not find any token separator in the input string, bail token = input.substring(0, index); input = input.substring(index + separator.length); if (token.length > 0) { token = opts.createSearchChoice.call(this, token, selection); if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) { dupe = false; for (i = 0, l = selection.length; i < l; i++) { if (equal(opts.id(token), opts.id(selection[i]))) { dupe = true; break; } } if (!dupe) selectCallback(token); } } } if (original!==input) return input; } function cleanupJQueryElements() { var self = this; $.each(arguments, function (i, element) { self[element].remove(); self[element] = null; }); } /** * Creates a new class * * @param superClass * @param methods */ function clazz(SuperClass, methods) { var constructor = function () {}; constructor.prototype = new SuperClass; constructor.prototype.constructor = constructor; constructor.prototype.parent = SuperClass.prototype; constructor.prototype = $.extend(constructor.prototype, methods); return constructor; } AbstractSelect2 = clazz(Object, { // abstract bind: function (func) { var self = this; return function () { func.apply(self, arguments); }; }, // abstract init: function (opts) { var results, search, resultsSelector = ".select2-results"; // prepare options this.opts = opts = this.prepareOpts(opts); this.id=opts.id; // destroy if called on an existing component if (opts.element.data("select2") !== undefined && opts.element.data("select2") !== null) { opts.element.data("select2").destroy(); } this.container = this.createContainer(); this.liveRegion = $('.select2-hidden-accessible'); if (this.liveRegion.length == 0) { this.liveRegion = $("<span>", { role: "status", "aria-live": "polite" }) .addClass("select2-hidden-accessible") .appendTo(document.body); } this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid()); this.containerEventName= this.containerId .replace(/([.])/g, '_') .replace(/([;&,\-\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); this.container.attr("id", this.containerId); this.container.attr("title", opts.element.attr("title")); this.body = $(document.body); syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass); this.container.attr("style", opts.element.attr("style")); this.container.css(evaluate(opts.containerCss, this.opts.element)); this.container.addClass(evaluate(opts.containerCssClass, this.opts.element)); this.elementTabIndex = this.opts.element.attr("tabindex"); // swap container for the element this.opts.element .data("select2", this) .attr("tabindex", "-1") .before(this.container) .on("click.select2", killEvent); // do not leak click events this.container.data("select2", this); this.dropdown = this.container.find(".select2-drop"); syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass); this.dropdown.addClass(evaluate(opts.dropdownCssClass, this.opts.element)); this.dropdown.data("select2", this); this.dropdown.on("click", killEvent); this.results = results = this.container.find(resultsSelector); this.search = search = this.container.find("input.select2-input"); this.queryCount = 0; this.resultsPage = 0; this.context = null; // initialize the container this.initContainer(); this.container.on("click", killEvent); installFilteredMouseMove(this.results); this.dropdown.on("mousemove-filtered", resultsSelector, this.bind(this.highlightUnderEvent)); this.dropdown.on("touchstart touchmove touchend", resultsSelector, this.bind(function (event) { this._touchEvent = true; this.highlightUnderEvent(event); })); this.dropdown.on("touchmove", resultsSelector, this.bind(this.touchMoved)); this.dropdown.on("touchstart touchend", resultsSelector, this.bind(this.clearTouchMoved)); // Waiting for a click event on touch devices to select option and hide dropdown // otherwise click will be triggered on an underlying element this.dropdown.on('click', this.bind(function (event) { if (this._touchEvent) { this._touchEvent = false; this.selectHighlighted(); } })); installDebouncedScroll(80, this.results); this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded)); // do not propagate change event from the search field out of the component $(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();}); $(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();}); // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel if ($.fn.mousewheel) { results.mousewheel(function (e, delta, deltaX, deltaY) { var top = results.scrollTop(); if (deltaY > 0 && top - deltaY <= 0) { results.scrollTop(0); killEvent(e); } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) { results.scrollTop(results.get(0).scrollHeight - results.height()); killEvent(e); } }); } installKeyUpChangeEvent(search); search.on("keyup-change input paste", this.bind(this.updateResults)); search.on("focus", function () { search.addClass("select2-focused"); }); search.on("blur", function () { search.removeClass("select2-focused");}); this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) { if ($(e.target).closest(".select2-result-selectable").length > 0) { this.highlightUnderEvent(e); this.selectHighlighted(e); } })); // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's // dom it will trigger the popup close, which is not what we want // focusin can cause focus wars between modals and select2 since the dropdown is outside the modal. this.dropdown.on("click mouseup mousedown touchstart touchend focusin", function (e) { e.stopPropagation(); }); this.lastSearchTerm = undefined; if ($.isFunction(this.opts.initSelection)) { // initialize selection based on the current value of the source element this.initSelection(); // if the user has provided a function that can set selection based on the value of the source element // we monitor the change event on the element and trigger it, allowing for two way synchronization this.monitorSource(); } if (opts.maximumInputLength !== null) { this.search.attr("maxlength", opts.maximumInputLength); } var disabled = opts.element.prop("disabled"); if (disabled === undefined) disabled = false; this.enable(!disabled); var readonly = opts.element.prop("readonly"); if (readonly === undefined) readonly = false; this.readonly(readonly); // Calculate size of scrollbar scrollBarDimensions = scrollBarDimensions || measureScrollbar(); this.autofocus = opts.element.prop("autofocus"); opts.element.prop("autofocus", false); if (this.autofocus) this.focus(); this.search.attr("placeholder", opts.searchInputPlaceholder); }, // abstract destroy: function () { var element=this.opts.element, select2 = element.data("select2"), self = this; this.close(); if (element.length && element[0].detachEvent && self._sync) { element.each(function () { if (self._sync) { this.detachEvent("onpropertychange", self._sync); } }); } if (this.propertyObserver) { this.propertyObserver.disconnect(); this.propertyObserver = null; } this._sync = null; if (select2 !== undefined) { select2.container.remove(); select2.liveRegion.remove(); select2.dropdown.remove(); element.removeData("select2") .off(".select2"); if (!element.is("input[type='hidden']")) { element .show() .prop("autofocus", this.autofocus || false); if (this.elementTabIndex) { element.attr({tabindex: this.elementTabIndex}); } else { element.removeAttr("tabindex"); } element.show(); } else { element.css("display", ""); } } cleanupJQueryElements.call(this, "container", "liveRegion", "dropdown", "results", "search" ); }, // abstract optionToData: function(element) { if (element.is("option")) { return { id:element.prop("value"), text:element.text(), element: element.get(), css: element.attr("class"), disabled: element.prop("disabled"), locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true) }; } else if (element.is("optgroup")) { return { text:element.attr("label"), children:[], element: element.get(), css: element.attr("class") }; } }, // abstract prepareOpts: function (opts) { var element, select, idKey, ajaxUrl, self = this; element = opts.element; if (element.get(0).tagName.toLowerCase() === "select") { this.select = select = opts.element; } if (select) { // these options are not allowed when attached to a select because they are picked up off the element itself $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () { if (this in opts) { throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element."); } }); } opts.debug = opts.debug || $.fn.select2.defaults.debug; // Warnings for options renamed/removed in Select2 4.0.0 // Only when it's enabled through debug mode if (opts.debug && console && console.warn) { // id was removed if (opts.id != null) { console.warn( 'Select2: The `id` option has been removed in Select2 4.0.0, ' + 'consider renaming your `id` property or mapping the property before your data makes it to Select2. ' + 'You can read more at https://select2.github.io/announcements-4.0.html#changed-id' ); } // text was removed if (opts.text != null) { console.warn( 'Select2: The `text` option has been removed in Select2 4.0.0, ' + 'consider renaming your `text` property or mapping the property before your data makes it to Select2. ' + 'You can read more at https://select2.github.io/announcements-4.0.html#changed-id' ); } // sortResults was renamed to results if (opts.sortResults != null) { console.warn( 'Select2: the `sortResults` option has been renamed to `sorter` in Select2 4.0.0. ' ); } // selectOnBlur was renamed to selectOnClose if (opts.selectOnBlur != null) { console.warn( 'Select2: The `selectOnBlur` option has been renamed to `selectOnClose` in Select2 4.0.0.' ); } // ajax.results was renamed to ajax.processResults if (opts.ajax != null && opts.ajax.results != null) { console.warn( 'Select2: The `ajax.results` option has been renamed to `ajax.processResults` in Select2 4.0.0.' ); } // format* options were renamed to language.* if (opts.formatNoResults != null) { console.warn( 'Select2: The `formatNoResults` option has been renamed to `language.noResults` in Select2 4.0.0.' ); } if (opts.formatSearching != null) { console.warn( 'Select2: The `formatSearching` option has been renamed to `language.searching` in Select2 4.0.0.' ); } if (opts.formatInputTooShort != null) { console.warn( 'Select2: The `formatInputTooShort` option has been renamed to `language.inputTooShort` in Select2 4.0.0.' ); } if (opts.formatInputTooLong != null) { console.warn( 'Select2: The `formatInputTooLong` option has been renamed to `language.inputTooLong` in Select2 4.0.0.' ); } if (opts.formatLoading != null) { console.warn( 'Select2: The `formatLoading` option has been renamed to `language.loadingMore` in Select2 4.0.0.' ); } if (opts.formatSelectionTooBig != null) { console.warn( 'Select2: The `formatSelectionTooBig` option has been renamed to `language.maximumSelected` in Select2 4.0.0.' ); } if (opts.element.data('select2Tags')) { console.warn( 'Select2: The `data-select2-tags` attribute has been renamed to `data-tags` in Select2 4.0.0.' ); } } // Aliasing options renamed in Select2 4.0.0 // data-select2-tags -> data-tags if (opts.element.data('tags') != null) { var elemTags = opts.element.data('tags'); // data-tags should actually be a boolean if (!$.isArray(elemTags)) { elemTags = []; } opts.element.data('select2Tags', elemTags); } // sortResults -> sorter if (opts.sorter != null) { opts.sortResults = opts.sorter; } // selectOnBlur -> selectOnClose if (opts.selectOnClose != null) { opts.selectOnBlur = opts.selectOnClose; } // ajax.results -> ajax.processResults if (opts.ajax != null) { if ($.isFunction(opts.ajax.processResults)) { opts.ajax.results = opts.ajax.processResults; } } // Formatters/language options if (opts.language != null) { var lang = opts.language; // formatNoMatches -> language.noMatches if ($.isFunction(lang.noMatches)) { opts.formatNoMatches = lang.noMatches; } // formatSearching -> language.searching if ($.isFunction(lang.searching)) { opts.formatSearching = lang.searching; } // formatInputTooShort -> language.inputTooShort if ($.isFunction(lang.inputTooShort)) { opts.formatInputTooShort = lang.inputTooShort; } // formatInputTooLong -> language.inputTooLong if ($.isFunction(lang.inputTooLong)) { opts.formatInputTooLong = lang.inputTooLong; } // formatLoading -> language.loadingMore if ($.isFunction(lang.loadingMore)) { opts.formatLoading = lang.loadingMore; } // formatSelectionTooBig -> language.maximumSelected if ($.isFunction(lang.maximumSelected)) { opts.formatSelectionTooBig = lang.maximumSelected; } } opts = $.extend({}, { populateResults: function(container, results, query) { var populate, id=this.opts.id, liveRegion=this.liveRegion; populate=function(results, container, depth) { var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted; results = opts.sortResults(results, container, query); // collect the created nodes for bulk append var nodes = []; for (i = 0, l = results.length; i < l; i = i + 1) { result=results[i]; disabled = (result.disabled === true); selectable = (!disabled) && (id(result) !== undefined); compound=result.children && result.children.length > 0; node=$("<li></li>"); node.addClass("select2-results-dept-"+depth); node.addClass("select2-result"); node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable"); if (disabled) { node.addClass("select2-disabled"); } if (compound) { node.addClass("select2-result-with-children"); } node.addClass(self.opts.formatResultCssClass(result)); node.attr("role", "presentation"); label=$(document.createElement("div")); label.addClass("select2-result-label"); label.attr("id", "select2-result-label-" + nextUid()); label.attr("role", "option"); formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup); if (formatted!==undefined) { label.html(formatted); node.append(label); } if (compound) { innerContainer=$("<ul></ul>"); innerContainer.addClass("select2-result-sub"); populate(result.children, innerContainer, depth+1); node.append(innerContainer); } node.data("select2-data", result); nodes.push(node[0]); } // bulk append the created nodes container.append(nodes); liveRegion.text(opts.formatMatches(results.length)); }; populate(results, container, 0); } }, $.fn.select2.defaults, opts); if (typeof(opts.id) !== "function") { idKey = opts.id; opts.id = function (e) { return e[idKey]; }; } if ($.isArray(opts.element.data("select2Tags"))) { if ("tags" in opts) { throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id"); } opts.tags=opts.element.data("select2Tags"); } if (select) { opts.query = this.bind(function (query) { var data = { results: [], more: false }, term = query.term, children, placeholderOption, process; process=function(element, collection) { var group; if (element.is("option")) { if (query.matcher(term, element.text(), element)) { collection.push(self.optionToData(element)); } } else if (element.is("optgroup")) { group=self.optionToData(element); element.children().each2(function(i, elm) { process(elm, group.children); }); if (group.children.length>0) { collection.push(group); } } }; children=element.children(); // ignore the placeholder option if there is one if (this.getPlaceholder() !== undefined && children.length > 0) { placeholderOption = this.getPlaceholderOption(); if (placeholderOption) { children=children.not(placeholderOption); } } children.each2(function(i, elm) { process(elm, data.results); }); query.callback(data); }); // this is needed because inside val() we construct choices from options and their id is hardcoded opts.id=function(e) { return e.id; }; } else { if (!("query" in opts)) { if ("ajax" in opts) { ajaxUrl = opts.element.data("ajax-url"); if (ajaxUrl && ajaxUrl.length > 0) { opts.ajax.url = ajaxUrl; } opts.query = ajax.call(opts.element, opts.ajax); } else if ("data" in opts) { opts.query = local(opts.data); } else if ("tags" in opts) { opts.query = tags(opts.tags); if (opts.createSearchChoice === undefined) { opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; }; } if (opts.initSelection === undefined) { opts.initSelection = function (element, callback) { var data = []; $(splitVal(element.val(), opts.separator, opts.transformVal)).each(function () { var obj = { id: this, text: this }, tags = opts.tags; if ($.isFunction(tags)) tags=tags(); $(tags).each(function() { if (equal(this.id, obj.id)) { obj = this; return false; } }); data.push(obj); }); callback(data); }; } } } } if (typeof(opts.query) !== "function") { throw "query function not defined for Select2 " + opts.element.attr("id"); } if (opts.createSearchChoicePosition === 'top') { opts.createSearchChoicePosition = function(list, item) { list.unshift(item); }; } else if (opts.createSearchChoicePosition === 'bottom') { opts.createSearchChoicePosition = function(list, item) { list.push(item); }; } else if (typeof(opts.createSearchChoicePosition) !== "function") { throw "invalid createSearchChoicePosition option must be 'top', 'bottom' or a custom function"; } return opts; }, /** * Monitor the original element for changes and update select2 accordingly */ // abstract monitorSource: function () { var el = this.opts.element, observer, self = this; el.on("change.select2", this.bind(function (e) { if (this.opts.element.data("select2-change-triggered") !== true) { this.initSelection(); } })); this._sync = this.bind(function () { // sync enabled state var disabled = el.prop("disabled"); if (disabled === undefined) disabled = false; this.enable(!disabled); var readonly = el.prop("readonly"); if (readonly === undefined) readonly = false; this.readonly(readonly); if (this.container) { syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass); this.container.addClass(evaluate(this.opts.containerCssClass, this.opts.element)); } if (this.dropdown) { syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass); this.dropdown.addClass(evaluate(this.opts.dropdownCssClass, this.opts.element)); } }); // IE8-10 (IE9/10 won't fire propertyChange via attachEventListener) if (el.length && el[0].attachEvent) { el.each(function() { this.attachEvent("onpropertychange", self._sync); }); } // safari, chrome, firefox, IE11 observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver; if (observer !== undefined) { if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; } this.propertyObserver = new observer(function (mutations) { $.each(mutations, self._sync); }); this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false }); } }, // abstract triggerSelect: function(data) { var evt = $.Event("select2-selecting", { val: this.id(data), object: data, choice: data }); this.opts.element.trigger(evt); return !evt.isDefaultPrevented(); }, /** * Triggers the change event on the source element */ // abstract triggerChange: function (details) { details = details || {}; details= $.extend({}, details, { type: "change", val: this.val() }); // prevents recursive triggering this.opts.element.data("select2-change-triggered", true); this.opts.element.trigger(details); this.opts.element.data("select2-change-triggered", false); // some validation frameworks ignore the change event and listen instead to keyup, click for selects // so here we trigger the click event manually this.opts.element.click(); // ValidationEngine ignores the change event and listens instead to blur // so here we trigger the blur event manually if so desired if (this.opts.blurOnChange) this.opts.element.blur(); }, //abstract isInterfaceEnabled: function() { return this.enabledInterface === true; }, // abstract enableInterface: function() { var enabled = this._enabled && !this._readonly, disabled = !enabled; if (enabled === this.enabledInterface) return false; this.container.toggleClass("select2-container-disabled", disabled); this.close(); this.enabledInterface = enabled; return true; }, // abstract enable: function(enabled) { if (enabled === undefined) enabled = true; if (this._enabled === enabled) return; this._enabled = enabled; this.opts.element.prop("disabled", !enabled); this.enableInterface(); }, // abstract disable: function() { this.enable(false); }, // abstract readonly: function(enabled) { if (enabled === undefined) enabled = false; if (this._readonly === enabled) return; this._readonly = enabled; this.opts.element.prop("readonly", enabled); this.enableInterface(); }, // abstract opened: function () { return (this.container) ? this.container.hasClass("select2-dropdown-open") : false; }, // abstract positionDropdown: function() { var $dropdown = this.dropdown, container = this.container, offset = container.offset(), height = container.outerHeight(false), width = container.outerWidth(false), dropHeight = $dropdown.outerHeight(false), $window = $(window), windowWidth = $window.width(), windowHeight = $window.height(), viewPortRight = $window.scrollLeft() + windowWidth, viewportBottom = $window.scrollTop() + windowHeight, dropTop = offset.top + height, dropLeft = offset.left, enoughRoomBelow = dropTop + dropHeight <= viewportBottom, enoughRoomAbove = (offset.top - dropHeight) >= $window.scrollTop(), dropWidth = $dropdown.outerWidth(false), enoughRoomOnRight = function() { return dropLeft + dropWidth <= viewPortRight; }, enoughRoomOnLeft = function() { return offset.left + viewPortRight + container.outerWidth(false) > dropWidth; }, aboveNow = $dropdown.hasClass("select2-drop-above"), bodyOffset, above, changeDirection, css, resultsListNode; // always prefer the current above/below alignment, unless there is not enough room if (aboveNow) { above = true; if (!enoughRoomAbove && enoughRoomBelow) { changeDirection = true; above = false; } } else { above = false; if (!enoughRoomBelow && enoughRoomAbove) { changeDirection = true; above = true; } } //if we are changing direction we need to get positions when dropdown is hidden; if (changeDirection) { $dropdown.hide(); offset = this.container.offset(); height = this.container.outerHeight(false); width = this.container.outerWidth(false); dropHeight = $dropdown.outerHeight(false); viewPortRight = $window.scrollLeft() + windowWidth; viewportBottom = $window.scrollTop() + windowHeight; dropTop = offset.top + height; dropLeft = offset.left; dropWidth = $dropdown.outerWidth(false); $dropdown.show(); // fix so the cursor does not move to the left within the search-textbox in IE this.focusSearch(); } if (this.opts.dropdownAutoWidth) { resultsListNode = $('.select2-results', $dropdown)[0]; $dropdown.addClass('select2-drop-auto-width'); $dropdown.css('width', ''); // Add scrollbar width to dropdown if vertical scrollbar is present dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width); dropWidth > width ? width = dropWidth : dropWidth = width; dropHeight = $dropdown.outerHeight(false); } else { this.container.removeClass('select2-drop-auto-width'); } //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow); //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body.scrollTop(), "enough?", enoughRoomAbove); // fix positioning when body has an offset and is not position: static if (this.body.css('position') !== 'static') { bodyOffset = this.body.offset(); dropTop -= bodyOffset.top; dropLeft -= bodyOffset.left; } if (!enoughRoomOnRight() && enoughRoomOnLeft()) { dropLeft = offset.left + this.container.outerWidth(false) - dropWidth; } css = { left: dropLeft, width: width }; if (above) { this.container.addClass("select2-drop-above"); $dropdown.addClass("select2-drop-above"); dropHeight = $dropdown.outerHeight(false); css.top = offset.top - dropHeight; css.bottom = 'auto'; } else { css.top = dropTop; css.bottom = 'auto'; this.container.removeClass("select2-drop-above"); $dropdown.removeClass("select2-drop-above"); } css = $.extend(css, evaluate(this.opts.dropdownCss, this.opts.element)); $dropdown.css(css); }, // abstract shouldOpen: function() { var event; if (this.opened()) return false; if (this._enabled === false || this._readonly === true) return false; event = $.Event("select2-opening"); this.opts.element.trigger(event); return !event.isDefaultPrevented(); }, // abstract clearDropdownAlignmentPreference: function() { // clear the classes used to figure out the preference of where the dropdown should be opened this.container.removeClass("select2-drop-above"); this.dropdown.removeClass("select2-drop-above"); }, /** * Opens the dropdown * * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example, * the dropdown is already open, or if the 'open' event listener on the element called preventDefault(). */ // abstract open: function () { if (!this.shouldOpen()) return false; this.opening(); // Only bind the document mousemove when the dropdown is visible $document.on("mousemove.select2Event", function (e) { lastMousePosition.x = e.pageX; lastMousePosition.y = e.pageY; }); return true; }, /** * Performs the opening of the dropdown */ // abstract opening: function() { var cid = this.containerEventName, scroll = "scroll." + cid, resize = "resize."+cid, orient = "orientationchange."+cid, mask; this.container.addClass("select2-dropdown-open").addClass("select2-container-active"); this.clearDropdownAlignmentPreference(); if(this.dropdown[0] !== this.body.children().last()[0]) { this.dropdown.detach().appendTo(this.body); } // create the dropdown mask if doesn't already exist mask = $("#select2-drop-mask"); if (mask.length === 0) { mask = $(document.createElement("div")); mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask"); mask.hide(); mask.appendTo(this.body); mask.on("mousedown touchstart click", function (e) { // Prevent IE from generating a click event on the body reinsertElement(mask); var dropdown = $("#select2-drop"), self; if (dropdown.length > 0) { self=dropdown.data("select2"); if (self.opts.selectOnBlur) { self.selectHighlighted({noFocus: true}); } self.close(); e.preventDefault(); e.stopPropagation(); } }); } // ensure the mask is always right before the dropdown if (this.dropdown.prev()[0] !== mask[0]) { this.dropdown.before(mask); } // move the global id to the correct dropdown $("#select2-drop").removeAttr("id"); this.dropdown.attr("id", "select2-drop"); // show the elements mask.show(); this.positionDropdown(); this.dropdown.show(); this.positionDropdown(); this.dropdown.addClass("select2-drop-active"); // attach listeners to events that can change the position of the container and thus require // the position of the dropdown to be updated as well so it does not come unglued from the container var that = this; this.container.parents().add(window).each(function () { $(this).on(resize+" "+scroll+" "+orient, function (e) { if (that.opened()) that.positionDropdown(); }); }); }, // abstract close: function () { if (!this.opened()) return; var cid = this.containerEventName, scroll = "scroll." + cid, resize = "resize."+cid, orient = "orientationchange."+cid; // unbind event listeners this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); }); this.clearDropdownAlignmentPreference(); $("#select2-drop-mask").hide(); this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id this.dropdown.hide(); this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active"); this.results.empty(); // Now that the dropdown is closed, unbind the global document mousemove event $document.off("mousemove.select2Event"); this.clearSearch(); this.search.removeClass("select2-active"); // Remove the aria active descendant for highlighted element this.search.removeAttr("aria-activedescendant"); this.opts.element.trigger($.Event("select2-close")); }, /** * Opens control, sets input value, and updates results. */ // abstract externalSearch: function (term) { this.open(); this.search.val(term); this.updateResults(false); }, // abstract clearSearch: function () { }, /** * @return {Boolean} Whether or not search value was changed. * @private */ prefillNextSearchTerm: function () { // initializes search's value with nextSearchTerm (if defined by user) // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter if(this.search.val() !== "") { return false; } var nextSearchTerm = this.opts.nextSearchTerm(this.data(), this.lastSearchTerm); if(nextSearchTerm !== undefined){ this.search.val(nextSearchTerm); this.search.select(); return true; } return false; }, //abstract getMaximumSelectionSize: function() { return evaluate(this.opts.maximumSelectionSize, this.opts.element); }, // abstract ensureHighlightVisible: function () { var results = this.results, children, index, child, hb, rb, y, more, topOffset; index = this.highlight(); if (index < 0) return; if (index == 0) { // if the first element is highlighted scroll all the way to the top, // that way any unselectable headers above it will also be scrolled // into view results.scrollTop(0); return; } children = this.findHighlightableChoices().find('.select2-result-label'); child = $(children[index]); topOffset = (child.offset() || {}).top || 0; hb = topOffset + child.outerHeight(true); // if this is the last child lets also make sure select2-more-results is visible if (index === children.length - 1) { more = results.find("li.select2-more-results"); if (more.length > 0) { hb = more.offset().top + more.outerHeight(true); } } rb = results.offset().top + results.outerHeight(false); if (hb > rb) { results.scrollTop(results.scrollTop() + (hb - rb)); } y = topOffset - results.offset().top; // make sure the top of the element is visible if (y < 0 && child.css('display') != 'none' ) { results.scrollTop(results.scrollTop() + y); // y is negative } }, // abstract findHighlightableChoices: function() { return this.results.find(".select2-result-selectable:not(.select2-disabled):not(.select2-selected)"); }, // abstract moveHighlight: function (delta) { var choices = this.findHighlightableChoices(), index = this.highlight(); while (index > -1 && index < choices.length) { index += delta; var choice = $(choices[index]); if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) { this.highlight(index); break; } } }, // abstract highlight: function (index) { var choices = this.findHighlightableChoices(), choice, data; if (arguments.length === 0) { return indexOf(choices.filter(".select2-highlighted")[0], choices.get()); } if (index >= choices.length) index = choices.length - 1; if (index < 0) index = 0; this.removeHighlight(); choice = $(choices[index]); choice.addClass("select2-highlighted"); // ensure assistive technology can determine the active choice this.search.attr("aria-activedescendant", choice.find(".select2-result-label").attr("id")); this.ensureHighlightVisible(); this.liveRegion.text(choice.text()); data = choice.data("select2-data"); if (data) { this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data }); } }, removeHighlight: function() { this.results.find(".select2-highlighted").removeClass("select2-highlighted"); }, touchMoved: function() { this._touchMoved = true; }, clearTouchMoved: function() { this._touchMoved = false; }, // abstract countSelectableResults: function() { return this.findHighlightableChoices().length; }, // abstract highlightUnderEvent: function (event) { var el = $(event.target).closest(".select2-result-selectable"); if (el.length > 0 && !el.is(".select2-highlighted")) { var choices = this.findHighlightableChoices(); this.highlight(choices.index(el)); } else if (el.length == 0) { // if we are over an unselectable item remove all highlights this.removeHighlight(); } }, // abstract loadMoreIfNeeded: function () { var results = this.results, more = results.find("li.select2-more-results"), below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible page = this.resultsPage + 1, self=this, term=this.search.val(), context=this.context; if (more.length === 0) return; below = more.offset().top - results.offset().top - results.height(); if (below <= this.opts.loadMorePadding) { more.addClass("select2-active"); this.opts.query({ element: this.opts.element, term: term, page: page, context: context, matcher: this.opts.matcher, callback: this.bind(function (data) { // ignore a response if the select2 has been closed before it was received if (!self.opened()) return; self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context}); self.postprocessResults(data, false, false); if (data.more===true) { more.detach().appendTo(results).html(self.opts.escapeMarkup(evaluate(self.opts.formatLoadMore, self.opts.element, page+1))); window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10); } else { more.remove(); } self.positionDropdown(); self.resultsPage = page; self.context = data.context; this.opts.element.trigger({ type: "select2-loaded", items: data }); })}); } }, /** * Default tokenizer function which does nothing */ tokenize: function() { }, /** * @param initial whether or not this is the call to this method right after the dropdown has been opened */ // abstract updateResults: function (initial) { var search = this.search, results = this.results, opts = this.opts, data, self = this, input, term = search.val(), lastTerm = $.data(this.container, "select2-last-term"), // sequence number used to drop out-of-order responses queryNumber; // prevent duplicate queries against the same term if (initial !== true && lastTerm && equal(term, lastTerm)) return; $.data(this.container, "select2-last-term", term); // if the search is currently hidden we do not alter the results if (initial !== true && (this.showSearchInput === false || !this.opened())) { return; } function postRender() { search.removeClass("select2-active"); self.positionDropdown(); if (results.find('.select2-no-results,.select2-selection-limit,.select2-searching').length) { self.liveRegion.text(results.text()); } else { self.liveRegion.text(self.opts.formatMatches(results.find('.select2-result-selectable:not(".select2-selected")').length)); } } function render(html) { results.html(html); postRender(); } queryNumber = ++this.queryCount; var maxSelSize = this.getMaximumSelectionSize(); if (maxSelSize >=1) { data = this.data(); if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) { render("<li class='select2-selection-limit'>" + evaluate(opts.formatSelectionTooBig, opts.element, maxSelSize) + "</li>"); return; } } if (search.val().length < opts.minimumInputLength) { if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) { render("<li class='select2-no-results'>" + evaluate(opts.formatInputTooShort, opts.element, search.val(), opts.minimumInputLength) + "</li>"); } else { render(""); } if (initial && this.showSearch) this.showSearch(true); return; } if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) { if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) { render("<li class='select2-no-results'>" + evaluate(opts.formatInputTooLong, opts.element, search.val(), opts.maximumInputLength) + "</li>"); } else { render(""); } return; } if (opts.formatSearching && this.findHighlightableChoices().length === 0) { render("<li class='select2-searching'>" + evaluate(opts.formatSearching, opts.element) + "</li>"); } search.addClass("select2-active"); this.removeHighlight(); // give the tokenizer a chance to pre-process the input input = this.tokenize(); if (input != undefined && input != null) { search.val(input); } this.resultsPage = 1; opts.query({ element: opts.element, term: search.val(), page: this.resultsPage, context: null, matcher: opts.matcher, callback: this.bind(function (data) { var def; // default choice // ignore old responses if (queryNumber != this.queryCount) { return; } // ignore a response if the select2 has been closed before it was received if (!this.opened()) { this.search.removeClass("select2-active"); return; } // handle ajax error if(data.hasError !== undefined && checkFormatter(opts.formatAjaxError, "formatAjaxError")) { render("<li class='select2-ajax-error'>" + evaluate(opts.formatAjaxError, opts.element, data.jqXHR, data.textStatus, data.errorThrown) + "</li>"); return; } // save context, if any this.context = (data.context===undefined) ? null : data.context; // create a default choice and prepend it to the list if (this.opts.createSearchChoice && search.val() !== "") { def = this.opts.createSearchChoice.call(self, search.val(), data.results); if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) { if ($(data.results).filter( function () { return equal(self.id(this), self.id(def)); }).length === 0) { this.opts.createSearchChoicePosition(data.results, def); } } } if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) { render("<li class='select2-no-results'>" + evaluate(opts.formatNoMatches, opts.element, search.val()) + "</li>"); if(this.showSearch){ this.showSearch(search.val()); } return; } results.empty(); self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null}); if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) { results.append("<li class='select2-more-results'>" + opts.escapeMarkup(evaluate(opts.formatLoadMore, opts.element, this.resultsPage)) + "</li>"); window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10); } this.postprocessResults(data, initial); postRender(); this.opts.element.trigger({ type: "select2-loaded", items: data }); })}); }, // abstract cancel: function () { this.close(); }, // abstract blur: function () { // if selectOnBlur == true, select the currently highlighted option if (this.opts.selectOnBlur) this.selectHighlighted({noFocus: true}); this.close(); this.container.removeClass("select2-container-active"); // synonymous to .is(':focus'), which is available in jquery >= 1.6 if (this.search[0] === document.activeElement) { this.search.blur(); } this.clearSearch(); this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"); }, // abstract focusSearch: function () { focus(this.search); }, // abstract selectHighlighted: function (options) { if (this._touchMoved) { this.clearTouchMoved(); return; } var index=this.highlight(), highlighted=this.results.find(".select2-highlighted"), data = highlighted.closest('.select2-result').data("select2-data"); if (data) { this.highlight(index); this.onSelect(data, options); } else if (options && options.noFocus) { this.close(); } }, // abstract getPlaceholder: function () { var placeholderOption; return this.opts.element.attr("placeholder") || this.opts.element.attr("data-placeholder") || // jquery 1.4 compat this.opts.element.data("placeholder") || this.opts.placeholder || ((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined); }, // abstract getPlaceholderOption: function() { if (this.select) { var firstOption = this.select.children('option').first(); if (this.opts.placeholderOption !== undefined ) { //Determine the placeholder option based on the specified placeholderOption setting return (this.opts.placeholderOption === "first" && firstOption) || (typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select)); } else if ($.trim(firstOption.text()) === "" && firstOption.val() === "") { //No explicit placeholder option specified, use the first if it's blank return firstOption; } } }, /** * Get the desired width for the container element. This is * derived first from option `width` passed to select2, then * the inline 'style' on the original element, and finally * falls back to the jQuery calculated element width. */ // abstract initContainerWidth: function () { function resolveContainerWidth() { var style, attrs, matches, i, l, attr; if (this.opts.width === "off") { return null; } else if (this.opts.width === "element"){ return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px'; } else if (this.opts.width === "copy" || this.opts.width === "resolve") { // check if there is inline style on the element that contains width style = this.opts.element.attr('style'); if (typeof(style) === "string") { attrs = style.split(';'); for (i = 0, l = attrs.length; i < l; i = i + 1) { attr = attrs[i].replace(/\s/g, ''); matches = attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i); if (matches !== null && matches.length >= 1) return matches[1]; } } if (this.opts.width === "resolve") { // next check if css('width') can resolve a width that is percent based, this is sometimes possible // when attached to input type=hidden or elements hidden via css style = this.opts.element.css('width'); if (style.indexOf("%") > 0) return style; // finally, fallback on the calculated width of the element return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px'); } return null; } else if ($.isFunction(this.opts.width)) { return this.opts.width(); } else { return this.opts.width; } }; var width = resolveContainerWidth.call(this); if (width !== null) { this.container.css("width", width); } } }); SingleSelect2 = clazz(AbstractSelect2, { // single createContainer: function () { var container = $(document.createElement("div")).attr({ "class": "select2-container" }).html([ "<a href='javascript:void(0)' class='select2-choice' tabindex='-1'>", " <span class='select2-chosen'>&#160;</span><abbr class='select2-search-choice-close'></abbr>", " <span class='select2-arrow' role='presentation'><b role='presentation'></b></span>", "</a>", "<label for='' class='select2-offscreen'></label>", "<input class='select2-focusser select2-offscreen' type='text' aria-haspopup='true' role='button' />", "<div class='select2-drop select2-display-none'>", " <div class='select2-search'>", " <label for='' class='select2-offscreen'></label>", " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input' role='combobox' aria-expanded='true'", " aria-autocomplete='list' />", " </div>", " <ul class='select2-results' role='listbox'>", " </ul>", "</div>"].join("")); return container; }, // single enableInterface: function() { if (this.parent.enableInterface.apply(this, arguments)) { this.focusser.prop("disabled", !this.isInterfaceEnabled()); } }, // single opening: function () { var el, range, len; if (this.opts.minimumResultsForSearch >= 0) { this.showSearch(true); } this.parent.opening.apply(this, arguments); if (this.showSearchInput !== false) { // IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range // all other browsers handle this just fine this.search.val(this.focusser.val()); } if (this.opts.shouldFocusInput(this)) { this.search.focus(); // move the cursor to the end after focussing, otherwise it will be at the beginning and // new text will appear *before* focusser.val() el = this.search.get(0); if (el.createTextRange) { range = el.createTextRange(); range.collapse(false); range.select(); } else if (el.setSelectionRange) { len = this.search.val().length; el.setSelectionRange(len, len); } } this.prefillNextSearchTerm(); this.focusser.prop("disabled", true).val(""); this.updateResults(true); this.opts.element.trigger($.Event("select2-open")); }, // single close: function () { if (!this.opened()) return; this.parent.close.apply(this, arguments); this.focusser.prop("disabled", false); if (this.opts.shouldFocusInput(this)) { this.focusser.focus(); } }, // single focus: function () { if (this.opened()) { this.close(); } else { this.focusser.prop("disabled", false); if (this.opts.shouldFocusInput(this)) { this.focusser.focus(); } } }, // single isFocused: function () { return this.container.hasClass("select2-container-active"); }, // single cancel: function () { this.parent.cancel.apply(this, arguments); this.focusser.prop("disabled", false); if (this.opts.shouldFocusInput(this)) { this.focusser.focus(); } }, // single destroy: function() { $("label[for='" + this.focusser.attr('id') + "']") .attr('for', this.opts.element.attr("id")); this.parent.destroy.apply(this, arguments); cleanupJQueryElements.call(this, "selection", "focusser" ); }, // single initContainer: function () { var selection, container = this.container, dropdown = this.dropdown, idSuffix = nextUid(), elementLabel; if (this.opts.minimumResultsForSearch < 0) { this.showSearch(false); } else { this.showSearch(true); } this.selection = selection = container.find(".select2-choice"); this.focusser = container.find(".select2-focusser"); // add aria associations selection.find(".select2-chosen").attr("id", "select2-chosen-"+idSuffix); this.focusser.attr("aria-labelledby", "select2-chosen-"+idSuffix); this.results.attr("id", "select2-results-"+idSuffix); this.search.attr("aria-owns", "select2-results-"+idSuffix); // rewrite labels from original element to focusser this.focusser.attr("id", "s2id_autogen"+idSuffix); elementLabel = $("label[for='" + this.opts.element.attr("id") + "']"); this.opts.element.on('focus.select2', this.bind(function () { this.focus(); })); this.focusser.prev() .text(elementLabel.text()) .attr('for', this.focusser.attr('id')); // Ensure the original element retains an accessible name var originalTitle = this.opts.element.attr("title"); this.opts.element.attr("title", (originalTitle || elementLabel.text())); this.focusser.attr("tabindex", this.elementTabIndex); // write label for search field using the label from the focusser element this.search.attr("id", this.focusser.attr('id') + '_search'); this.search.prev() .text($("label[for='" + this.focusser.attr('id') + "']").text()) .attr('for', this.search.attr('id')); this.search.on("keydown", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; // filter 229 keyCodes (input method editor is processing key input) if (229 == e.keyCode) return; if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) { // prevent the page from scrolling killEvent(e); return; } switch (e.which) { case KEY.UP: case KEY.DOWN: this.moveHighlight((e.which === KEY.UP) ? -1 : 1); killEvent(e); return; case KEY.ENTER: this.selectHighlighted(); killEvent(e); return; case KEY.TAB: this.selectHighlighted({noFocus: true}); return; case KEY.ESC: this.cancel(e); killEvent(e); return; } })); this.search.on("blur", this.bind(function(e) { // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown. // without this the search field loses focus which is annoying if (document.activeElement === this.body.get(0)) { window.setTimeout(this.bind(function() { if (this.opened() && this.results && this.results.length > 1) { this.search.focus(); } }), 0); } })); this.focusser.on("keydown", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) { return; } if (this.opts.openOnEnter === false && e.which === KEY.ENTER) { killEvent(e); return; } if (e.which == KEY.DOWN || e.which == KEY.UP || (e.which == KEY.ENTER && this.opts.openOnEnter)) { if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return; this.open(); killEvent(e); return; } if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) { if (this.opts.allowClear) { this.clear(); } killEvent(e); return; } })); installKeyUpChangeEvent(this.focusser); this.focusser.on("keyup-change input", this.bind(function(e) { if (this.opts.minimumResultsForSearch >= 0) { e.stopPropagation(); if (this.opened()) return; this.open(); } })); selection.on("mousedown touchstart", "abbr", this.bind(function (e) { if (!this.isInterfaceEnabled()) { return; } this.clear(); killEventImmediately(e); this.close(); if (this.selection) { this.selection.focus(); } })); selection.on("mousedown touchstart", this.bind(function (e) { // Prevent IE from generating a click event on the body reinsertElement(selection); if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } if (this.opened()) { this.close(); } else if (this.isInterfaceEnabled()) { this.open(); } killEvent(e); })); dropdown.on("mousedown touchstart", this.bind(function() { if (this.opts.shouldFocusInput(this)) { this.search.focus(); } })); selection.on("focus", this.bind(function(e) { killEvent(e); })); this.focusser.on("focus", this.bind(function(){ if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.container.addClass("select2-container-active"); })).on("blur", this.bind(function() { if (!this.opened()) { this.container.removeClass("select2-container-active"); this.opts.element.trigger($.Event("select2-blur")); } })); this.search.on("focus", this.bind(function(){ if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.container.addClass("select2-container-active"); })); this.initContainerWidth(); this.opts.element.hide(); this.setPlaceholder(); }, // single clear: function(triggerChange) { var data=this.selection.data("select2-data"); if (data) { // guard against queued quick consecutive clicks var evt = $.Event("select2-clearing"); this.opts.element.trigger(evt); if (evt.isDefaultPrevented()) { return; } var placeholderOption = this.getPlaceholderOption(); this.opts.element.val(placeholderOption ? placeholderOption.val() : ""); this.selection.find(".select2-chosen").empty(); this.selection.removeData("select2-data"); this.setPlaceholder(); if (triggerChange !== false){ this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data }); this.triggerChange({removed:data}); } } }, /** * Sets selection based on source element's value */ // single initSelection: function () { var selected; if (this.isPlaceholderOptionSelected()) { this.updateSelection(null); this.close(); this.setPlaceholder(); } else { var self = this; this.opts.initSelection.call(null, this.opts.element, function(selected){ if (selected !== undefined && selected !== null) { self.updateSelection(selected); self.close(); self.setPlaceholder(); self.lastSearchTerm = self.search.val(); } }); } }, isPlaceholderOptionSelected: function() { var placeholderOption; if (this.getPlaceholder() === undefined) return false; // no placeholder specified so no option should be considered return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.prop("selected")) || (this.opts.element.val() === "") || (this.opts.element.val() === undefined) || (this.opts.element.val() === null); }, // single prepareOpts: function () { var opts = this.parent.prepareOpts.apply(this, arguments), self=this; if (opts.element.get(0).tagName.toLowerCase() === "select") { // install the selection initializer opts.initSelection = function (element, callback) { var selected = element.find("option").filter(function() { return this.selected && !this.disabled }); // a single select box always has a value, no need to null check 'selected' callback(self.optionToData(selected)); }; } else if ("data" in opts) { // install default initSelection when applied to hidden input and data is local opts.initSelection = opts.initSelection || function (element, callback) { var id = element.val(); //search in data by id, storing the actual matching item var match = null; opts.query({ matcher: function(term, text, el){ var is_match = equal(id, opts.id(el)); if (is_match) { match = el; } return is_match; }, callback: !$.isFunction(callback) ? $.noop : function() { callback(match); } }); }; } return opts; }, // single getPlaceholder: function() { // if a placeholder is specified on a single select without a valid placeholder option ignore it if (this.select) { if (this.getPlaceholderOption() === undefined) { return undefined; } } return this.parent.getPlaceholder.apply(this, arguments); }, // single setPlaceholder: function () { var placeholder = this.getPlaceholder(); if (this.isPlaceholderOptionSelected() && placeholder !== undefined) { // check for a placeholder option if attached to a select if (this.select && this.getPlaceholderOption() === undefined) return; this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder)); this.selection.addClass("select2-default"); this.container.removeClass("select2-allowclear"); } }, // single postprocessResults: function (data, initial, noHighlightUpdate) { var selected = 0, self = this, showSearchInput = true; // find the selected element in the result list this.findHighlightableChoices().each2(function (i, elm) { if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) { selected = i; return false; } }); // and highlight it if (noHighlightUpdate !== false) { if (initial === true && selected >= 0) { this.highlight(selected); } else { this.highlight(0); } } // hide the search box if this is the first we got the results and there are enough of them for search if (initial === true) { var min = this.opts.minimumResultsForSearch; if (min >= 0) { this.showSearch(countResults(data.results) >= min); } } }, // single showSearch: function(showSearchInput) { if (this.showSearchInput === showSearchInput) return; this.showSearchInput = showSearchInput; this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput); this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput); //add "select2-with-searchbox" to the container if search box is shown $(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput); }, // single onSelect: function (data, options) { if (!this.triggerSelect(data)) { return; } var old = this.opts.element.val(), oldData = this.data(); this.opts.element.val(this.id(data)); this.updateSelection(data); this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data }); this.lastSearchTerm = this.search.val(); this.close(); if ((!options || !options.noFocus) && this.opts.shouldFocusInput(this)) { this.focusser.focus(); } if (!equal(old, this.id(data))) { this.triggerChange({ added: data, removed: oldData }); } }, // single updateSelection: function (data) { var container=this.selection.find(".select2-chosen"), formatted, cssClass; this.selection.data("select2-data", data); container.empty(); if (data !== null) { formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup); } if (formatted !== undefined) { container.append(formatted); } cssClass=this.opts.formatSelectionCssClass(data, container); if (cssClass !== undefined) { container.addClass(cssClass); } this.selection.removeClass("select2-default"); if (this.opts.allowClear && this.getPlaceholder() !== undefined) { this.container.addClass("select2-allowclear"); } }, // single val: function () { var val, triggerChange = false, data = null, self = this, oldData = this.data(); if (arguments.length === 0) { return this.opts.element.val(); } val = arguments[0]; if (arguments.length > 1) { triggerChange = arguments[1]; if (this.opts.debug && console && console.warn) { console.warn( 'Select2: The second option to `select2("val")` is not supported in Select2 4.0.0. ' + 'The `change` event will always be triggered in 4.0.0.' ); } } if (this.select) { if (this.opts.debug && console && console.warn) { console.warn( 'Select2: Setting the value on a <select> using `select2("val")` is no longer supported in 4.0.0. ' + 'You can use the `.val(newValue).trigger("change")` method provided by jQuery instead.' ); } this.select .val(val) .find("option").filter(function() { return this.selected }).each2(function (i, elm) { data = self.optionToData(elm); return false; }); this.updateSelection(data); this.setPlaceholder(); if (triggerChange) { this.triggerChange({added: data, removed:oldData}); } } else { // val is an id. !val is true for [undefined,null,'',0] - 0 is legal if (!val && val !== 0) { this.clear(triggerChange); return; } if (this.opts.initSelection === undefined) { throw new Error("cannot call val() if initSelection() is not defined"); } this.opts.element.val(val); this.opts.initSelection(this.opts.element, function(data){ self.opts.element.val(!data ? "" : self.id(data)); self.updateSelection(data); self.setPlaceholder(); if (triggerChange) { self.triggerChange({added: data, removed:oldData}); } }); } }, // single clearSearch: function () { this.search.val(""); this.focusser.val(""); }, // single data: function(value) { var data, triggerChange = false; if (arguments.length === 0) { data = this.selection.data("select2-data"); if (data == undefined) data = null; return data; } else { if (this.opts.debug && console && console.warn) { console.warn( 'Select2: The `select2("data")` method can no longer set selected values in 4.0.0, ' + 'consider using the `.val()` method instead.' ); } if (arguments.length > 1) { triggerChange = arguments[1]; } if (!value) { this.clear(triggerChange); } else { data = this.data(); this.opts.element.val(!value ? "" : this.id(value)); this.updateSelection(value); if (triggerChange) { this.triggerChange({added: value, removed:data}); } } } } }); MultiSelect2 = clazz(AbstractSelect2, { // multi createContainer: function () { var container = $(document.createElement("div")).attr({ "class": "select2-container select2-container-multi" }).html([ "<ul class='select2-choices'>", " <li class='select2-search-field'>", " <label for='' class='select2-offscreen'></label>", " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>", " </li>", "</ul>", "<div class='select2-drop select2-drop-multi select2-display-none'>", " <ul class='select2-results'>", " </ul>", "</div>"].join("")); return container; }, // multi prepareOpts: function () { var opts = this.parent.prepareOpts.apply(this, arguments), self=this; // TODO validate placeholder is a string if specified if (opts.element.get(0).tagName.toLowerCase() === "select") { // install the selection initializer opts.initSelection = function (element, callback) { var data = []; element.find("option").filter(function() { return this.selected && !this.disabled }).each2(function (i, elm) { data.push(self.optionToData(elm)); }); callback(data); }; } else if ("data" in opts) { // install default initSelection when applied to hidden input and data is local opts.initSelection = opts.initSelection || function (element, callback) { var ids = splitVal(element.val(), opts.separator, opts.transformVal); //search in data by array of ids, storing matching items in a list var matches = []; opts.query({ matcher: function(term, text, el){ var is_match = $.grep(ids, function(id) { return equal(id, opts.id(el)); }).length; if (is_match) { matches.push(el); } return is_match; }, callback: !$.isFunction(callback) ? $.noop : function() { // reorder matches based on the order they appear in the ids array because right now // they are in the order in which they appear in data array var ordered = []; for (var i = 0; i < ids.length; i++) { var id = ids[i]; for (var j = 0; j < matches.length; j++) { var match = matches[j]; if (equal(id, opts.id(match))) { ordered.push(match); matches.splice(j, 1); break; } } } callback(ordered); } }); }; } return opts; }, // multi selectChoice: function (choice) { var selected = this.container.find(".select2-search-choice-focus"); if (selected.length && choice && choice[0] == selected[0]) { } else { if (selected.length) { this.opts.element.trigger("choice-deselected", selected); } selected.removeClass("select2-search-choice-focus"); if (choice && choice.length) { this.close(); choice.addClass("select2-search-choice-focus"); this.opts.element.trigger("choice-selected", choice); } } }, // multi destroy: function() { $("label[for='" + this.search.attr('id') + "']") .attr('for', this.opts.element.attr("id")); this.parent.destroy.apply(this, arguments); cleanupJQueryElements.call(this, "searchContainer", "selection" ); }, // multi initContainer: function () { var selector = ".select2-choices", selection; this.searchContainer = this.container.find(".select2-search-field"); this.selection = selection = this.container.find(selector); var _this = this; this.selection.on("click", ".select2-container:not(.select2-container-disabled) .select2-search-choice:not(.select2-locked)", function (e) { _this.search[0].focus(); _this.selectChoice($(this)); }); // rewrite labels from original element to focusser this.search.attr("id", "s2id_autogen"+nextUid()); this.search.prev() .text($("label[for='" + this.opts.element.attr("id") + "']").text()) .attr('for', this.search.attr('id')); this.opts.element.on('focus.select2', this.bind(function () { this.focus(); })); this.search.on("input paste", this.bind(function() { if (this.search.attr('placeholder') && this.search.val().length == 0) return; if (!this.isInterfaceEnabled()) return; if (!this.opened()) { this.open(); } })); this.search.attr("tabindex", this.elementTabIndex); this.keydowns = 0; this.search.on("keydown", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; ++this.keydowns; var selected = selection.find(".select2-search-choice-focus"); var prev = selected.prev(".select2-search-choice:not(.select2-locked)"); var next = selected.next(".select2-search-choice:not(.select2-locked)"); var pos = getCursorInfo(this.search); if (selected.length && (e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) { var selectedChoice = selected; if (e.which == KEY.LEFT && prev.length) { selectedChoice = prev; } else if (e.which == KEY.RIGHT) { selectedChoice = next.length ? next : null; } else if (e.which === KEY.BACKSPACE) { if (this.unselect(selected.first())) { this.search.width(10); selectedChoice = prev.length ? prev : next; } } else if (e.which == KEY.DELETE) { if (this.unselect(selected.first())) { this.search.width(10); selectedChoice = next.length ? next : null; } } else if (e.which == KEY.ENTER) { selectedChoice = null; } this.selectChoice(selectedChoice); killEvent(e); if (!selectedChoice || !selectedChoice.length) { this.open(); } return; } else if (((e.which === KEY.BACKSPACE && this.keydowns == 1) || e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) { this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last()); killEvent(e); return; } else { this.selectChoice(null); } if (this.opened()) { switch (e.which) { case KEY.UP: case KEY.DOWN: this.moveHighlight((e.which === KEY.UP) ? -1 : 1); killEvent(e); return; case KEY.ENTER: this.selectHighlighted(); killEvent(e); return; case KEY.TAB: this.selectHighlighted({noFocus:true}); this.close(); return; case KEY.ESC: this.cancel(e); killEvent(e); return; } } if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) { return; } if (e.which === KEY.ENTER) { if (this.opts.openOnEnter === false) { return; } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) { return; } } this.open(); if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) { // prevent the page from scrolling killEvent(e); } if (e.which === KEY.ENTER) { // prevent form from being submitted killEvent(e); } })); this.search.on("keyup", this.bind(function (e) { this.keydowns = 0; this.resizeSearch(); }) ); this.search.on("blur", this.bind(function(e) { this.container.removeClass("select2-container-active"); this.search.removeClass("select2-focused"); this.selectChoice(null); if (!this.opened()) this.clearSearch(); e.stopImmediatePropagation(); this.opts.element.trigger($.Event("select2-blur")); })); this.container.on("click", selector, this.bind(function (e) { if (!this.isInterfaceEnabled()) return; if ($(e.target).closest(".select2-search-choice").length > 0) { // clicked inside a select2 search choice, do not open return; } this.selectChoice(null); this.clearPlaceholder(); if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.open(); this.focusSearch(); e.preventDefault(); })); this.container.on("focus", selector, this.bind(function () { if (!this.isInterfaceEnabled()) return; if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.container.addClass("select2-container-active"); this.dropdown.addClass("select2-drop-active"); this.clearPlaceholder(); })); this.initContainerWidth(); this.opts.element.hide(); // set the placeholder if necessary this.clearSearch(); }, // multi enableInterface: function() { if (this.parent.enableInterface.apply(this, arguments)) { this.search.prop("disabled", !this.isInterfaceEnabled()); } }, // multi initSelection: function () { var data; if (this.opts.element.val() === "" && this.opts.element.text() === "") { this.updateSelection([]); this.close(); // set the placeholder if necessary this.clearSearch(); } if (this.select || this.opts.element.val() !== "") { var self = this; this.opts.initSelection.call(null, this.opts.element, function(data){ if (data !== undefined && data !== null) { self.updateSelection(data); self.close(); // set the placeholder if necessary self.clearSearch(); } }); } }, // multi clearSearch: function () { var placeholder = this.getPlaceholder(), maxWidth = this.getMaxSearchWidth(); if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) { this.search.val(placeholder).addClass("select2-default"); // stretch the search box to full width of the container so as much of the placeholder is visible as possible // we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944 this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width")); } else { this.search.val("").width(10); } }, // multi clearPlaceholder: function () { if (this.search.hasClass("select2-default")) { this.search.val("").removeClass("select2-default"); } }, // multi opening: function () { this.clearPlaceholder(); // should be done before super so placeholder is not used to search this.resizeSearch(); this.parent.opening.apply(this, arguments); this.focusSearch(); this.prefillNextSearchTerm(); this.updateResults(true); if (this.opts.shouldFocusInput(this)) { this.search.focus(); } this.opts.element.trigger($.Event("select2-open")); }, // multi close: function () { if (!this.opened()) return; this.parent.close.apply(this, arguments); }, // multi focus: function () { this.close(); this.search.focus(); }, // multi isFocused: function () { return this.search.hasClass("select2-focused"); }, // multi updateSelection: function (data) { var ids = {}, filtered = [], self = this; // filter out duplicates $(data).each(function () { if (!(self.id(this) in ids)) { ids[self.id(this)] = 0; filtered.push(this); } }); this.selection.find(".select2-search-choice").remove(); this.addSelectedChoice(filtered); self.postprocessResults(); }, // multi tokenize: function() { var input = this.search.val(); input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts); if (input != null && input != undefined) { this.search.val(input); if (input.length > 0) { this.open(); } } }, // multi onSelect: function (data, options) { if (!this.triggerSelect(data) || data.text === "") { return; } this.addSelectedChoice(data); this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data }); // keep track of the search's value before it gets cleared this.lastSearchTerm = this.search.val(); this.clearSearch(); this.updateResults(); if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true); if (this.opts.closeOnSelect) { this.close(); this.search.width(10); } else { if (this.countSelectableResults()>0) { this.search.width(10); this.resizeSearch(); if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) { // if we reached max selection size repaint the results so choices // are replaced with the max selection reached message this.updateResults(true); } else { // initializes search's value with nextSearchTerm and update search result if (this.prefillNextSearchTerm()) { this.updateResults(); } } this.positionDropdown(); } else { // if nothing left to select close this.close(); this.search.width(10); } } // since its not possible to select an element that has already been // added we do not need to check if this is a new element before firing change this.triggerChange({ added: data }); if (!options || !options.noFocus) this.focusSearch(); }, // multi cancel: function () { this.close(); this.focusSearch(); }, addSelectedChoice: function (data) { var val = this.getVal(), self = this; $(data).each(function () { val.push(self.createChoice(this)); }); this.setVal(val); }, createChoice: function (data) { var enableChoice = !data.locked, enabledItem = $( "<li class='select2-search-choice'>" + " <div></div>" + " <a href='#' class='select2-search-choice-close' tabindex='-1'></a>" + "</li>"), disabledItem = $( "<li class='select2-search-choice select2-locked'>" + "<div></div>" + "</li>"); var choice = enableChoice ? enabledItem : disabledItem, id = this.id(data), formatted, cssClass; formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup); if (formatted != undefined) { choice.find("div").replaceWith($("<div></div>").html(formatted)); } cssClass=this.opts.formatSelectionCssClass(data, choice.find("div")); if (cssClass != undefined) { choice.addClass(cssClass); } if(enableChoice){ choice.find(".select2-search-choice-close") .on("mousedown", killEvent) .on("click dblclick", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; this.unselect($(e.target)); this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"); killEvent(e); this.close(); this.focusSearch(); })).on("focus", this.bind(function () { if (!this.isInterfaceEnabled()) return; this.container.addClass("select2-container-active"); this.dropdown.addClass("select2-drop-active"); })); } choice.data("select2-data", data); choice.insertBefore(this.searchContainer); return id; }, // multi unselect: function (selected) { var val = this.getVal(), data, index; selected = selected.closest(".select2-search-choice"); if (selected.length === 0) { throw "Invalid argument: " + selected + ". Must be .select2-search-choice"; } data = selected.data("select2-data"); if (!data) { // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued // and invoked on an element already removed return; } var evt = $.Event("select2-removing"); evt.val = this.id(data); evt.choice = data; this.opts.element.trigger(evt); if (evt.isDefaultPrevented()) { return false; } while((index = indexOf(this.id(data), val)) >= 0) { val.splice(index, 1); this.setVal(val); if (this.select) this.postprocessResults(); } selected.remove(); this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data }); this.triggerChange({ removed: data }); return true; }, // multi postprocessResults: function (data, initial, noHighlightUpdate) { var val = this.getVal(), choices = this.results.find(".select2-result"), compound = this.results.find(".select2-result-with-children"), self = this; choices.each2(function (i, choice) { var id = self.id(choice.data("select2-data")); if (indexOf(id, val) >= 0) { choice.addClass("select2-selected"); // mark all children of the selected parent as selected choice.find(".select2-result-selectable").addClass("select2-selected"); } }); compound.each2(function(i, choice) { // hide an optgroup if it doesn't have any selectable children if (!choice.is('.select2-result-selectable') && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) { choice.addClass("select2-selected"); } }); if (this.highlight() == -1 && noHighlightUpdate !== false && this.opts.closeOnSelect === true){ self.highlight(0); } //If all results are chosen render formatNoMatches if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){ if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) { if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) { this.results.append("<li class='select2-no-results'>" + evaluate(self.opts.formatNoMatches, self.opts.element, self.search.val()) + "</li>"); } } } }, // multi getMaxSearchWidth: function() { return this.selection.width() - getSideBorderPadding(this.search); }, // multi resizeSearch: function () { var minimumWidth, left, maxWidth, containerLeft, searchWidth, sideBorderPadding = getSideBorderPadding(this.search); minimumWidth = measureTextWidth(this.search) + 10; left = this.search.offset().left; maxWidth = this.selection.width(); containerLeft = this.selection.offset().left; searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding; if (searchWidth < minimumWidth) { searchWidth = maxWidth - sideBorderPadding; } if (searchWidth < 40) { searchWidth = maxWidth - sideBorderPadding; } if (searchWidth <= 0) { searchWidth = minimumWidth; } this.search.width(Math.floor(searchWidth)); }, // multi getVal: function () { var val; if (this.select) { val = this.select.val(); return val === null ? [] : val; } else { val = this.opts.element.val(); return splitVal(val, this.opts.separator, this.opts.transformVal); } }, // multi setVal: function (val) { if (this.select) { this.select.val(val); } else { var unique = [], valMap = {}; // filter out duplicates $(val).each(function () { if (!(this in valMap)) { unique.push(this); valMap[this] = 0; } }); this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator)); } }, // multi buildChangeDetails: function (old, current) { var current = current.slice(0), old = old.slice(0); // remove intersection from each array for (var i = 0; i < current.length; i++) { for (var j = 0; j < old.length; j++) { if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) { current.splice(i, 1); i--; old.splice(j, 1); break; } } } return {added: current, removed: old}; }, // multi val: function (val, triggerChange) { var oldData, self=this; if (arguments.length === 0) { return this.getVal(); } oldData=this.data(); if (!oldData.length) oldData=[]; // val is an id. !val is true for [undefined,null,'',0] - 0 is legal if (!val && val !== 0) { this.opts.element.val(""); this.updateSelection([]); this.clearSearch(); if (triggerChange) { this.triggerChange({added: this.data(), removed: oldData}); } return; } // val is a list of ids this.setVal(val); if (this.select) { this.opts.initSelection(this.select, this.bind(this.updateSelection)); if (triggerChange) { this.triggerChange(this.buildChangeDetails(oldData, this.data())); } } else { if (this.opts.initSelection === undefined) { throw new Error("val() cannot be called if initSelection() is not defined"); } this.opts.initSelection(this.opts.element, function(data){ var ids=$.map(data, self.id); self.setVal(ids); self.updateSelection(data); self.clearSearch(); if (triggerChange) { self.triggerChange(self.buildChangeDetails(oldData, self.data())); } }); } this.clearSearch(); }, // multi onSortStart: function() { if (this.select) { throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead."); } // collapse search field into 0 width so its container can be collapsed as well this.search.width(0); // hide the container this.searchContainer.hide(); }, // multi onSortEnd:function() { var val=[], self=this; // show search and move it to the end of the list this.searchContainer.show(); // make sure the search container is the last item in the list this.searchContainer.appendTo(this.searchContainer.parent()); // since we collapsed the width in dragStarted, we resize it here this.resizeSearch(); // update selection this.selection.find(".select2-search-choice").each(function() { val.push(self.opts.id($(this).data("select2-data"))); }); this.setVal(val); this.triggerChange(); }, // multi data: function(values, triggerChange) { var self=this, ids, old; if (arguments.length === 0) { return this.selection .children(".select2-search-choice") .map(function() { return $(this).data("select2-data"); }) .get(); } else { old = this.data(); if (!values) { values = []; } ids = $.map(values, function(e) { return self.opts.id(e); }); this.setVal(ids); this.updateSelection(values); this.clearSearch(); if (triggerChange) { this.triggerChange(this.buildChangeDetails(old, this.data())); } } } }); $.fn.select2 = function () { var args = Array.prototype.slice.call(arguments, 0), opts, select2, method, value, multiple, allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"], valueMethods = ["opened", "isFocused", "container", "dropdown"], propertyMethods = ["val", "data"], methodsMap = { search: "externalSearch" }; this.each(function () { if (args.length === 0 || typeof(args[0]) === "object") { opts = args.length === 0 ? {} : $.extend({}, args[0]); opts.element = $(this); if (opts.element.get(0).tagName.toLowerCase() === "select") { multiple = opts.element.prop("multiple"); } else { multiple = opts.multiple || false; if ("tags" in opts) {opts.multiple = multiple = true;} } select2 = multiple ? new window.Select2["class"].multi() : new window.Select2["class"].single(); select2.init(opts); } else if (typeof(args[0]) === "string") { if (indexOf(args[0], allowedMethods) < 0) { throw "Unknown method: " + args[0]; } value = undefined; select2 = $(this).data("select2"); if (select2 === undefined) return; method=args[0]; if (method === "container") { value = select2.container; } else if (method === "dropdown") { value = select2.dropdown; } else { if (methodsMap[method]) method = methodsMap[method]; value = select2[method].apply(select2, args.slice(1)); } if (indexOf(args[0], valueMethods) >= 0 || (indexOf(args[0], propertyMethods) >= 0 && args.length == 1)) { return false; // abort the iteration, ready to return first matched value } } else { throw "Invalid arguments to select2 plugin: " + args; } }); return (value === undefined) ? this : value; }; // plugin defaults, accessible to users $.fn.select2.defaults = { debug: false, width: "copy", loadMorePadding: 0, closeOnSelect: true, openOnEnter: true, containerCss: {}, dropdownCss: {}, containerCssClass: "", dropdownCssClass: "", formatResult: function(result, container, query, escapeMarkup) { var markup=[]; markMatch(this.text(result), query.term, markup, escapeMarkup); return markup.join(""); }, transformVal: function(val) { return $.trim(val); }, formatSelection: function (data, container, escapeMarkup) { return data ? escapeMarkup(this.text(data)) : undefined; }, sortResults: function (results, container, query) { return results; }, formatResultCssClass: function(data) {return data.css;}, formatSelectionCssClass: function(data, container) {return undefined;}, minimumResultsForSearch: 0, minimumInputLength: 0, maximumInputLength: null, maximumSelectionSize: 0, id: function (e) { return e == undefined ? null : e.id; }, text: function (e) { if (e && this.data && this.data.text) { if ($.isFunction(this.data.text)) { return this.data.text(e); } else { return e[this.data.text]; } } else { return e.text; } }, matcher: function(term, text) { return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0; }, separator: ",", tokenSeparators: [], tokenizer: defaultTokenizer, escapeMarkup: defaultEscapeMarkup, blurOnChange: false, selectOnBlur: false, adaptContainerCssClass: function(c) { return c; }, adaptDropdownCssClass: function(c) { return null; }, nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; }, searchInputPlaceholder: '', createSearchChoicePosition: 'top', shouldFocusInput: function (instance) { // Attempt to detect touch devices var supportsTouchEvents = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0)); // Only devices which support touch events should be special cased if (!supportsTouchEvents) { return true; } // Never focus the input if search is disabled if (instance.opts.minimumResultsForSearch < 0) { return false; } return true; } }; $.fn.select2.locales = []; $.fn.select2.locales['en'] = { formatMatches: function (matches) { if (matches === 1) { return "One result is available, press enter to select it."; } return matches + " results are available, use up and down arrow keys to navigate."; }, formatNoMatches: function () { return "No matches found"; }, formatAjaxError: function (jqXHR, textStatus, errorThrown) { return "Loading failed"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " or more character" + (n == 1 ? "" : "s"); }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1 ? "" : "s"); }, formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); }, formatLoadMore: function (pageNumber) { return "Loading more results…"; }, formatSearching: function () { return "Searching…"; } }; $.extend($.fn.select2.defaults, $.fn.select2.locales['en']); $.fn.select2.ajaxDefaults = { transport: $.ajax, params: { type: "GET", cache: false, dataType: "json" } }; // exports window.Select2 = { query: { ajax: ajax, local: local, tags: tags }, util: { debounce: debounce, markMatch: markMatch, escapeMarkup: defaultEscapeMarkup, stripDiacritics: stripDiacritics }, "class": { "abstract": AbstractSelect2, "single": SingleSelect2, "multi": MultiSelect2 } }; }(jQuery));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-select2-3.5.4.js
jquery-select2-3.5.4.js
var TableTools;(function(c,a,d){var b=function(g,f){var e={version:"1.0.4-TableTools2",clients:{},moviePath:"",nextId:1,$:function(i){if(typeof(i)=="string"){i=a.getElementById(i)}if(!i.addClass){i.hide=function(){this.style.display="none"};i.show=function(){this.style.display=""};i.addClass=function(j){this.removeClass(j);this.className+=" "+j};i.removeClass=function(j){this.className=this.className.replace(new RegExp("\\s*"+j+"\\s*")," ").replace(/^\s+/,"").replace(/\s+$/,"")};i.hasClass=function(j){return !!this.className.match(new RegExp("\\s*"+j+"\\s*"))}}return i},setMoviePath:function(i){this.moviePath=i},dispatch:function(l,j,k){var i=this.clients[l];if(i){i.receiveEvent(j,k)}},register:function(j,i){this.clients[j]=i},getDOMObjectPosition:function(j){var i={left:0,top:0,width:j.width?j.width:j.offsetWidth,height:j.height?j.height:j.offsetHeight};if(j.style.width!==""){i.width=j.style.width.replace("px","")}if(j.style.height!==""){i.height=j.style.height.replace("px","")}while(j){i.left+=j.offsetLeft;i.top+=j.offsetTop;j=j.offsetParent}return i},Client:function(i){this.handlers={};this.id=e.nextId++;this.movieId="ZeroClipboard_TableToolsMovie_"+this.id;e.register(this.id,this);if(i){this.glue(i)}}};e.Client.prototype={id:0,ready:false,movie:null,clipText:"",fileName:"",action:"copy",handCursorEnabled:true,cssEffects:true,handlers:null,sized:false,glue:function(k,l){this.domElement=e.$(k);var m=99;if(this.domElement.style.zIndex){m=parseInt(this.domElement.style.zIndex,10)+1}var j=e.getDOMObjectPosition(this.domElement);this.div=a.createElement("div");var i=this.div.style;i.position="absolute";i.left="0px";i.top="0px";i.width=(j.width)+"px";i.height=j.height+"px";i.zIndex=m;if(typeof l!="undefined"&&l!==""){this.div.title=l}if(j.width!==0&&j.height!==0){this.sized=true}if(this.domElement){this.domElement.appendChild(this.div);this.div.innerHTML=this.getHTML(j.width,j.height).replace(/&/g,"&amp;")}},positionElement:function(){var k=e.getDOMObjectPosition(this.domElement);var j=this.div.style;j.position="absolute";j.width=k.width+"px";j.height=k.height+"px";if(k.width!==0&&k.height!==0){this.sized=true}else{return}var i=this.div.childNodes[0];i.width=k.width;i.height=k.height},getHTML:function(l,i){var k="";var j="id="+this.id+"&width="+l+"&height="+i;if(navigator.userAgent.match(/MSIE/)){var m=location.href.match(/^https/i)?"https://":"http://";k+='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+m+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+l+'" height="'+i+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+e.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+j+'"/><param name="wmode" value="transparent"/></object>'}else{k+='<embed id="'+this.movieId+'" src="'+e.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+l+'" height="'+i+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+j+'" wmode="transparent" />'}return k},hide:function(){if(this.div){this.div.style.left="-2000px"}},show:function(){this.reposition()},destroy:function(){if(this.domElement&&this.div){this.hide();this.div.innerHTML="";var i=a.getElementsByTagName("body")[0];try{i.removeChild(this.div)}catch(j){}this.domElement=null;this.div=null}},reposition:function(k){if(k){this.domElement=e.$(k);if(!this.domElement){this.hide()}}if(this.domElement&&this.div){var j=e.getDOMObjectPosition(this.domElement);var i=this.div.style;i.left=""+j.left+"px";i.top=""+j.top+"px"}},clearText:function(){this.clipText="";if(this.ready){this.movie.clearText()}},appendText:function(i){this.clipText+=i;if(this.ready){this.movie.appendText(i)}},setText:function(i){this.clipText=i;if(this.ready){this.movie.setText(i)}},setCharSet:function(i){this.charSet=i;if(this.ready){this.movie.setCharSet(i)}},setBomInc:function(i){this.incBom=i;if(this.ready){this.movie.setBomInc(i)}},setFileName:function(i){this.fileName=i;if(this.ready){this.movie.setFileName(i)}},setAction:function(i){this.action=i;if(this.ready){this.movie.setAction(i)}},addEventListener:function(i,j){i=i.toString().toLowerCase().replace(/^on/,"");if(!this.handlers[i]){this.handlers[i]=[]}this.handlers[i].push(j)},setHandCursor:function(i){this.handCursorEnabled=i;if(this.ready){this.movie.setHandCursor(i)}},setCSSEffects:function(i){this.cssEffects=!!i},receiveEvent:function(l,m){var k;l=l.toString().toLowerCase().replace(/^on/,"");switch(l){case"load":this.movie=a.getElementById(this.movieId);if(!this.movie){k=this;setTimeout(function(){k.receiveEvent("load",null)},1);return}if(!this.ready&&navigator.userAgent.match(/Firefox/)&&navigator.userAgent.match(/Windows/)){k=this;setTimeout(function(){k.receiveEvent("load",null)},100);this.ready=true;return}this.ready=true;this.movie.clearText();this.movie.appendText(this.clipText);this.movie.setFileName(this.fileName);this.movie.setAction(this.action);this.movie.setCharSet(this.charSet);this.movie.setBomInc(this.incBom);this.movie.setHandCursor(this.handCursorEnabled);break;case"mouseover":if(this.domElement&&this.cssEffects){if(this.recoverActive){this.domElement.addClass("active")}}break;case"mouseout":if(this.domElement&&this.cssEffects){this.recoverActive=false;if(this.domElement.hasClass("active")){this.domElement.removeClass("active");this.recoverActive=true}}break;case"mousedown":if(this.domElement&&this.cssEffects){this.domElement.addClass("active")}break;case"mouseup":if(this.domElement&&this.cssEffects){this.domElement.removeClass("active");this.recoverActive=false}break}if(this.handlers[l]){for(var j=0,i=this.handlers[l].length;j<i;j++){var n=this.handlers[l][j];if(typeof(n)=="function"){n(this,m)}else{if((typeof(n)=="object")&&(n.length==2)){n[0][n[1]](this,m)}else{if(typeof(n)=="string"){c[n](this,m)}}}}}}};c.ZeroClipboard_TableTools=e;var h;(function(k,j,i){h=function(l,n){if(!this instanceof h){alert("Warning: TableTools must be initialised with the keyword 'new'")}var m=k.fn.dataTable.Api?new k.fn.dataTable.Api(l).settings()[0]:l.fnSettings();this.s={that:this,dt:m,print:{saveStart:-1,saveLength:-1,saveScroll:-1,funcEnd:function(){}},buttonCounter:0,select:{type:"",selected:[],preRowSelect:null,postSelected:null,postDeselected:null,all:false,selectedClass:""},custom:{},swfPath:"",buttonSet:[],master:false,tags:{}};this.dom={container:null,table:null,print:{hidden:[],message:null},collection:{collection:null,background:null}};this.classes=k.extend(true,{},h.classes);if(this.s.dt.bJUI){k.extend(true,this.classes,h.classes_themeroller)}this.fnSettings=function(){return this.s};if(typeof n=="undefined"){n={}}this._fnConstruct(n);return this};h.prototype={fnGetSelected:function(n){var m=[],q=this.s.dt.aoData,p=this.s.dt.aiDisplay,o,l;if(n){for(o=0,l=p.length;o<l;o++){if(q[p[o]]._DTTT_selected){m.push(q[p[o]].nTr)}}}else{for(o=0,l=q.length;o<l;o++){if(q[o]._DTTT_selected){m.push(q[o].nTr)}}}return m},fnGetSelectedData:function(){var m=[];var o=this.s.dt.aoData;var n,l;for(n=0,l=o.length;n<l;n++){if(o[n]._DTTT_selected){m.push(this.s.dt.oInstance.fnGetData(n))}}return m},fnIsSelected:function(m){var l=this.s.dt.oInstance.fnGetPosition(m);return(this.s.dt.aoData[l]._DTTT_selected===true)?true:false},fnSelectAll:function(l){var m=this._fnGetMasterSettings();this._fnRowSelect((l===true)?m.dt.aiDisplay:m.dt.aoData)},fnSelectNone:function(l){var m=this._fnGetMasterSettings();this._fnRowDeselect(this.fnGetSelected(l))},fnSelect:function(l){if(this.s.select.type=="single"){this.fnSelectNone();this._fnRowSelect(l)}else{if(this.s.select.type=="multi"){this._fnRowSelect(l)}}},fnDeselect:function(l){this._fnRowDeselect(l)},fnGetTitle:function(n){var l="";if(typeof n.sTitle!="undefined"&&n.sTitle!==""){l=n.sTitle}else{var m=i.getElementsByTagName("title");if(m.length>0){l=m[0].innerHTML}}if("\u00A1".toString().length<4){return l.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g,"")}else{return l.replace(/[^a-zA-Z0-9_\.,\-_ !\(\)]/g,"")}},fnCalcColRatios:function(q){var p=this.s.dt.aoColumns,m=this._fnColumnTargets(q.mColumns),o=[],r=0,s=0,n,l;for(n=0,l=m.length;n<l;n++){if(m[n]){r=p[n].nTh.offsetWidth;s+=r;o.push(r)}}for(n=0,l=o.length;n<l;n++){o[n]=o[n]/s}return o.join("\t")},fnGetTableData:function(l){if(this.s.dt){return this._fnGetDataTablesData(l)}},fnSetText:function(l,m){this._fnFlashSetText(l,m)},fnResizeButtons:function(){for(var l in e.clients){if(l){var m=e.clients[l];if(typeof m.domElement!="undefined"&&m.domElement.parentNode){m.positionElement()}}}},fnResizeRequired:function(){for(var l in e.clients){if(l){var m=e.clients[l];if(typeof m.domElement!="undefined"&&m.domElement.parentNode==this.dom.container&&m.sized===false){return true}}}return false},fnPrint:function(l,m){if(m===d){m={}}if(l===d||l){this._fnPrintStart(m)}else{this._fnPrintEnd()}},fnInfo:function(l,n){var m=k("<div/>").addClass(this.classes.print.info).html(l).appendTo("body");setTimeout(function(){m.fadeOut("normal",function(){m.remove()})},n)},fnContainer:function(){return this.dom.container},_fnConstruct:function(m){var l=this;this._fnCustomiseSettings(m);this.dom.container=i.createElement(this.s.tags.container);this.dom.container.className=this.classes.container;if(this.s.select.type!="none"){this._fnRowSelectConfig()}this._fnButtonDefinations(this.s.buttonSet,this.dom.container);this.s.dt.aoDestroyCallback.push({sName:"TableTools",fn:function(){k(l.s.dt.nTBody).off("click.DTTT_Select","tr");k(l.dom.container).empty()}})},_fnCustomiseSettings:function(l){if(typeof this.s.dt._TableToolsInit=="undefined"){this.s.master=true;this.s.dt._TableToolsInit=true}this.dom.table=this.s.dt.nTable;this.s.custom=k.extend({},h.DEFAULTS,l);this.s.swfPath=this.s.custom.sSwfPath;if(typeof e!="undefined"){e.moviePath=this.s.swfPath}this.s.select.type=this.s.custom.sRowSelect;this.s.select.preRowSelect=this.s.custom.fnPreRowSelect;this.s.select.postSelected=this.s.custom.fnRowSelected;this.s.select.postDeselected=this.s.custom.fnRowDeselected;if(this.s.custom.sSelectedClass){this.classes.select.row=this.s.custom.sSelectedClass}this.s.tags=this.s.custom.oTags;this.s.buttonSet=this.s.custom.aButtons},_fnButtonDefinations:function(p,r){var m;for(var n=0,l=p.length;n<l;n++){if(typeof p[n]=="string"){if(typeof h.BUTTONS[p[n]]=="undefined"){alert("TableTools: Warning - unknown button type: "+p[n]);continue}m=k.extend({},h.BUTTONS[p[n]],true)}else{if(typeof h.BUTTONS[p[n].sExtends]=="undefined"){alert("TableTools: Warning - unknown button type: "+p[n].sExtends);continue}var q=k.extend({},h.BUTTONS[p[n].sExtends],true);m=k.extend(q,p[n],true)}r.appendChild(this._fnCreateButton(m,k(r).hasClass(this.classes.collection.container)))}},_fnCreateButton:function(n,l){var m=this._fnButtonBase(n,l);if(n.sAction.match(/flash/)){this._fnFlashConfig(m,n)}else{if(n.sAction=="text"){this._fnTextConfig(m,n)}else{if(n.sAction=="div"){this._fnTextConfig(m,n)}else{if(n.sAction=="collection"){this._fnTextConfig(m,n);this._fnCollectionConfig(m,n)}}}}return m},_fnButtonBase:function(s,m){var n,q,t;if(m){n=s.sTag&&s.sTag!=="default"?s.sTag:this.s.tags.collection.button;q=s.sLinerTag&&s.sLinerTag!=="default"?s.sLiner:this.s.tags.collection.liner;t=this.classes.collection.buttons.normal}else{n=s.sTag&&s.sTag!=="default"?s.sTag:this.s.tags.button;q=s.sLinerTag&&s.sLinerTag!=="default"?s.sLiner:this.s.tags.liner;t=this.classes.buttons.normal}var p=i.createElement(n),l=i.createElement(q),r=this._fnGetMasterSettings();p.className=t+" "+s.sButtonClass;p.setAttribute("id","ToolTables_"+this.s.dt.sInstance+"_"+r.buttonCounter);p.appendChild(l);l.innerHTML=s.sButtonText;r.buttonCounter++;return p},_fnGetMasterSettings:function(){if(this.s.master){return this.s}else{var n=h._aInstances;for(var m=0,l=n.length;m<l;m++){if(this.dom.table==n[m].s.dt.nTable){return n[m].s}}}},_fnCollectionConfig:function(l,m){var n=i.createElement(this.s.tags.collection.container);n.style.display="none";n.className=this.classes.collection.container;m._collection=n;i.body.appendChild(n);this._fnButtonDefinations(m.aButtons,n)},_fnCollectionShow:function(p,s){var v=this,x=k(p).offset(),q=s._collection,m=x.left,l=x.top+k(p).outerHeight(),u=k(j).height(),r=k(i).height(),t=k(j).width(),w=k(i).width();q.style.position="absolute";q.style.left=m+"px";q.style.top=l+"px";q.style.display="block";k(q).css("opacity",0);var n=i.createElement("div");n.style.position="absolute";n.style.left="0px";n.style.top="0px";n.style.height=((u>r)?u:r)+"px";n.style.width=((t>w)?t:w)+"px";n.className=this.classes.collection.background;k(n).css("opacity",0);i.body.appendChild(n);i.body.appendChild(q);var o=k(q).outerWidth();var y=k(q).outerHeight();if(m+o>w){q.style.left=(w-o)+"px"}if(l+y>r){q.style.top=(l-y-k(p).outerHeight())+"px"}this.dom.collection.collection=q;this.dom.collection.background=n;setTimeout(function(){k(q).animate({opacity:1},500);k(n).animate({opacity:0.25},500)},10);this.fnResizeButtons();k(n).click(function(){v._fnCollectionHide.call(v,null,null)})},_fnCollectionHide:function(l,m){if(m!==null&&m.sExtends=="collection"){return}if(this.dom.collection.collection!==null){k(this.dom.collection.collection).animate({opacity:0},500,function(n){this.style.display="none"});k(this.dom.collection.background).animate({opacity:0},500,function(n){this.parentNode.removeChild(this)});this.dom.collection.collection=null;this.dom.collection.background=null}},_fnRowSelectConfig:function(){if(this.s.master){var o=this,m,l,n=this.s.dt,p=this.s.dt.aoOpenRows;k(n.nTable).addClass(this.classes.select.table);if(this.s.select.type==="os"){k(n.nTBody).on("mousedown.DTTT_Select","tr",function(q){if(q.shiftKey){k(n.nTBody).css("-moz-user-select","none").one("selectstart.DTTT_Select","tr",function(){return false})}});k(n.nTBody).on("mouseup.DTTT_Select","tr",function(q){k(n.nTBody).css("-moz-user-select","")})}k(n.nTBody).on("click.DTTT_Select","tr",function(v){var q=o.s.select;var w=o.s.dt.oInstance.fnGetPosition(this);if(this.parentNode!=n.nTBody){return}if(n.oInstance.fnGetData(this)===null){return}if(q.type=="os"){if(v.ctrlKey||v.metaKey){if(o.fnIsSelected(this)){o._fnRowDeselect(this,v)}else{o._fnRowSelect(this,v)}}else{if(v.shiftKey){var t=o.s.dt.aiDisplay.slice();var s=k.inArray(q.lastRow,t);var r=k.inArray(w,t);if(o.fnGetSelected().length===0||s===-1){t.splice(k.inArray(w,t)+1,t.length)}else{if(s>r){var u=r;r=s;s=u}t.splice(r+1,t.length);t.splice(0,s)}if(!o.fnIsSelected(this)){o._fnRowSelect(t,v)}else{t.splice(k.inArray(w,t),1);o._fnRowDeselect(t,v)}}else{if(o.fnIsSelected(this)&&o.fnGetSelected().length===1){o._fnRowDeselect(this,v)}else{o.fnSelectNone();o._fnRowSelect(this,v)}}}}else{if(o.fnIsSelected(this)){o._fnRowDeselect(this,v)}else{if(q.type=="single"){o.fnSelectNone();o._fnRowSelect(this,v)}else{if(q.type=="multi"){o._fnRowSelect(this,v)}}}}q.lastRow=w});n.oApi._fnCallbackReg(n,"aoRowCreatedCallback",function(s,r,q){if(n.aoData[q]._DTTT_selected){k(s).addClass(o.classes.select.row)}},"TableTools-SelectAll")}},_fnRowSelect:function(s,r){var p=this,q=this._fnSelectData(s),n=q.length===0?null:q[0].nTr,m=[],o,l;for(o=0,l=q.length;o<l;o++){if(q[o].nTr){m.push(q[o].nTr)}}if(this.s.select.preRowSelect!==null&&!this.s.select.preRowSelect.call(this,r,m,true)){return}for(o=0,l=q.length;o<l;o++){q[o]._DTTT_selected=true;if(q[o].nTr){k(q[o].nTr).addClass(p.classes.select.row)}}if(this.s.select.postSelected!==null){this.s.select.postSelected.call(this,m)}h._fnEventDispatch(this,"select",m,true)},_fnRowDeselect:function(s,r){var o=this,p=this._fnSelectData(s),m=p.length===0?null:p[0].nTr,q=[],n,l;for(n=0,l=p.length;n<l;n++){if(p[n].nTr){q.push(p[n].nTr)}}if(this.s.select.preRowSelect!==null&&!this.s.select.preRowSelect.call(this,r,q,false)){return}for(n=0,l=p.length;n<l;n++){p[n]._DTTT_selected=false;if(p[n].nTr){k(p[n].nTr).removeClass(o.classes.select.row)}}if(this.s.select.postDeselected!==null){this.s.select.postDeselected.call(this,q)}h._fnEventDispatch(this,"select",q,false)},_fnSelectData:function(o){var m=[],p,n,l;if(o.nodeName){p=this.s.dt.oInstance.fnGetPosition(o);m.push(this.s.dt.aoData[p])}else{if(typeof o.length!=="undefined"){for(n=0,l=o.length;n<l;n++){if(o[n].nodeName){p=this.s.dt.oInstance.fnGetPosition(o[n]);m.push(this.s.dt.aoData[p])}else{if(typeof o[n]==="number"){m.push(this.s.dt.aoData[o[n]])}else{m.push(o[n])}}}return m}else{m.push(o)}}return m},_fnTextConfig:function(l,n){var m=this;if(n.fnInit!==null){n.fnInit.call(this,l,n)}if(n.sToolTip!==""){l.title=n.sToolTip}k(l).hover(function(){if(n.fnMouseover!==null){n.fnMouseover.call(this,l,n,null)}},function(){if(n.fnMouseout!==null){n.fnMouseout.call(this,l,n,null)}});if(n.fnSelect!==null){h._fnEventListen(this,"select",function(o){n.fnSelect.call(m,l,n,o)})}k(l).click(function(o){if(n.fnClick!==null){n.fnClick.call(m,l,n,null,o)}if(n.fnComplete!==null){n.fnComplete.call(m,l,n,null,null)}m._fnCollectionHide(l,n)})},_fnFlashConfig:function(m,o){var n=this;var l=new e.Client();if(o.fnInit!==null){o.fnInit.call(this,m,o)}l.setHandCursor(true);if(o.sAction=="flash_save"){l.setAction("save");l.setCharSet((o.sCharSet=="utf16le")?"UTF16LE":"UTF8");l.setBomInc(o.bBomInc);l.setFileName(o.sFileName.replace("*",this.fnGetTitle(o)))}else{if(o.sAction=="flash_pdf"){l.setAction("pdf");l.setFileName(o.sFileName.replace("*",this.fnGetTitle(o)))}else{l.setAction("copy")}}l.addEventListener("mouseOver",function(p){if(o.fnMouseover!==null){o.fnMouseover.call(n,m,o,l)}});l.addEventListener("mouseOut",function(p){if(o.fnMouseout!==null){o.fnMouseout.call(n,m,o,l)}});l.addEventListener("mouseDown",function(p){if(o.fnClick!==null){o.fnClick.call(n,m,o,l)}});l.addEventListener("complete",function(p,q){if(o.fnComplete!==null){o.fnComplete.call(n,m,o,l,q)}n._fnCollectionHide(m,o)});this._fnFlashGlue(l,m,o.sToolTip)},_fnFlashGlue:function(l,n,o){var m=this;var p=n.getAttribute("id");if(i.getElementById(p)){l.glue(n,o)}else{setTimeout(function(){m._fnFlashGlue(l,n,o)},100)}},_fnFlashSetText:function(p,m){var o=this._fnChunkData(m,8192);p.clearText();for(var n=0,l=o.length;n<l;n++){p.appendText(o[n])}},_fnColumnTargets:function(n){var p=[];var o=this.s.dt;var m,l;if(typeof n=="object"){for(m=0,l=o.aoColumns.length;m<l;m++){p.push(false)}for(m=0,l=n.length;m<l;m++){p[n[m]]=true}}else{if(n=="visible"){for(m=0,l=o.aoColumns.length;m<l;m++){p.push(o.aoColumns[m].bVisible?true:false)}}else{if(n=="hidden"){for(m=0,l=o.aoColumns.length;m<l;m++){p.push(o.aoColumns[m].bVisible?false:true)}}else{if(n=="sortable"){for(m=0,l=o.aoColumns.length;m<l;m++){p.push(o.aoColumns[m].bSortable?true:false)}}else{for(m=0,l=o.aoColumns.length;m<l;m++){p.push(true)}}}}}return p},_fnNewline:function(l){if(l.sNewLine=="auto"){return navigator.userAgent.match(/Windows/)?"\r\n":"\n"}else{return l.sNewLine}},_fnGetDataTablesData:function(r){var A,y,z,D;var n,p=[],l="",m;var x=this.s.dt,o,u;var q=new RegExp(r.sFieldBoundary,"g");var w=this._fnColumnTargets(r.mColumns);var B=(typeof r.bSelectedOnly!="undefined")?r.bSelectedOnly:false;if(r.bHeader){n=[];for(A=0,y=x.aoColumns.length;A<y;A++){if(w[A]){l=x.aoColumns[A].sTitle.replace(/\n/g," ").replace(/<.*?>/g,"").replace(/^\s+|\s+$/g,"");l=this._fnHtmlDecode(l);n.push(this._fnBoundData(l,r.sFieldBoundary,q))}}p.push(n.join(r.sFieldSeperator))}var C=this.fnGetSelected();B=this.s.select.type!=="none"&&B&&C.length!==0;var s=x.oInstance.$("tr",r.oSelectorOpts).map(function(F,E){return B&&k.inArray(E,C)===-1?null:x.oInstance.fnGetPosition(E)}).get();for(z=0,D=s.length;z<D;z++){o=x.aoData[s[z]].nTr;n=[];for(A=0,y=x.aoColumns.length;A<y;A++){if(w[A]){var v=x.oApi._fnGetCellData(x,s[z],A,"display");if(r.fnCellRender){l=r.fnCellRender(v,A,o,s[z])+""}else{if(typeof v=="string"){l=v.replace(/\n/g," ");l=l.replace(/<img.*?\s+alt\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+)).*?>/gi,"$1$2$3");l=l.replace(/<.*?>/g,"")}else{l=v+""}}l=l.replace(/^\s+/,"").replace(/\s+$/,"");l=this._fnHtmlDecode(l);n.push(this._fnBoundData(l,r.sFieldBoundary,q))}}p.push(n.join(r.sFieldSeperator));if(r.bOpenRows){m=k.grep(x.aoOpenRows,function(E){return E.nParent===o});if(m.length===1){l=this._fnBoundData(k("td",m[0].nTr).html(),r.sFieldBoundary,q);p.push(l)}}}if(r.bFooter&&x.nTFoot!==null){n=[];for(A=0,y=x.aoColumns.length;A<y;A++){if(w[A]&&x.aoColumns[A].nTf!==null){l=x.aoColumns[A].nTf.innerHTML.replace(/\n/g," ").replace(/<.*?>/g,"");l=this._fnHtmlDecode(l);n.push(this._fnBoundData(l,r.sFieldBoundary,q))}}p.push(n.join(r.sFieldSeperator))}var t=p.join(this._fnNewline(r));return t},_fnBoundData:function(l,n,m){if(n===""){return l}else{return n+l.replace(m,n+n)+n}},_fnChunkData:function(l,n){var o=[];var p=l.length;for(var m=0;m<p;m+=n){if(m+n<p){o.push(l.substring(m,m+n))}else{o.push(l.substring(m,p))}}return o},_fnHtmlDecode:function(l){if(l.indexOf("&")===-1){return l}var m=i.createElement("div");return l.replace(/&([^\s]*);/g,function(n,o){if(n.substr(1,1)==="#"){return String.fromCharCode(Number(o.substr(1)))}else{m.innerHTML=n;return m.childNodes[0].nodeValue}})},_fnPrintStart:function(q){var p=this;var n=this.s.dt;this._fnPrintHideNodes(n.nTable);this.s.print.saveStart=n._iDisplayStart;this.s.print.saveLength=n._iDisplayLength;if(q.bShowAll){n._iDisplayStart=0;n._iDisplayLength=-1;if(n.oApi._fnCalculateEnd){n.oApi._fnCalculateEnd(n)}n.oApi._fnDraw(n)}if(n.oScroll.sX!==""||n.oScroll.sY!==""){this._fnPrintScrollStart(n);k(this.s.dt.nTable).bind("draw.DTTT_Print",function(){p._fnPrintScrollStart(n)})}var m=n.aanFeatures;for(var r in m){if(r!="i"&&r!="t"&&r.length==1){for(var o=0,l=m[r].length;o<l;o++){this.dom.print.hidden.push({node:m[r][o],display:"block"});m[r][o].style.display="none"}}}k(i.body).addClass(this.classes.print.body);if(q.sInfo!==""){this.fnInfo(q.sInfo,3000)}if(q.sMessage){k("<div/>").addClass(this.classes.print.message).html(q.sMessage).prepend("body")}this.s.print.saveScroll=k(j).scrollTop();j.scrollTo(0,0);k(i).bind("keydown.DTTT",function(s){if(s.keyCode==27){s.preventDefault();p._fnPrintEnd.call(p,s)}})},_fnPrintEnd:function(p){var n=this;var l=this.s.dt;var o=this.s.print;var m=this.dom.print;this._fnPrintShowNodes();if(l.oScroll.sX!==""||l.oScroll.sY!==""){k(this.s.dt.nTable).unbind("draw.DTTT_Print");this._fnPrintScrollEnd()}j.scrollTo(0,o.saveScroll);if(m.message!==null){i.body.removeChild(m.message);m.message=null}k(i.body).removeClass("DTTT_Print");l._iDisplayStart=o.saveStart;l._iDisplayLength=o.saveLength;if(l.oApi._fnCalculateEnd){l.oApi._fnCalculateEnd(l)}l.oApi._fnDraw(l);k(i).unbind("keydown.DTTT")},_fnPrintScrollStart:function(){var n=this.s.dt,p=n.nScrollHead.getElementsByTagName("div")[0],l=p.getElementsByTagName("table")[0],q=n.nTable.parentNode,m,o;m=n.nTable.getElementsByTagName("thead");if(m.length>0){n.nTable.removeChild(m[0])}if(n.nTFoot!==null){o=n.nTable.getElementsByTagName("tfoot");if(o.length>0){n.nTable.removeChild(o[0])}}m=n.nTHead.cloneNode(true);n.nTable.insertBefore(m,n.nTable.childNodes[0]);if(n.nTFoot!==null){o=n.nTFoot.cloneNode(true);n.nTable.insertBefore(o,n.nTable.childNodes[1])}if(n.oScroll.sX!==""){n.nTable.style.width=k(n.nTable).outerWidth()+"px";q.style.width=k(n.nTable).outerWidth()+"px";q.style.overflow="visible"}if(n.oScroll.sY!==""){q.style.height=k(n.nTable).outerHeight()+"px";q.style.overflow="visible"}},_fnPrintScrollEnd:function(){var l=this.s.dt,m=l.nTable.parentNode;if(l.oScroll.sX!==""){m.style.width=l.oApi._fnStringToCss(l.oScroll.sX);m.style.overflow="auto"}if(l.oScroll.sY!==""){m.style.height=l.oApi._fnStringToCss(l.oScroll.sY);m.style.overflow="auto"}},_fnPrintShowNodes:function(){var n=this.dom.print.hidden;for(var m=0,l=n.length;m<l;m++){n[m].node.style.display=n[m].display}n.splice(0,n.length)},_fnPrintHideNodes:function(m){var o=this.dom.print.hidden;var q=m.parentNode;var r=q.childNodes;for(var n=0,l=r.length;n<l;n++){if(r[n]!=m&&r[n].nodeType==1){var p=k(r[n]).css("display");if(p!="none"){o.push({node:r[n],display:p});r[n].style.display="none"}}}if(q.nodeName.toUpperCase()!="BODY"){this._fnPrintHideNodes(q)}}};h._aInstances=[];h._aListeners=[];h.fnGetMasters=function(){var m=[];for(var n=0,l=h._aInstances.length;n<l;n++){if(h._aInstances[n].s.master){m.push(h._aInstances[n])}}return m};h.fnGetInstance=function(n){if(typeof n!="object"){n=i.getElementById(n)}for(var m=0,l=h._aInstances.length;m<l;m++){if(h._aInstances[m].s.master&&h._aInstances[m].dom.table==n){return h._aInstances[m]}}return null};h._fnEventListen=function(n,m,l){h._aListeners.push({that:n,type:m,fn:l})};h._fnEventDispatch=function(r,p,q,o){var n=h._aListeners;for(var m=0,l=n.length;m<l;m++){if(r.dom.table==n[m].that.dom.table&&n[m].type==p){n[m].fn(q,o)}}};h.buttonBase={sAction:"text",sTag:"default",sLinerTag:"default",sButtonClass:"DTTT_button_text",sButtonText:"Button text",sTitle:"",sToolTip:"",sCharSet:"utf8",bBomInc:false,sFileName:"*.csv",sFieldBoundary:"",sFieldSeperator:"\t",sNewLine:"auto",mColumns:"all",bHeader:true,bFooter:true,bOpenRows:false,bSelectedOnly:false,oSelectorOpts:d,fnMouseover:null,fnMouseout:null,fnClick:null,fnSelect:null,fnComplete:null,fnInit:null,fnCellRender:null};h.BUTTONS={csv:k.extend({},h.buttonBase,{sAction:"flash_save",sButtonClass:"DTTT_button_csv",sButtonText:"CSV",sFieldBoundary:'"',sFieldSeperator:",",fnClick:function(m,n,l){this.fnSetText(l,this.fnGetTableData(n))}}),xls:k.extend({},h.buttonBase,{sAction:"flash_save",sCharSet:"utf16le",bBomInc:true,sButtonClass:"DTTT_button_xls",sButtonText:"Excel",fnClick:function(m,n,l){this.fnSetText(l,this.fnGetTableData(n))}}),copy:k.extend({},h.buttonBase,{sAction:"flash_copy",sButtonClass:"DTTT_button_copy",sButtonText:"Copy",fnClick:function(m,n,l){this.fnSetText(l,this.fnGetTableData(n))},fnComplete:function(p,q,o,r){var m=r.split("\n").length,l=this.s.dt.nTFoot===null?m-1:m-2,n=(l==1)?"":"s";this.fnInfo("<h6>Table copied</h6><p>Copied "+l+" row"+n+" to the clipboard.</p>",1500)}}),pdf:k.extend({},h.buttonBase,{sAction:"flash_pdf",sNewLine:"\n",sFileName:"*.pdf",sButtonClass:"DTTT_button_pdf",sButtonText:"PDF",sPdfOrientation:"portrait",sPdfSize:"A4",sPdfMessage:"",fnClick:function(m,n,l){this.fnSetText(l,"title:"+this.fnGetTitle(n)+"\nmessage:"+n.sPdfMessage+"\ncolWidth:"+this.fnCalcColRatios(n)+"\norientation:"+n.sPdfOrientation+"\nsize:"+n.sPdfSize+"\n--/TableToolsOpts--\n"+this.fnGetTableData(n))}}),print:k.extend({},h.buttonBase,{sInfo:"<h6>Print view</h6><p>Please use your browser's print function to print this table. Press escape when finished.</p>",sMessage:null,bShowAll:true,sToolTip:"View print view",sButtonClass:"DTTT_button_print",sButtonText:"Print",fnClick:function(l,m){this.fnPrint(true,m)}}),text:k.extend({},h.buttonBase),select:k.extend({},h.buttonBase,{sButtonText:"Select button",fnSelect:function(l,m){if(this.fnGetSelected().length!==0){k(l).removeClass(this.classes.buttons.disabled)}else{k(l).addClass(this.classes.buttons.disabled)}},fnInit:function(l,m){k(l).addClass(this.classes.buttons.disabled)}}),select_single:k.extend({},h.buttonBase,{sButtonText:"Select button",fnSelect:function(m,n){var l=this.fnGetSelected().length;if(l==1){k(m).removeClass(this.classes.buttons.disabled)}else{k(m).addClass(this.classes.buttons.disabled)}},fnInit:function(l,m){k(l).addClass(this.classes.buttons.disabled)}}),select_all:k.extend({},h.buttonBase,{sButtonText:"Select all",fnClick:function(l,m){this.fnSelectAll()},fnSelect:function(l,m){if(this.fnGetSelected().length==this.s.dt.fnRecordsDisplay()){k(l).addClass(this.classes.buttons.disabled)}else{k(l).removeClass(this.classes.buttons.disabled)}}}),select_none:k.extend({},h.buttonBase,{sButtonText:"Deselect all",fnClick:function(l,m){this.fnSelectNone()},fnSelect:function(l,m){if(this.fnGetSelected().length!==0){k(l).removeClass(this.classes.buttons.disabled)}else{k(l).addClass(this.classes.buttons.disabled)}},fnInit:function(l,m){k(l).addClass(this.classes.buttons.disabled)}}),ajax:k.extend({},h.buttonBase,{sAjaxUrl:"/xhr.php",sButtonText:"Ajax button",fnClick:function(m,n){var l=this.fnGetTableData(n);k.ajax({url:n.sAjaxUrl,data:[{name:"tableData",value:l}],success:n.fnAjaxComplete,dataType:"json",type:"POST",cache:false,error:function(){alert("Error detected when sending table data to server")}})},fnAjaxComplete:function(l){alert("Ajax complete")}}),div:k.extend({},h.buttonBase,{sAction:"div",sTag:"div",sButtonClass:"DTTT_nonbutton",sButtonText:"Text button"}),collection:k.extend({},h.buttonBase,{sAction:"collection",sButtonClass:"DTTT_button_collection",sButtonText:"Collection",fnClick:function(l,m){this._fnCollectionShow(l,m)}})};h.buttons=h.BUTTONS;h.classes={container:"DTTT_container",buttons:{normal:"DTTT_button",disabled:"DTTT_disabled"},collection:{container:"DTTT_collection",background:"DTTT_collection_background",buttons:{normal:"DTTT_button",disabled:"DTTT_disabled"}},select:{table:"DTTT_selectable",row:"DTTT_selected selected"},print:{body:"DTTT_Print",info:"DTTT_print_info",message:"DTTT_PrintMessage"}};h.classes_themeroller={container:"DTTT_container ui-buttonset ui-buttonset-multi",buttons:{normal:"DTTT_button ui-button ui-state-default"},collection:{container:"DTTT_collection ui-buttonset ui-buttonset-multi"}};h.DEFAULTS={sSwfPath:"../swf/copy_csv_xls_pdf.swf",sRowSelect:"none",sSelectedClass:null,fnPreRowSelect:null,fnRowSelected:null,fnRowDeselected:null,aButtons:["copy","csv","xls","pdf","print"],oTags:{container:"div",button:"a",liner:"span",collection:{container:"div",button:"a",liner:"span"}}};h.defaults=h.DEFAULTS;h.prototype.CLASS="TableTools";h.version="2.2.0-dev";if(k.fn.dataTable.Api){k.fn.dataTable.Api.register("tabletools()",function(){var l=null;if(this.context.length>0){l=h.fnGetInstance(this.context[0].nTable)}return l})}if(typeof k.fn.dataTable=="function"&&typeof k.fn.dataTableExt.fnVersionCheck=="function"&&k.fn.dataTableExt.fnVersionCheck("1.9.0")){k.fn.dataTableExt.aoFeatures.push({fnInit:function(o){var n=o.oInit;var m=n.tableTools||n.oTableTools||{};var l=new h(o.oInstance,m);h._aInstances.push(l);return l.dom.container},cFeature:"T",sFeature:"TableTools"})}else{alert("Warning: TableTools requires DataTables 1.9.0 or newer - www.datatables.net/download")}k.fn.DataTable.TableTools=h})(jQuery,c,a);if(typeof g.fn.dataTable=="function"&&typeof g.fn.dataTableExt.fnVersionCheck=="function"&&g.fn.dataTableExt.fnVersionCheck("1.9.0")){g.fn.dataTableExt.aoFeatures.push({fnInit:function(k){var j=typeof k.oInit.oTableTools!="undefined"?k.oInit.oTableTools:{};var i=new h(k.oInstance,j);h._aInstances.push(i);return i.dom.container},cFeature:"T",sFeature:"TableTools"})}else{alert("Warning: TableTools 2 requires DataTables 1.9.0 or newer - www.datatables.net/download")}g.fn.dataTable.TableTools=h;g.fn.DataTable.TableTools=h;return h};b(jQuery,jQuery.fn.dataTable)})(window,document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-tableTools.min.js
jquery-dataTables-tableTools.min.js
/* * File: jquery.dataTables.columnFilter.js * Version: 1.5.3. * Author: Jovan Popovic * * Copyright 2011-2014 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. * * Parameters:" * @sPlaceHolder String Place where inline filtering function should be placed ("tfoot", "thead:before", "thead:after"). Default is "tfoot" * @sRangeSeparator String Separator that will be used when range values are sent to the server-side. Default value is "~". * @sRangeFormat string Default format of the From ... to ... range inputs. Default is From {from} to {to} * @aoColumns Array Array of the filter settings that will be applied on the columns */ (function ($) { $.fn.columnFilter = function (options) { var asInitVals, i, label, th; //var sTableId = "table"; var sRangeFormat = "From {from} to {to}"; //Array of the functions that will override sSearch_ parameters var afnSearch_ = new Array(); var aiCustomSearch_Indexes = new Array(); var oFunctionTimeout = null; var fnOnFiltered = function () { }; function _fnGetColumnValues(oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty) { ///<summary> ///Return values in the column ///</summary> ///<param name="oSettings" type="Object">DataTables settings</param> ///<param name="iColumn" type="int">Id of the column</param> ///<param name="bUnique" type="bool">Return only distinct values</param> ///<param name="bFiltered" type="bool">Return values only from the filtered rows</param> ///<param name="bIgnoreEmpty" type="bool">Ignore empty cells</param> // check that we have a column id if (typeof iColumn == "undefined") return new Array(); // by default we only wany unique data if (typeof bUnique == "undefined") bUnique = true; // by default we do want to only look at filtered data if (typeof bFiltered == "undefined") bFiltered = true; // by default we do not wany to include empty values if (typeof bIgnoreEmpty == "undefined") bIgnoreEmpty = true; // list of rows which we're going to loop through var aiRows; // use only filtered rows if (bFiltered == true) aiRows = oSettings.aiDisplay; // use all rows else aiRows = oSettings.aiDisplayMaster; // all row numbers // set up data array var asResultData = new Array(); for (var i = 0, c = aiRows.length; i < c; i++) { var iRow = aiRows[i]; var aData = oTable.fnGetData(iRow); var sValue = aData[iColumn]; // ignore empty values? if (bIgnoreEmpty == true && sValue.length == 0) continue; // ignore unique values? else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue; // else push the value onto the result data array else asResultData.push(sValue); } return asResultData.sort(); } function _fnColumnIndex(iColumnIndex) { if (properties.bUseColVis) return iColumnIndex; else return oTable.fnSettings().oApi._fnVisibleToColumnIndex(oTable.fnSettings(), iColumnIndex); //return iColumnIndex; //return oTable.fnSettings().oApi._fnColumnIndexToVisible(oTable.fnSettings(), iColumnIndex); } function fnCreateInput(oTable, regex, smart, bIsNumber, iFilterLength, iMaxLenght) { var sCSSClass = "text_filter"; if (bIsNumber) sCSSClass = "number_filter"; label = label.replace(/(^\s*)|(\s*$)/g, ""); var currentFilter = oTable.fnSettings().aoPreSearchCols[i].sSearch; var search_init = 'search_init '; var inputvalue = label; if (currentFilter != '' && currentFilter != '^') { if (bIsNumber && currentFilter.charAt(0) == '^') inputvalue = currentFilter.substr(1); //ignore trailing ^ else inputvalue = currentFilter; search_init = ''; } var input = $('<input type="text" class="' + search_init + sCSSClass + '" value="' + inputvalue + '" rel="' + i + '"/>'); if (iMaxLenght != undefined && iMaxLenght != -1) { input.attr('maxlength', iMaxLenght); } th.html(input); if (bIsNumber) th.wrapInner('<span class="filter_column filter_number" />'); else th.wrapInner('<span class="filter_column filter_text" />'); asInitVals[i] = label; var index = i; if (bIsNumber && !oTable.fnSettings().oFeatures.bServerSide) { input.keyup(function () { /* Filter on the column all numbers that starts with the entered value */ oTable.fnFilter('^' + this.value, _fnColumnIndex(index), true, false); //Issue 37 fnOnFiltered(); }); } else { input.keyup(function () { if (oTable.fnSettings().oFeatures.bServerSide && iFilterLength != 0) { //If filter length is set in the server-side processing mode //Check has the user entered at least iFilterLength new characters var currentFilter = oTable.fnSettings().aoPreSearchCols[index].sSearch; var iLastFilterLength = $(this).data("dt-iLastFilterLength"); if (typeof iLastFilterLength == "undefined") iLastFilterLength = 0; var iCurrentFilterLength = this.value.length; if (Math.abs(iCurrentFilterLength - iLastFilterLength) < iFilterLength //&& currentFilter.length == 0 //Why this? ) { //Cancel the filtering return; } else { //Remember the current filter length $(this).data("dt-iLastFilterLength", iCurrentFilterLength); } } /* Filter on the column (the index) of this element */ oTable.fnFilter(this.value, _fnColumnIndex(index), regex, smart); //Issue 37 fnOnFiltered(); }); } input.focus(function () { if ($(this).hasClass("search_init")) { $(this).removeClass("search_init"); this.value = ""; } }); input.blur(function () { if (this.value == "") { $(this).addClass("search_init"); this.value = asInitVals[index]; } }); } function fnCreateRangeInput(oTable) { //var currentFilter = oTable.fnSettings().aoPreSearchCols[i].sSearch; th.html(_fnRangeLabelPart(0)); var sFromId = oTable.attr("id") + '_range_from_' + i; var from = $('<input type="text" class="number_range_filter" id="' + sFromId + '" rel="' + i + '"/>'); th.append(from); th.append(_fnRangeLabelPart(1)); var sToId = oTable.attr("id") + '_range_to_' + i; var to = $('<input type="text" class="number_range_filter" id="' + sToId + '" rel="' + i + '"/>'); th.append(to); th.append(_fnRangeLabelPart(2)); th.wrapInner('<span class="filter_column filter_number_range" />'); var index = i; aiCustomSearch_Indexes.push(i); //------------start range filtering function /* Custom filtering function which will filter data in column four between two values * Author: Allan Jardine, Modified by Jovan Popovic */ //$.fn.dataTableExt.afnFiltering.push( oTable.dataTableExt.afnFiltering.push( function (oSettings, aData, iDataIndex) { if (oTable.attr("id") != oSettings.sTableId) return true; // Try to handle missing nodes more gracefully if (document.getElementById(sFromId) == null) return true; var iMin = document.getElementById(sFromId).value * 1; var iMax = document.getElementById(sToId).value * 1; var iValue = aData[_fnColumnIndex(index)] == "-" ? 0 : aData[_fnColumnIndex(index)] * 1; if (iMin == "" && iMax == "") { return true; } else if (iMin == "" && iValue <= iMax) { return true; } else if (iMin <= iValue && "" == iMax) { return true; } else if (iMin <= iValue && iValue <= iMax) { return true; } return false; } ); //------------end range filtering function $('#' + sFromId + ',#' + sToId, th).keyup(function () { var iMin = document.getElementById(sFromId).value * 1; var iMax = document.getElementById(sToId).value * 1; if (iMin != 0 && iMax != 0 && iMin > iMax) return; oTable.fnDraw(); fnOnFiltered(); }); } function fnCreateDateRangeInput(oTable) { var aoFragments = sRangeFormat.split(/[}{]/); th.html(""); //th.html(_fnRangeLabelPart(0)); var sFromId = oTable.attr("id") + '_range_from_' + i; var from = $('<input type="text" class="date_range_filter" id="' + sFromId + '" rel="' + i + '"/>'); from.datepicker(); //th.append(from); //th.append(_fnRangeLabelPart(1)); var sToId = oTable.attr("id") + '_range_to_' + i; var to = $('<input type="text" class="date_range_filter" id="' + sToId + '" rel="' + i + '"/>'); //th.append(to); //th.append(_fnRangeLabelPart(2)); for (ti = 0; ti < aoFragments.length; ti++) { if (aoFragments[ti] == properties.sDateFromToken) { th.append(from); } else { if (aoFragments[ti] == properties.sDateToToken) { th.append(to); } else { th.append(aoFragments[ti]); } } } th.wrapInner('<span class="filter_column filter_date_range" />'); to.datepicker(); var index = i; aiCustomSearch_Indexes.push(i); //------------start date range filtering function //$.fn.dataTableExt.afnFiltering.push( oTable.dataTableExt.afnFiltering.push( function (oSettings, aData, iDataIndex) { if (oTable.attr("id") != oSettings.sTableId) return true; var dStartDate = from.datepicker("getDate"); var dEndDate = to.datepicker("getDate"); if (dStartDate == null && dEndDate == null) { return true; } var dCellDate = null; try { if (aData[_fnColumnIndex(index)] == null || aData[_fnColumnIndex(index)] == "") return false; dCellDate = $.datepicker.parseDate($.datepicker.regional[""].dateFormat, aData[_fnColumnIndex(index)]); } catch (ex) { return false; } if (dCellDate == null) return false; if (dStartDate == null && dCellDate <= dEndDate) { return true; } else if (dStartDate <= dCellDate && dEndDate == null) { return true; } else if (dStartDate <= dCellDate && dCellDate <= dEndDate) { return true; } return false; } ); //------------end date range filtering function $('#' + sFromId + ',#' + sToId, th).change(function () { oTable.fnDraw(); fnOnFiltered(); }); } function fnCreateColumnSelect(oTable, aData, iColumn, nTh, sLabel, bRegex, oSelected) { if (aData == null) aData = _fnGetColumnValues(oTable.fnSettings(), iColumn, true, false, true); var index = iColumn; var currentFilter = oTable.fnSettings().aoPreSearchCols[i].sSearch; if (currentFilter == null || currentFilter == "")//Issue 81 currentFilter = oSelected; var r = '<select class="search_init select_filter" rel="' + i + '"><option value="" class="search_init">' + sLabel + '</option>'; var j = 0; var iLen = aData.length; for (j = 0; j < iLen; j++) { if (typeof (aData[j]) != 'object') { var selected = ''; if (escape(aData[j]) == currentFilter || escape(aData[j]) == escape(currentFilter) ) selected = 'selected ' r += '<option ' + selected + ' value="' + escape(aData[j]) + '">' + aData[j] + '</option>'; } else { var selected = ''; if (bRegex) { //Do not escape values if they are explicitely set to avoid escaping special characters in the regexp if (aData[j].value == currentFilter) selected = 'selected '; r += '<option ' + selected + 'value="' + aData[j].value + '">' + aData[j].label + '</option>'; } else { if (escape(aData[j].value) == currentFilter) selected = 'selected '; r += '<option ' + selected + 'value="' + escape(aData[j].value) + '">' + aData[j].label + '</option>'; } } } var select = $(r + '</select>'); nTh.html(select); nTh.wrapInner('<span class="filter_column filter_select" />'); select.change(function () { //var val = $(this).val(); if ($(this).val() != "") { $(this).removeClass("search_init"); } else { $(this).addClass("search_init"); } if (bRegex) oTable.fnFilter($(this).val(), iColumn, bRegex); //Issue 41 else oTable.fnFilter(unescape($(this).val()), iColumn); //Issue 25 fnOnFiltered(); }); if (currentFilter != null && currentFilter != "")//Issue 81 oTable.fnFilter(unescape(currentFilter), iColumn); } function fnCreateSelect(oTable, aData, bRegex, oSelected) { var oSettings = oTable.fnSettings(); if (aData == null && oSettings.sAjaxSource != "" && !oSettings.oFeatures.bServerSide) { // Add a function to the draw callback, which will check for the Ajax data having // been loaded. Use a closure for the individual column elements that are used to // built the column filter, since 'i' and 'th' (etc) are locally "global". oSettings.aoDrawCallback.push({ "fn": (function (iColumn, nTh, sLabel) { return function () { // Only rebuild the select on the second draw - i.e. when the Ajax // data has been loaded. if (oSettings.iDraw == 2 && oSettings.sAjaxSource != null && oSettings.sAjaxSource != "" && !oSettings.oFeatures.bServerSide) { return fnCreateColumnSelect(oTable, null, _fnColumnIndex(iColumn), nTh, sLabel, bRegex, oSelected); //Issue 37 } }; })(i, th, label), "sName": "column_filter_" + i }); } // Regardless of the Ajax state, build the select on first pass fnCreateColumnSelect(oTable, aData, _fnColumnIndex(i), th, label, bRegex, oSelected); //Issue 37 } function fnCreateDropdown(aData) { var index = i; var r = '<div class="dropdown select_filter"><a class="dropdown-toggle" data-toggle="dropdown" href="#">' + label + '<b class="caret"></b></a><ul class="dropdown-menu" role="menu"><li data-value=""><a>Show All</a></li>', j, iLen = aData.length; for (j = 0; j < iLen; j++) { r += '<li data-value="' + aData[j] + '"><a>' + aData[j] + '</a></li>'; } var select = $(r + '</ul></div>'); th.html(select); th.wrapInner('<span class="filterColumn filter_select" />'); select.find('li').click(function () { oTable.fnFilter($(this).data('value'), index); }); } function fnCreateCheckbox(oTable, aData) { if (aData == null) aData = _fnGetColumnValues(oTable.fnSettings(), i, true, true, true); var index = i; var r = '', j, iLen = aData.length; //clean the string var localLabel = label.replace('%', 'Perc').replace("&", "AND").replace("$", "DOL").replace("£", "STERL").replace("@", "AT").replace(/\s/g, "_"); localLabel = localLabel.replace(/[^a-zA-Z 0-9]+/g, ''); //clean the string //button label override var labelBtn = label; if (properties.sFilterButtonText != null || properties.sFilterButtonText != undefined) { labelBtn = properties.sFilterButtonText; } var relativeDivWidthToggleSize = 10; var numRow = 12; //numero di checkbox per colonna var numCol = Math.floor(iLen / numRow); if (iLen % numRow > 0) { numCol = numCol + 1; } ; //count how many column should be generated and split the div size var divWidth = 100 / numCol - 2; var divWidthToggle = relativeDivWidthToggleSize * numCol; if (numCol == 1) { divWidth = 20; } var divRowDef = '<div style="float:left; min-width: ' + divWidth + '%; " >'; var divClose = '</div>'; var uniqueId = oTable.attr("id") + localLabel; var buttonId = "chkBtnOpen" + uniqueId; var checkToggleDiv = uniqueId + "-flt-toggle"; r += '<button id="' + buttonId + '" class="checkbox_filter" > ' + labelBtn + '</button>'; //filter button witch open dialog r += '<div id="' + checkToggleDiv + '" ' + 'title="' + label + '" ' + 'rel="' + i + '" ' + 'class="toggle-check ui-widget-content ui-corner-all" style="width: ' + (divWidthToggle) + '%; " >'; //dialog div //r+= '<div align="center" style="margin-top: 5px; "> <button id="'+buttonId+'Reset" class="checkbox_filter" > reset </button> </div>'; //reset button and its div r += divRowDef; for (j = 0; j < iLen; j++) { //if last check close div if (j % numRow == 0 && j != 0) { r += divClose + divRowDef; } var sLabel = aData[j]; var sValue = aData[j]; if (typeof (aData[j]) == 'object') { sLabel = aData[j].label; sValue = aData[j].value; } //check button r += '<input class="search_init checkbox_filter" type="checkbox" id= "' + uniqueId + '_cb_' + sValue + '" name= "' + localLabel + '" value="' + sValue + '" >' + sLabel + '<br/>'; var checkbox = $(r); th.html(checkbox); th.wrapInner('<span class="filter_column filter_checkbox" />'); //on every checkbox selection checkbox.change(function () { var search = ''; var or = '|'; //var for select checks in 'or' into the regex var resSize = $('input:checkbox[name="' + localLabel + '"]:checked').size(); $('input:checkbox[name="' + localLabel + '"]:checked').each(function (index) { //search = search + ' ' + $(this).val(); //concatenation for selected checks in or if ((index == 0 && resSize == 1) || (index != 0 && index == resSize - 1)) { or = ''; } //trim search = search.replace(/^\s+|\s+$/g, ""); search = search + $(this).val() + or; or = '|'; }); if (search != "") { $('input:checkbox[name="' + localLabel + '"]').removeClass("search_init"); } else { $('input:checkbox[name="' + localLabel + '"]').addClass("search_init"); } /* Old code for setting search_init CSS class on checkboxes if any of them is checked for (var jj = 0; jj < iLen; jj++) { if (search != "") { $('#' + aData[jj]).removeClass("search_init"); } else { $('#' + aData[jj]).addClass("search_init"); } } */ //execute search oTable.fnFilter(search, index, true, false); fnOnFiltered(); }); } //filter button $('#' + buttonId).button(); //dialog $('#' + checkToggleDiv).dialog({ //height: 140, autoOpen: false, //show: "blind", hide: "blind", buttons: [ { text: "Reset", click: function () { //$('#'+buttonId).removeClass("filter_selected"); //LM remove border if filter selected $('input:checkbox[name="' + localLabel + '"]:checked').each(function (index3) { $(this).attr('checked', false); $(this).addClass("search_init"); }); oTable.fnFilter('', index, true, false); fnOnFiltered(); return false; } }, { text: "Close", click: function () { $(this).dialog("close"); } } ] }); $('#' + buttonId).click(function () { $('#' + checkToggleDiv).dialog('open'); var target = $(this); $('#' + checkToggleDiv).dialog("widget").position({ my: 'top', at: 'bottom', of: target }); return false; }); var fnOnFilteredCurrent = fnOnFiltered; fnOnFiltered = function () { var target = $('#' + buttonId); $('#' + checkToggleDiv).dialog("widget").position({ my: 'top', at: 'bottom', of: target }); fnOnFilteredCurrent(); }; //reset /* $('#'+buttonId+"Reset").button(); $('#'+buttonId+"Reset").click(function(){ $('#'+buttonId).removeClass("filter_selected"); //LM remove border if filter selected $('input:checkbox[name="'+localLabel+'"]:checked').each(function(index3) { $(this).attr('checked', false); $(this).addClass("search_init"); }); oTable.fnFilter('', index, true, false); return false; }); */ } function _fnRangeLabelPart(iPlace) { switch (iPlace) { case 0: return sRangeFormat.substring(0, sRangeFormat.indexOf("{from}")); case 1: return sRangeFormat.substring(sRangeFormat.indexOf("{from}") + 6, sRangeFormat.indexOf("{to}")); default: return sRangeFormat.substring(sRangeFormat.indexOf("{to}") + 4); } } var oTable = this; var defaults = { sPlaceHolder: "foot", sRangeSeparator: "~", iFilteringDelay: 500, aoColumns: null, sRangeFormat: "From {from} to {to}", sDateFromToken: "from", sDateToToken: "to" }; var properties = $.extend(defaults, options); return this.each(function () { if (!oTable.fnSettings().oFeatures.bFilter) return; asInitVals = new Array(); var aoFilterCells = oTable.fnSettings().aoFooter[0]; var oHost = oTable.fnSettings().nTFoot; //Before fix for ColVis var sFilterRow = "tr"; //Before fix for ColVis if (properties.sPlaceHolder == "head:after") { var tr = $("tr:first", oTable.fnSettings().nTHead).detach(); //tr.appendTo($(oTable.fnSettings().nTHead)); if (oTable.fnSettings().bSortCellsTop) { tr.prependTo($(oTable.fnSettings().nTHead)); //tr.appendTo($("thead", oTable)); aoFilterCells = oTable.fnSettings().aoHeader[1]; } else { tr.appendTo($(oTable.fnSettings().nTHead)); //tr.prependTo($("thead", oTable)); aoFilterCells = oTable.fnSettings().aoHeader[0]; } sFilterRow = "tr:last"; oHost = oTable.fnSettings().nTHead; } else if (properties.sPlaceHolder == "head:before") { if (oTable.fnSettings().bSortCellsTop) { var tr = $("tr:first", oTable.fnSettings().nTHead).detach(); tr.appendTo($(oTable.fnSettings().nTHead)); aoFilterCells = oTable.fnSettings().aoHeader[1]; } else { aoFilterCells = oTable.fnSettings().aoHeader[0]; } /*else { //tr.prependTo($("thead", oTable)); sFilterRow = "tr:first"; }*/ sFilterRow = "tr:first"; oHost = oTable.fnSettings().nTHead; } //$(sFilterRow + " th", oHost).each(function (index) {//bug with ColVis $(aoFilterCells).each(function (index) {//fix for ColVis i = index; var aoColumn = { type: "text", bRegex: false, bSmart: true, iMaxLenght: -1, iFilterLength: 0 }; if (properties.aoColumns != null) { if (properties.aoColumns.length < i || properties.aoColumns[i] == null) return; aoColumn = properties.aoColumns[i]; } //label = $(this).text(); //Before fix for ColVis label = $($(this)[0].cell).text(); //Fix for ColVis if (aoColumn.sSelector == null) { //th = $($(this)[0]);//Before fix for ColVis th = $($(this)[0].cell); //Fix for ColVis } else { th = $(aoColumn.sSelector); if (th.length == 0) th = $($(this)[0].cell); } if (aoColumn != null) { if (aoColumn.sRangeFormat != null) sRangeFormat = aoColumn.sRangeFormat; else sRangeFormat = properties.sRangeFormat; switch (aoColumn.type) { case "null": break; case "number": fnCreateInput(oTable, true, false, true, aoColumn.iFilterLength, aoColumn.iMaxLenght); break; case "select": if (aoColumn.bRegex != true) aoColumn.bRegex = false; fnCreateSelect(oTable, aoColumn.values, aoColumn.bRegex, aoColumn.selected); break; case "number-range": fnCreateRangeInput(oTable); break; case "date-range": fnCreateDateRangeInput(oTable); break; case "checkbox": fnCreateCheckbox(oTable, aoColumn.values); break; case "twitter-dropdown": case "dropdown": fnCreateDropdown(aoColumn.values); break; case "text": default: bRegex = (aoColumn.bRegex == null ? false : aoColumn.bRegex); bSmart = (aoColumn.bSmart == null ? false : aoColumn.bSmart); fnCreateInput(oTable, bRegex, bSmart, false, aoColumn.iFilterLength, aoColumn.iMaxLenght); break; } } }); for (j = 0; j < aiCustomSearch_Indexes.length; j++) { //var index = aiCustomSearch_Indexes[j]; var fnSearch_ = function () { var id = oTable.attr("id"); return $("#" + id + "_range_from_" + aiCustomSearch_Indexes[j]).val() + properties.sRangeSeparator + $("#" + id + "_range_to_" + aiCustomSearch_Indexes[j]).val() } afnSearch_.push(fnSearch_); } if (oTable.fnSettings().oFeatures.bServerSide) { var fnServerDataOriginal = oTable.fnSettings().fnServerData; oTable.fnSettings().fnServerData = function (sSource, aoData, fnCallback) { for (j = 0; j < aiCustomSearch_Indexes.length; j++) { var index = aiCustomSearch_Indexes[j]; for (k = 0; k < aoData.length; k++) { if (aoData[k].name == "sSearch_" + index) aoData[k].value = afnSearch_[j](); } } aoData.push({ "name": "sRangeSeparator", "value": properties.sRangeSeparator }); if (fnServerDataOriginal != null) { try { fnServerDataOriginal(sSource, aoData, fnCallback, oTable.fnSettings()); //TODO: See Issue 18 } catch (ex) { fnServerDataOriginal(sSource, aoData, fnCallback); } } else { $.getJSON(sSource, aoData, function (json) { fnCallback(json) }); } }; } }); }; })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-columnFilter.js
jquery-dataTables-columnFilter.js
// AMD support (function($) { "use strict"; /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are mutually exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').on('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); You can also use ajaxForm with delegation (requires jQuery v1.7+), so the form does not have to exist when you invoke ajaxForm: $('#myForm').ajaxForm({ delegation: true, target: '#output' }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * Feature detection */ var feature = {}; feature.fileapi = $("<input type='file'/>").get(0).files !== undefined; feature.formdata = window.FormData !== undefined; var hasProp = !!$.fn.prop; // attr2 uses prop when it can but checks the return type for // an expected string. this accounts for the case where a form // contains inputs with names like "action" or "method"; in those // cases "prop" returns the element $.fn.attr2 = function() { if ( ! hasProp ) { return this.attr.apply(this, arguments); } var val = this.prop.apply(this, arguments); if ( ( val && val.jquery ) || typeof val === 'string' ) { return val; } return this.attr.apply(this, arguments); }; /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { /*jshint scripturl:true */ // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } var method, action, url, $form = this; if (typeof options == 'function') { options = { success: options }; } else if ( options === undefined ) { options = {}; } method = options.type || this.attr2('method'); action = options.url || this.attr2('action'); url = (typeof action === 'string') ? $.trim(action) : ''; url = url || window.location.href || ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: method || $.ajaxSettings.type, iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var traditional = options.traditional; if ( traditional === undefined ) { traditional = $.ajaxSettings.traditional; } var elements = []; var qx, a = this.formToArray(options.semantic, elements); if (options.data) { options.extraData = options.data; qx = $.param(options.data, traditional); } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a, traditional); if (qx) { q = ( q ? (q + '&' + qx) : qx ); } if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(options.includeHidden); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || this ; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; if (options.error) { var oldError = options.error; options.error = function(xhr, status, error) { var context = options.context || this; oldError.apply(context, [xhr, status, error, $form]); }; } if (options.complete) { var oldComplete = options.complete; options.complete = function(xhr, status) { var context = options.context || this; oldComplete.apply(context, [xhr, status, $form]); }; } // are there files to upload? // [value] (issue #113), also see comment: // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219 var fileInputs = $('input[type=file]:enabled', this).filter(function() { return $(this).val() !== ''; }); var hasFileInputs = fileInputs.length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); var fileAPI = feature.fileapi && feature.formdata; log("fileAPI :" + fileAPI); var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; var jqxhr; // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (options.iframe || shouldUseFrame)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, function() { jqxhr = fileUploadIframe(a); }); } else { jqxhr = fileUploadIframe(a); } } else if ((hasFileInputs || multipart) && fileAPI) { jqxhr = fileUploadXhr(a); } else { jqxhr = $.ajax(options); } $form.removeData('jqxhr').data('jqxhr', jqxhr); // clear element array for (var k=0; k < elements.length; k++) { elements[k] = null; } // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // utility fn for deep serialization function deepSerialize(extraData){ var serialized = $.param(extraData, options.traditional).split('&'); var len = serialized.length; var result = []; var i, part; for (i=0; i < len; i++) { // #252; undo param space replacement serialized[i] = serialized[i].replace(/\+/g,' '); part = serialized[i].split('='); // #278; use array instead of object storage, favoring array serializations result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]); } return result; } // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) function fileUploadXhr(a) { var formdata = new FormData(); for (var i=0; i < a.length; i++) { formdata.append(a[i].name, a[i].value); } if (options.extraData) { var serializedData = deepSerialize(options.extraData); for (i=0; i < serializedData.length; i++) { if (serializedData[i]) { formdata.append(serializedData[i][0], serializedData[i][1]); } } } options.data = null; var s = $.extend(true, {}, $.ajaxSettings, options, { contentType: false, processData: false, cache: false, type: method || 'POST' }); if (options.uploadProgress) { // workaround because jqXHR does not expose upload property s.xhr = function() { var xhr = $.ajaxSettings.xhr(); if (xhr.upload) { xhr.upload.addEventListener('progress', function(event) { var percent = 0; var position = event.loaded || event.position; /*event.position is deprecated*/ var total = event.total; if (event.lengthComputable) { percent = Math.ceil(position / total * 100); } options.uploadProgress(event, position, total, percent); }, false); } return xhr; }; } s.data = null; var beforeSend = s.beforeSend; s.beforeSend = function(xhr, o) { //Send FormData() provided by user if (options.formData) { o.data = options.formData; } else { o.data = formdata; } if(beforeSend) { beforeSend.call(this, xhr, o); } }; return $.ajax(s); } // private function for handling file uploads (hat tip to YAHOO!) function fileUploadIframe(a) { var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle; var deferred = $.Deferred(); // #341 deferred.abort = function(status) { xhr.abort(status); }; if (a) { // ensure that every serialized input is still enabled for (i=0; i < elements.length; i++) { el = $(elements[i]); if ( hasProp ) { el.prop('disabled', false); } else { el.removeAttr('disabled'); } } } s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; id = 'jqFormIO' + (new Date().getTime()); if (s.iframeTarget) { $io = $(s.iframeTarget); n = $io.attr2('name'); if (!n) { $io.attr2('name', id); } else { id = n; } } else { $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />'); $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); } io = $io[0]; xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; try { // #214, #257 if (io.contentWindow.document.execCommand) { io.contentWindow.document.execCommand('Stop'); } } catch(ignore) {} $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; if (s.error) { s.error.call(s.context, xhr, e, status); } if (g) { $.event.trigger("ajaxError", [xhr, s, e]); } if (s.complete) { s.complete.call(s.context, xhr, e); } } }; g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && 0 === $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } deferred.reject(); return deferred; } if (xhr.aborted) { deferred.reject(); return deferred; } // add submitting element to data if we know it sub = form.clk; if (sub) { n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } var CLIENT_TIMEOUT_ABORT = 1; var SERVER_ABORT = 2; function getDoc(frame) { /* it looks like contentWindow or contentDocument do not * carry the protocol property in ie8, when running under ssl * frame.document is the only valid response document, since * the protocol is know but not on the other two objects. strange? * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy */ var doc = null; // IE8 cascading access check try { if (frame.contentWindow) { doc = frame.contentWindow.document; } } catch(err) { // IE8 access denied under ssl & missing protocol log('cannot get iframe.contentWindow document: ' + err); } if (doc) { // successful getting content return doc; } try { // simply checking may throw in ie8 under ssl or mismatched protocol doc = frame.contentDocument ? frame.contentDocument : frame.document; } catch(err) { // last attempt log('cannot get iframe.contentDocument: ' + err); doc = frame.document; } return doc; } // Rails CSRF hack (thanks to Yvan Barthelemy) var csrf_token = $('meta[name=csrf-token]').attr('content'); var csrf_param = $('meta[name=csrf-param]').attr('content'); if (csrf_param && csrf_token) { s.extraData = s.extraData || {}; s.extraData[csrf_param] = csrf_token; } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr2('target'), a = $form.attr2('action'), mp = 'multipart/form-data', et = $form.attr('enctype') || $form.attr('encoding') || mp; // update form attrs in IE friendly way form.setAttribute('target',id); if (!method || /post/i.test(method) ) { form.setAttribute('method', 'POST'); } if (a != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride && (!method || /post/i.test(method))) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout); } // look for server aborts function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state && state.toLowerCase() == 'uninitialized') { setTimeout(checkState,50); } } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); if (timeoutHandle) { clearTimeout(timeoutHandle); } timeoutHandle = undefined; } } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { if (s.extraData.hasOwnProperty(n)) { // if using the $.param format that allows for multiple values with the same name if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) { extraInputs.push( $('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value) .appendTo(form)[0]); } else { extraInputs.push( $('<input type="hidden" name="'+n+'">').val(s.extraData[n]) .appendTo(form)[0]); } } } } if (!s.iframeTarget) { // add iframe to doc and submit the form $io.appendTo('body'); } if (io.attachEvent) { io.attachEvent('onload', cb); } else { io.addEventListener('load', cb, false); } setTimeout(checkState,15); try { form.submit(); } catch(err) { // just in case form has element with name/id of 'submit' var submitFn = document.createElement('form').submit; submitFn.apply(form); } } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); form.setAttribute('enctype', et); // #380 if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } doc = getDoc(io); if(!doc) { log('cannot access response document'); e = SERVER_ABORT; } if (e === CLIENT_TIMEOUT_ABORT && xhr) { xhr.abort('timeout'); deferred.reject(xhr, 'timeout'); return; } else if (e == SERVER_ABORT && xhr) { xhr.abort('server abort'); deferred.reject(xhr, 'error', 'server abort'); return; } if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) { return; } } if (io.detachEvent) { io.detachEvent('onload', cb); } else { io.removeEventListener('load', cb, false); } var status = 'success', errMsg; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); var docRoot = doc.body ? doc.body : doc.documentElement; xhr.responseText = docRoot ? docRoot.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (isXml) { s.dataType = 'xml'; } xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header.toLowerCase()]; }; // support for XHR 'status' & 'statusText' emulation : if (docRoot) { xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status; xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText; } var dt = (s.dataType || '').toLowerCase(); var scr = /(json|script|text)/.test(dt); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; // support for XHR 'status' & 'statusText' emulation : xhr.status = Number( ta.getAttribute('status') ) || xhr.status; xhr.statusText = ta.getAttribute('statusText') || xhr.statusText; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent ? pre.textContent : pre.innerText; } else if (b) { xhr.responseText = b.textContent ? b.textContent : b.innerText; } } } else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) { xhr.responseXML = toXml(xhr.responseText); } try { data = httpData(xhr, dt, s); } catch (err) { status = 'parsererror'; xhr.error = errMsg = (err || status); } } catch (err) { log('error caught: ',err); status = 'error'; xhr.error = errMsg = (err || status); } if (xhr.aborted) { log('upload aborted'); status = null; } if (xhr.status) { // we've set xhr.status status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error'; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (status === 'success') { if (s.success) { s.success.call(s.context, data, 'success', xhr); } deferred.resolve(xhr.responseText, 'success', xhr); if (g) { $.event.trigger("ajaxSuccess", [xhr, s]); } } else if (status) { if (errMsg === undefined) { errMsg = xhr.statusText; } if (s.error) { s.error.call(s.context, xhr, status, errMsg); } deferred.reject(xhr, 'error', errMsg); if (g) { $.event.trigger("ajaxError", [xhr, s, errMsg]); } } if (g) { $.event.trigger("ajaxComplete", [xhr, s]); } if (g && ! --$.active) { $.event.trigger("ajaxStop"); } if (s.complete) { s.complete.call(s.context, xhr, status); } callbackProcessed = true; if (s.timeout) { clearTimeout(timeoutHandle); } // clean up setTimeout(function() { if (!s.iframeTarget) { $io.remove(); } else { //adding else to clean up existing iframe response. $io.attr('src', s.iframeSrc); } xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { /*jslint evil:true */ return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { if ($.error) { $.error('parsererror'); } } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; return deferred; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { options = options || {}; options.delegation = options.delegation && $.isFunction($.fn.on); // in jQuery 1.3+ we can fix mistakes with the ready state if (!options.delegation && this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } if ( options.delegation ) { $(document) .off('submit.form-plugin', this.selector, doAjaxSubmit) .off('click.form-plugin', this.selector, captureSubmittingElement) .on('submit.form-plugin', this.selector, options, doAjaxSubmit) .on('click.form-plugin', this.selector, options, captureSubmittingElement); return this; } return this.ajaxFormUnbind() .bind('submit.form-plugin', options, doAjaxSubmit) .bind('click.form-plugin', options, captureSubmittingElement); }; // private event handlers function doAjaxSubmit(e) { /*jshint validthis:true */ var options = e.data; if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(e.target).ajaxSubmit(options); // #365 } } function captureSubmittingElement(e) { /*jshint validthis:true */ var target = e.target; var $el = $(target); if (!($el.is("[type=submit],[type=image]"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest('[type=submit]'); if (t.length === 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX !== undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); } // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic, elements) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var formId = this.attr('id'); var els = semantic ? form.getElementsByTagName('*') : form.elements; var els2; if (els && !/MSIE 8/.test(navigator.userAgent)) { // #390 els = $(els).get(); // convert to standard array } // #386; account for inputs outside the form which use the 'form' attribute if ( formId ) { els2 = $(':input[form=' + formId + ']').get(); if ( els2.length ) { els = (els || []).concat(els2); } } if (!els || !els.length) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n || el.disabled) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(form.clk == el) { a.push({name: n, value: $(el).val(), type: el.type }); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { if (elements) { elements.push(el); } for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (feature.fileapi && el.type == 'file') { if (elements) { elements.push(el); } var files = el.files; if (files.length) { for (j=0; j < files.length; j++) { a.push({name: n, value: files[j], type: el.type}); } } else { // #180 a.push({ name: n, value: '', type: el.type }); } } else if (v !== null && typeof v != 'undefined') { if (elements) { elements.push(el); } a.push({name: n, value: v, type: el.type, required: el.required}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $('input[type=text]').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $('input[type=checkbox]').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $('input[type=radio]').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } if (v.constructor == Array) { $.merge(val, v); } else { val.push(v); } } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes.value && !(op.attributes.value.specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function(includeHidden) { return this.each(function() { $('input,select,textarea', this).clearFields(includeHidden); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function(includeHidden) { var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (re.test(t) || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } else if (t == "file") { if (/MSIE/.test(navigator.userAgent)) { $(this).replaceWith($(this).clone(true)); } else { $(this).val(''); } } else if (includeHidden) { // includeHidden can be the value true, or it can be a selector string // indicating a special test; for example: // $('#myForm').clearForm('.special:hidden') // the above would clean hidden inputs that have the class of 'special' if ( (includeHidden === true && /hidden/.test(t)) || (typeof includeHidden == 'string' && $(this).is(includeHidden)) ) { this.value = ''; } } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // expose debug var $.fn.ajaxSubmit.debug = false; // helper fn for console logging function log() { if (!$.fn.ajaxSubmit.debug) { return; } var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } } })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-form-3.49.js
jquery-form-3.49.js
(function(b,a){if(typeof module==="object"&&typeof module.exports==="object"){module.exports=b.document?a(b,true):function(c){if(!c.document){throw new Error("jQuery requires a window with a document")}return a(c)}}else{a(b)}}(typeof window!=="undefined"?window:this,function(window,noGlobal){var arr=[];var slice=arr.slice;var concat=arr.concat;var push=arr.push;var indexOf=arr.indexOf;var class2type={};var toString=class2type.toString;var hasOwn=class2type.hasOwnProperty;var support={};var document=window.document,version="2.1.3",jQuery=function(selector,context){return new jQuery.fn.init(selector,context)},rtrim=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,rmsPrefix=/^-ms-/,rdashAlpha=/-([\da-z])/gi,fcamelCase=function(all,letter){return letter.toUpperCase()};jQuery.fn=jQuery.prototype={jquery:version,constructor:jQuery,selector:"",length:0,toArray:function(){return slice.call(this)},get:function(num){return num!=null?(num<0?this[num+this.length]:this[num]):slice.call(this)},pushStack:function(elems){var ret=jQuery.merge(this.constructor(),elems);ret.prevObject=this;ret.context=this.context;return ret},each:function(callback,args){return jQuery.each(this,callback,args)},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem)}))},slice:function(){return this.pushStack(slice.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(i){var len=this.length,j=+i+(i<0?len:0);return this.pushStack(j>=0&&j<len?[this[j]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:push,sort:arr.sort,splice:arr.splice};jQuery.extend=jQuery.fn.extend=function(){var options,name,src,copy,copyIsArray,clone,target=arguments[0]||{},i=1,length=arguments.length,deep=false;if(typeof target==="boolean"){deep=target;target=arguments[i]||{};i++}if(typeof target!=="object"&&!jQuery.isFunction(target)){target={}}if(i===length){target=this;i--}for(;i<length;i++){if((options=arguments[i])!=null){for(name in options){src=target[name];copy=options[name];if(target===copy){continue}if(deep&&copy&&(jQuery.isPlainObject(copy)||(copyIsArray=jQuery.isArray(copy)))){if(copyIsArray){copyIsArray=false;clone=src&&jQuery.isArray(src)?src:[]}else{clone=src&&jQuery.isPlainObject(src)?src:{}}target[name]=jQuery.extend(deep,clone,copy)}else{if(copy!==undefined){target[name]=copy}}}}}return target};jQuery.extend({expando:"jQuery"+(version+Math.random()).replace(/\D/g,""),isReady:true,error:function(msg){throw new Error(msg)},noop:function(){},isFunction:function(obj){return jQuery.type(obj)==="function"},isArray:Array.isArray,isWindow:function(obj){return obj!=null&&obj===obj.window},isNumeric:function(obj){return !jQuery.isArray(obj)&&(obj-parseFloat(obj)+1)>=0},isPlainObject:function(obj){if(jQuery.type(obj)!=="object"||obj.nodeType||jQuery.isWindow(obj)){return false}if(obj.constructor&&!hasOwn.call(obj.constructor.prototype,"isPrototypeOf")){return false}return true},isEmptyObject:function(obj){var name;for(name in obj){return false}return true},type:function(obj){if(obj==null){return obj+""}return typeof obj==="object"||typeof obj==="function"?class2type[toString.call(obj)]||"object":typeof obj},globalEval:function(code){var script,indirect=eval;code=jQuery.trim(code);if(code){if(code.indexOf("use strict")===1){script=document.createElement("script");script.text=code;document.head.appendChild(script).parentNode.removeChild(script)}else{indirect(code)}}},camelCase:function(string){return string.replace(rmsPrefix,"ms-").replace(rdashAlpha,fcamelCase)},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toLowerCase()===name.toLowerCase()},each:function(obj,callback,args){var value,i=0,length=obj.length,isArray=isArraylike(obj);if(args){if(isArray){for(;i<length;i++){value=callback.apply(obj[i],args);if(value===false){break}}}else{for(i in obj){value=callback.apply(obj[i],args);if(value===false){break}}}}else{if(isArray){for(;i<length;i++){value=callback.call(obj[i],i,obj[i]);if(value===false){break}}}else{for(i in obj){value=callback.call(obj[i],i,obj[i]);if(value===false){break}}}}return obj},trim:function(text){return text==null?"":(text+"").replace(rtrim,"")},makeArray:function(arr,results){var ret=results||[];if(arr!=null){if(isArraylike(Object(arr))){jQuery.merge(ret,typeof arr==="string"?[arr]:arr)}else{push.call(ret,arr)}}return ret},inArray:function(elem,arr,i){return arr==null?-1:indexOf.call(arr,elem,i)},merge:function(first,second){var len=+second.length,j=0,i=first.length;for(;j<len;j++){first[i++]=second[j]}first.length=i;return first},grep:function(elems,callback,invert){var callbackInverse,matches=[],i=0,length=elems.length,callbackExpect=!invert;for(;i<length;i++){callbackInverse=!callback(elems[i],i);if(callbackInverse!==callbackExpect){matches.push(elems[i])}}return matches},map:function(elems,callback,arg){var value,i=0,length=elems.length,isArray=isArraylike(elems),ret=[];if(isArray){for(;i<length;i++){value=callback(elems[i],i,arg);if(value!=null){ret.push(value)}}}else{for(i in elems){value=callback(elems[i],i,arg);if(value!=null){ret.push(value)}}}return concat.apply([],ret)},guid:1,proxy:function(fn,context){var tmp,args,proxy;if(typeof context==="string"){tmp=fn[context];context=fn;fn=tmp}if(!jQuery.isFunction(fn)){return undefined}args=slice.call(arguments,2);proxy=function(){return fn.apply(context||this,args.concat(slice.call(arguments)))};proxy.guid=fn.guid=fn.guid||jQuery.guid++;return proxy},now:Date.now,support:support});jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(i,name){class2type["[object "+name+"]"]=name.toLowerCase()});function isArraylike(obj){var length=obj.length,type=jQuery.type(obj);if(type==="function"||jQuery.isWindow(obj)){return false}if(obj.nodeType===1&&length){return true}return type==="array"||length===0||typeof length==="number"&&length>0&&(length-1) in obj}var Sizzle= /* * Sizzle CSS Selector Engine v2.2.0-pre * http://sizzlejs.com/ * * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-12-16 */ (function(window){var i,support,Expr,getText,isXML,tokenize,compile,select,outermostContext,sortInput,hasDuplicate,setDocument,document,docElem,documentIsHTML,rbuggyQSA,rbuggyMatches,matches,contains,expando="sizzle"+1*new Date(),preferredDoc=window.document,dirruns=0,done=0,classCache=createCache(),tokenCache=createCache(),compilerCache=createCache(),sortOrder=function(a,b){if(a===b){hasDuplicate=true}return 0},MAX_NEGATIVE=1<<31,hasOwn=({}).hasOwnProperty,arr=[],pop=arr.pop,push_native=arr.push,push=arr.push,slice=arr.slice,indexOf=function(list,elem){var i=0,len=list.length;for(;i<len;i++){if(list[i]===elem){return i}}return -1},booleans="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",whitespace="[\\x20\\t\\r\\n\\f]",characterEncoding="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",identifier=characterEncoding.replace("w","w#"),attributes="\\["+whitespace+"*("+characterEncoding+")(?:"+whitespace+"*([*^$|!~]?=)"+whitespace+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+identifier+"))|)"+whitespace+"*\\]",pseudos=":("+characterEncoding+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+attributes+")*)|.*)\\)|)",rwhitespace=new RegExp(whitespace+"+","g"),rtrim=new RegExp("^"+whitespace+"+|((?:^|[^\\\\])(?:\\\\.)*)"+whitespace+"+$","g"),rcomma=new RegExp("^"+whitespace+"*,"+whitespace+"*"),rcombinators=new RegExp("^"+whitespace+"*([>+~]|"+whitespace+")"+whitespace+"*"),rattributeQuotes=new RegExp("="+whitespace+"*([^\\]'\"]*?)"+whitespace+"*\\]","g"),rpseudo=new RegExp(pseudos),ridentifier=new RegExp("^"+identifier+"$"),matchExpr={ID:new RegExp("^#("+characterEncoding+")"),CLASS:new RegExp("^\\.("+characterEncoding+")"),TAG:new RegExp("^("+characterEncoding.replace("w","w*")+")"),ATTR:new RegExp("^"+attributes),PSEUDO:new RegExp("^"+pseudos),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+whitespace+"*(even|odd|(([+-]|)(\\d*)n|)"+whitespace+"*(?:([+-]|)"+whitespace+"*(\\d+)|))"+whitespace+"*\\)|)","i"),bool:new RegExp("^(?:"+booleans+")$","i"),needsContext:new RegExp("^"+whitespace+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+whitespace+"*((?:-\\d)?\\d*)"+whitespace+"*\\)|)(?=[^-]|$)","i")},rinputs=/^(?:input|select|textarea|button)$/i,rheader=/^h\d$/i,rnative=/^[^{]+\{\s*\[native \w/,rquickExpr=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,rsibling=/[+~]/,rescape=/'|\\/g,runescape=new RegExp("\\\\([\\da-f]{1,6}"+whitespace+"?|("+whitespace+")|.)","ig"),funescape=function(_,escaped,escapedWhitespace){var high="0x"+escaped-65536;return high!==high||escapedWhitespace?escaped:high<0?String.fromCharCode(high+65536):String.fromCharCode(high>>10|55296,high&1023|56320)},unloadHandler=function(){setDocument()};try{push.apply((arr=slice.call(preferredDoc.childNodes)),preferredDoc.childNodes);arr[preferredDoc.childNodes.length].nodeType}catch(e){push={apply:arr.length?function(target,els){push_native.apply(target,slice.call(els))}:function(target,els){var j=target.length,i=0;while((target[j++]=els[i++])){}target.length=j-1}}}function Sizzle(selector,context,results,seed){var match,elem,m,nodeType,i,groups,old,nid,newContext,newSelector;if((context?context.ownerDocument||context:preferredDoc)!==document){setDocument(context)}context=context||document;results=results||[];nodeType=context.nodeType;if(typeof selector!=="string"||!selector||nodeType!==1&&nodeType!==9&&nodeType!==11){return results}if(!seed&&documentIsHTML){if(nodeType!==11&&(match=rquickExpr.exec(selector))){if((m=match[1])){if(nodeType===9){elem=context.getElementById(m);if(elem&&elem.parentNode){if(elem.id===m){results.push(elem);return results}}else{return results}}else{if(context.ownerDocument&&(elem=context.ownerDocument.getElementById(m))&&contains(context,elem)&&elem.id===m){results.push(elem);return results}}}else{if(match[2]){push.apply(results,context.getElementsByTagName(selector));return results}else{if((m=match[3])&&support.getElementsByClassName){push.apply(results,context.getElementsByClassName(m));return results}}}}if(support.qsa&&(!rbuggyQSA||!rbuggyQSA.test(selector))){nid=old=expando;newContext=context;newSelector=nodeType!==1&&selector;if(nodeType===1&&context.nodeName.toLowerCase()!=="object"){groups=tokenize(selector);if((old=context.getAttribute("id"))){nid=old.replace(rescape,"\\$&")}else{context.setAttribute("id",nid)}nid="[id='"+nid+"'] ";i=groups.length;while(i--){groups[i]=nid+toSelector(groups[i])}newContext=rsibling.test(selector)&&testContext(context.parentNode)||context;newSelector=groups.join(",")}if(newSelector){try{push.apply(results,newContext.querySelectorAll(newSelector));return results}catch(qsaError){}finally{if(!old){context.removeAttribute("id")}}}}}return select(selector.replace(rtrim,"$1"),context,results,seed)}function createCache(){var keys=[];function cache(key,value){if(keys.push(key+" ")>Expr.cacheLength){delete cache[keys.shift()]}return(cache[key+" "]=value)}return cache}function markFunction(fn){fn[expando]=true;return fn}function assert(fn){var div=document.createElement("div");try{return !!fn(div)}catch(e){return false}finally{if(div.parentNode){div.parentNode.removeChild(div)}div=null}}function addHandle(attrs,handler){var arr=attrs.split("|"),i=attrs.length;while(i--){Expr.attrHandle[arr[i]]=handler}}function siblingCheck(a,b){var cur=b&&a,diff=cur&&a.nodeType===1&&b.nodeType===1&&(~b.sourceIndex||MAX_NEGATIVE)-(~a.sourceIndex||MAX_NEGATIVE);if(diff){return diff}if(cur){while((cur=cur.nextSibling)){if(cur===b){return -1}}}return a?1:-1}function createInputPseudo(type){return function(elem){var name=elem.nodeName.toLowerCase();return name==="input"&&elem.type===type}}function createButtonPseudo(type){return function(elem){var name=elem.nodeName.toLowerCase();return(name==="input"||name==="button")&&elem.type===type}}function createPositionalPseudo(fn){return markFunction(function(argument){argument=+argument;return markFunction(function(seed,matches){var j,matchIndexes=fn([],seed.length,argument),i=matchIndexes.length;while(i--){if(seed[(j=matchIndexes[i])]){seed[j]=!(matches[j]=seed[j])}}})})}function testContext(context){return context&&typeof context.getElementsByTagName!=="undefined"&&context}support=Sizzle.support={};isXML=Sizzle.isXML=function(elem){var documentElement=elem&&(elem.ownerDocument||elem).documentElement;return documentElement?documentElement.nodeName!=="HTML":false};setDocument=Sizzle.setDocument=function(node){var hasCompare,parent,doc=node?node.ownerDocument||node:preferredDoc;if(doc===document||doc.nodeType!==9||!doc.documentElement){return document}document=doc;docElem=doc.documentElement;parent=doc.defaultView;if(parent&&parent!==parent.top){if(parent.addEventListener){parent.addEventListener("unload",unloadHandler,false)}else{if(parent.attachEvent){parent.attachEvent("onunload",unloadHandler)}}}documentIsHTML=!isXML(doc);support.attributes=assert(function(div){div.className="i";return !div.getAttribute("className")});support.getElementsByTagName=assert(function(div){div.appendChild(doc.createComment(""));return !div.getElementsByTagName("*").length});support.getElementsByClassName=rnative.test(doc.getElementsByClassName);support.getById=assert(function(div){docElem.appendChild(div).id=expando;return !doc.getElementsByName||!doc.getElementsByName(expando).length});if(support.getById){Expr.find.ID=function(id,context){if(typeof context.getElementById!=="undefined"&&documentIsHTML){var m=context.getElementById(id);return m&&m.parentNode?[m]:[]}};Expr.filter.ID=function(id){var attrId=id.replace(runescape,funescape);return function(elem){return elem.getAttribute("id")===attrId}}}else{delete Expr.find.ID;Expr.filter.ID=function(id){var attrId=id.replace(runescape,funescape);return function(elem){var node=typeof elem.getAttributeNode!=="undefined"&&elem.getAttributeNode("id");return node&&node.value===attrId}}}Expr.find.TAG=support.getElementsByTagName?function(tag,context){if(typeof context.getElementsByTagName!=="undefined"){return context.getElementsByTagName(tag)}else{if(support.qsa){return context.querySelectorAll(tag)}}}:function(tag,context){var elem,tmp=[],i=0,results=context.getElementsByTagName(tag);if(tag==="*"){while((elem=results[i++])){if(elem.nodeType===1){tmp.push(elem)}}return tmp}return results};Expr.find.CLASS=support.getElementsByClassName&&function(className,context){if(documentIsHTML){return context.getElementsByClassName(className)}};rbuggyMatches=[];rbuggyQSA=[];if((support.qsa=rnative.test(doc.querySelectorAll))){assert(function(div){docElem.appendChild(div).innerHTML="<a id='"+expando+"'></a><select id='"+expando+"-\f]' msallowcapture=''><option selected=''></option></select>";if(div.querySelectorAll("[msallowcapture^='']").length){rbuggyQSA.push("[*^$]="+whitespace+"*(?:''|\"\")")}if(!div.querySelectorAll("[selected]").length){rbuggyQSA.push("\\["+whitespace+"*(?:value|"+booleans+")")}if(!div.querySelectorAll("[id~="+expando+"-]").length){rbuggyQSA.push("~=")}if(!div.querySelectorAll(":checked").length){rbuggyQSA.push(":checked")}if(!div.querySelectorAll("a#"+expando+"+*").length){rbuggyQSA.push(".#.+[+~]")}});assert(function(div){var input=doc.createElement("input");input.setAttribute("type","hidden");div.appendChild(input).setAttribute("name","D");if(div.querySelectorAll("[name=d]").length){rbuggyQSA.push("name"+whitespace+"*[*^$|!~]?=")}if(!div.querySelectorAll(":enabled").length){rbuggyQSA.push(":enabled",":disabled")}div.querySelectorAll("*,:x");rbuggyQSA.push(",.*:")})}if((support.matchesSelector=rnative.test((matches=docElem.matches||docElem.webkitMatchesSelector||docElem.mozMatchesSelector||docElem.oMatchesSelector||docElem.msMatchesSelector)))){assert(function(div){support.disconnectedMatch=matches.call(div,"div");matches.call(div,"[s!='']:x");rbuggyMatches.push("!=",pseudos)})}rbuggyQSA=rbuggyQSA.length&&new RegExp(rbuggyQSA.join("|"));rbuggyMatches=rbuggyMatches.length&&new RegExp(rbuggyMatches.join("|"));hasCompare=rnative.test(docElem.compareDocumentPosition);contains=hasCompare||rnative.test(docElem.contains)?function(a,b){var adown=a.nodeType===9?a.documentElement:a,bup=b&&b.parentNode;return a===bup||!!(bup&&bup.nodeType===1&&(adown.contains?adown.contains(bup):a.compareDocumentPosition&&a.compareDocumentPosition(bup)&16))}:function(a,b){if(b){while((b=b.parentNode)){if(b===a){return true}}}return false};sortOrder=hasCompare?function(a,b){if(a===b){hasDuplicate=true;return 0}var compare=!a.compareDocumentPosition-!b.compareDocumentPosition;if(compare){return compare}compare=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1;if(compare&1||(!support.sortDetached&&b.compareDocumentPosition(a)===compare)){if(a===doc||a.ownerDocument===preferredDoc&&contains(preferredDoc,a)){return -1}if(b===doc||b.ownerDocument===preferredDoc&&contains(preferredDoc,b)){return 1}return sortInput?(indexOf(sortInput,a)-indexOf(sortInput,b)):0}return compare&4?-1:1}:function(a,b){if(a===b){hasDuplicate=true;return 0}var cur,i=0,aup=a.parentNode,bup=b.parentNode,ap=[a],bp=[b];if(!aup||!bup){return a===doc?-1:b===doc?1:aup?-1:bup?1:sortInput?(indexOf(sortInput,a)-indexOf(sortInput,b)):0}else{if(aup===bup){return siblingCheck(a,b)}}cur=a;while((cur=cur.parentNode)){ap.unshift(cur)}cur=b;while((cur=cur.parentNode)){bp.unshift(cur)}while(ap[i]===bp[i]){i++}return i?siblingCheck(ap[i],bp[i]):ap[i]===preferredDoc?-1:bp[i]===preferredDoc?1:0};return doc};Sizzle.matches=function(expr,elements){return Sizzle(expr,null,null,elements)};Sizzle.matchesSelector=function(elem,expr){if((elem.ownerDocument||elem)!==document){setDocument(elem)}expr=expr.replace(rattributeQuotes,"='$1']");if(support.matchesSelector&&documentIsHTML&&(!rbuggyMatches||!rbuggyMatches.test(expr))&&(!rbuggyQSA||!rbuggyQSA.test(expr))){try{var ret=matches.call(elem,expr);if(ret||support.disconnectedMatch||elem.document&&elem.document.nodeType!==11){return ret}}catch(e){}}return Sizzle(expr,document,null,[elem]).length>0};Sizzle.contains=function(context,elem){if((context.ownerDocument||context)!==document){setDocument(context)}return contains(context,elem)};Sizzle.attr=function(elem,name){if((elem.ownerDocument||elem)!==document){setDocument(elem)}var fn=Expr.attrHandle[name.toLowerCase()],val=fn&&hasOwn.call(Expr.attrHandle,name.toLowerCase())?fn(elem,name,!documentIsHTML):undefined;return val!==undefined?val:support.attributes||!documentIsHTML?elem.getAttribute(name):(val=elem.getAttributeNode(name))&&val.specified?val.value:null};Sizzle.error=function(msg){throw new Error("Syntax error, unrecognized expression: "+msg)};Sizzle.uniqueSort=function(results){var elem,duplicates=[],j=0,i=0;hasDuplicate=!support.detectDuplicates;sortInput=!support.sortStable&&results.slice(0);results.sort(sortOrder);if(hasDuplicate){while((elem=results[i++])){if(elem===results[i]){j=duplicates.push(i)}}while(j--){results.splice(duplicates[j],1)}}sortInput=null;return results};getText=Sizzle.getText=function(elem){var node,ret="",i=0,nodeType=elem.nodeType;if(!nodeType){while((node=elem[i++])){ret+=getText(node)}}else{if(nodeType===1||nodeType===9||nodeType===11){if(typeof elem.textContent==="string"){return elem.textContent}else{for(elem=elem.firstChild;elem;elem=elem.nextSibling){ret+=getText(elem)}}}else{if(nodeType===3||nodeType===4){return elem.nodeValue}}}return ret};Expr=Sizzle.selectors={cacheLength:50,createPseudo:markFunction,match:matchExpr,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:true}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:true},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(match){match[1]=match[1].replace(runescape,funescape);match[3]=(match[3]||match[4]||match[5]||"").replace(runescape,funescape);if(match[2]==="~="){match[3]=" "+match[3]+" "}return match.slice(0,4)},CHILD:function(match){match[1]=match[1].toLowerCase();if(match[1].slice(0,3)==="nth"){if(!match[3]){Sizzle.error(match[0])}match[4]=+(match[4]?match[5]+(match[6]||1):2*(match[3]==="even"||match[3]==="odd"));match[5]=+((match[7]+match[8])||match[3]==="odd")}else{if(match[3]){Sizzle.error(match[0])}}return match},PSEUDO:function(match){var excess,unquoted=!match[6]&&match[2];if(matchExpr.CHILD.test(match[0])){return null}if(match[3]){match[2]=match[4]||match[5]||""}else{if(unquoted&&rpseudo.test(unquoted)&&(excess=tokenize(unquoted,true))&&(excess=unquoted.indexOf(")",unquoted.length-excess)-unquoted.length)){match[0]=match[0].slice(0,excess);match[2]=unquoted.slice(0,excess)}}return match.slice(0,3)}},filter:{TAG:function(nodeNameSelector){var nodeName=nodeNameSelector.replace(runescape,funescape).toLowerCase();return nodeNameSelector==="*"?function(){return true}:function(elem){return elem.nodeName&&elem.nodeName.toLowerCase()===nodeName}},CLASS:function(className){var pattern=classCache[className+" "];return pattern||(pattern=new RegExp("(^|"+whitespace+")"+className+"("+whitespace+"|$)"))&&classCache(className,function(elem){return pattern.test(typeof elem.className==="string"&&elem.className||typeof elem.getAttribute!=="undefined"&&elem.getAttribute("class")||"")})},ATTR:function(name,operator,check){return function(elem){var result=Sizzle.attr(elem,name);if(result==null){return operator==="!="}if(!operator){return true}result+="";return operator==="="?result===check:operator==="!="?result!==check:operator==="^="?check&&result.indexOf(check)===0:operator==="*="?check&&result.indexOf(check)>-1:operator==="$="?check&&result.slice(-check.length)===check:operator==="~="?(" "+result.replace(rwhitespace," ")+" ").indexOf(check)>-1:operator==="|="?result===check||result.slice(0,check.length+1)===check+"-":false}},CHILD:function(type,what,argument,first,last){var simple=type.slice(0,3)!=="nth",forward=type.slice(-4)!=="last",ofType=what==="of-type";return first===1&&last===0?function(elem){return !!elem.parentNode}:function(elem,context,xml){var cache,outerCache,node,diff,nodeIndex,start,dir=simple!==forward?"nextSibling":"previousSibling",parent=elem.parentNode,name=ofType&&elem.nodeName.toLowerCase(),useCache=!xml&&!ofType;if(parent){if(simple){while(dir){node=elem;while((node=node[dir])){if(ofType?node.nodeName.toLowerCase()===name:node.nodeType===1){return false}}start=dir=type==="only"&&!start&&"nextSibling"}return true}start=[forward?parent.firstChild:parent.lastChild];if(forward&&useCache){outerCache=parent[expando]||(parent[expando]={});cache=outerCache[type]||[];nodeIndex=cache[0]===dirruns&&cache[1];diff=cache[0]===dirruns&&cache[2];node=nodeIndex&&parent.childNodes[nodeIndex];while((node=++nodeIndex&&node&&node[dir]||(diff=nodeIndex=0)||start.pop())){if(node.nodeType===1&&++diff&&node===elem){outerCache[type]=[dirruns,nodeIndex,diff];break}}}else{if(useCache&&(cache=(elem[expando]||(elem[expando]={}))[type])&&cache[0]===dirruns){diff=cache[1]}else{while((node=++nodeIndex&&node&&node[dir]||(diff=nodeIndex=0)||start.pop())){if((ofType?node.nodeName.toLowerCase()===name:node.nodeType===1)&&++diff){if(useCache){(node[expando]||(node[expando]={}))[type]=[dirruns,diff]}if(node===elem){break}}}}}diff-=last;return diff===first||(diff%first===0&&diff/first>=0)}}},PSEUDO:function(pseudo,argument){var args,fn=Expr.pseudos[pseudo]||Expr.setFilters[pseudo.toLowerCase()]||Sizzle.error("unsupported pseudo: "+pseudo);if(fn[expando]){return fn(argument)}if(fn.length>1){args=[pseudo,pseudo,"",argument];return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase())?markFunction(function(seed,matches){var idx,matched=fn(seed,argument),i=matched.length;while(i--){idx=indexOf(seed,matched[i]);seed[idx]=!(matches[idx]=matched[i])}}):function(elem){return fn(elem,0,args)}}return fn}},pseudos:{not:markFunction(function(selector){var input=[],results=[],matcher=compile(selector.replace(rtrim,"$1"));return matcher[expando]?markFunction(function(seed,matches,context,xml){var elem,unmatched=matcher(seed,null,xml,[]),i=seed.length;while(i--){if((elem=unmatched[i])){seed[i]=!(matches[i]=elem)}}}):function(elem,context,xml){input[0]=elem;matcher(input,null,xml,results);input[0]=null;return !results.pop()}}),has:markFunction(function(selector){return function(elem){return Sizzle(selector,elem).length>0}}),contains:markFunction(function(text){text=text.replace(runescape,funescape);return function(elem){return(elem.textContent||elem.innerText||getText(elem)).indexOf(text)>-1}}),lang:markFunction(function(lang){if(!ridentifier.test(lang||"")){Sizzle.error("unsupported lang: "+lang)}lang=lang.replace(runescape,funescape).toLowerCase();return function(elem){var elemLang;do{if((elemLang=documentIsHTML?elem.lang:elem.getAttribute("xml:lang")||elem.getAttribute("lang"))){elemLang=elemLang.toLowerCase();return elemLang===lang||elemLang.indexOf(lang+"-")===0}}while((elem=elem.parentNode)&&elem.nodeType===1);return false}}),target:function(elem){var hash=window.location&&window.location.hash;return hash&&hash.slice(1)===elem.id},root:function(elem){return elem===docElem},focus:function(elem){return elem===document.activeElement&&(!document.hasFocus||document.hasFocus())&&!!(elem.type||elem.href||~elem.tabIndex)},enabled:function(elem){return elem.disabled===false},disabled:function(elem){return elem.disabled===true},checked:function(elem){var nodeName=elem.nodeName.toLowerCase();return(nodeName==="input"&&!!elem.checked)||(nodeName==="option"&&!!elem.selected)},selected:function(elem){if(elem.parentNode){elem.parentNode.selectedIndex}return elem.selected===true},empty:function(elem){for(elem=elem.firstChild;elem;elem=elem.nextSibling){if(elem.nodeType<6){return false}}return true},parent:function(elem){return !Expr.pseudos.empty(elem)},header:function(elem){return rheader.test(elem.nodeName)},input:function(elem){return rinputs.test(elem.nodeName)},button:function(elem){var name=elem.nodeName.toLowerCase();return name==="input"&&elem.type==="button"||name==="button"},text:function(elem){var attr;return elem.nodeName.toLowerCase()==="input"&&elem.type==="text"&&((attr=elem.getAttribute("type"))==null||attr.toLowerCase()==="text")},first:createPositionalPseudo(function(){return[0]}),last:createPositionalPseudo(function(matchIndexes,length){return[length-1]}),eq:createPositionalPseudo(function(matchIndexes,length,argument){return[argument<0?argument+length:argument]}),even:createPositionalPseudo(function(matchIndexes,length){var i=0;for(;i<length;i+=2){matchIndexes.push(i)}return matchIndexes}),odd:createPositionalPseudo(function(matchIndexes,length){var i=1;for(;i<length;i+=2){matchIndexes.push(i)}return matchIndexes}),lt:createPositionalPseudo(function(matchIndexes,length,argument){var i=argument<0?argument+length:argument;for(;--i>=0;){matchIndexes.push(i)}return matchIndexes}),gt:createPositionalPseudo(function(matchIndexes,length,argument){var i=argument<0?argument+length:argument;for(;++i<length;){matchIndexes.push(i)}return matchIndexes})}};Expr.pseudos.nth=Expr.pseudos.eq;for(i in {radio:true,checkbox:true,file:true,password:true,image:true}){Expr.pseudos[i]=createInputPseudo(i)}for(i in {submit:true,reset:true}){Expr.pseudos[i]=createButtonPseudo(i)}function setFilters(){}setFilters.prototype=Expr.filters=Expr.pseudos;Expr.setFilters=new setFilters();tokenize=Sizzle.tokenize=function(selector,parseOnly){var matched,match,tokens,type,soFar,groups,preFilters,cached=tokenCache[selector+" "];if(cached){return parseOnly?0:cached.slice(0)}soFar=selector;groups=[];preFilters=Expr.preFilter;while(soFar){if(!matched||(match=rcomma.exec(soFar))){if(match){soFar=soFar.slice(match[0].length)||soFar}groups.push((tokens=[]))}matched=false;if((match=rcombinators.exec(soFar))){matched=match.shift();tokens.push({value:matched,type:match[0].replace(rtrim," ")});soFar=soFar.slice(matched.length)}for(type in Expr.filter){if((match=matchExpr[type].exec(soFar))&&(!preFilters[type]||(match=preFilters[type](match)))){matched=match.shift();tokens.push({value:matched,type:type,matches:match});soFar=soFar.slice(matched.length)}}if(!matched){break}}return parseOnly?soFar.length:soFar?Sizzle.error(selector):tokenCache(selector,groups).slice(0)};function toSelector(tokens){var i=0,len=tokens.length,selector="";for(;i<len;i++){selector+=tokens[i].value}return selector}function addCombinator(matcher,combinator,base){var dir=combinator.dir,checkNonElements=base&&dir==="parentNode",doneName=done++;return combinator.first?function(elem,context,xml){while((elem=elem[dir])){if(elem.nodeType===1||checkNonElements){return matcher(elem,context,xml)}}}:function(elem,context,xml){var oldCache,outerCache,newCache=[dirruns,doneName];if(xml){while((elem=elem[dir])){if(elem.nodeType===1||checkNonElements){if(matcher(elem,context,xml)){return true}}}}else{while((elem=elem[dir])){if(elem.nodeType===1||checkNonElements){outerCache=elem[expando]||(elem[expando]={});if((oldCache=outerCache[dir])&&oldCache[0]===dirruns&&oldCache[1]===doneName){return(newCache[2]=oldCache[2])}else{outerCache[dir]=newCache;if((newCache[2]=matcher(elem,context,xml))){return true}}}}}}}function elementMatcher(matchers){return matchers.length>1?function(elem,context,xml){var i=matchers.length;while(i--){if(!matchers[i](elem,context,xml)){return false}}return true}:matchers[0]}function multipleContexts(selector,contexts,results){var i=0,len=contexts.length;for(;i<len;i++){Sizzle(selector,contexts[i],results)}return results}function condense(unmatched,map,filter,context,xml){var elem,newUnmatched=[],i=0,len=unmatched.length,mapped=map!=null;for(;i<len;i++){if((elem=unmatched[i])){if(!filter||filter(elem,context,xml)){newUnmatched.push(elem);if(mapped){map.push(i)}}}}return newUnmatched}function setMatcher(preFilter,selector,matcher,postFilter,postFinder,postSelector){if(postFilter&&!postFilter[expando]){postFilter=setMatcher(postFilter)}if(postFinder&&!postFinder[expando]){postFinder=setMatcher(postFinder,postSelector)}return markFunction(function(seed,results,context,xml){var temp,i,elem,preMap=[],postMap=[],preexisting=results.length,elems=seed||multipleContexts(selector||"*",context.nodeType?[context]:context,[]),matcherIn=preFilter&&(seed||!selector)?condense(elems,preMap,preFilter,context,xml):elems,matcherOut=matcher?postFinder||(seed?preFilter:preexisting||postFilter)?[]:results:matcherIn;if(matcher){matcher(matcherIn,matcherOut,context,xml)}if(postFilter){temp=condense(matcherOut,postMap);postFilter(temp,[],context,xml);i=temp.length;while(i--){if((elem=temp[i])){matcherOut[postMap[i]]=!(matcherIn[postMap[i]]=elem)}}}if(seed){if(postFinder||preFilter){if(postFinder){temp=[];i=matcherOut.length;while(i--){if((elem=matcherOut[i])){temp.push((matcherIn[i]=elem))}}postFinder(null,(matcherOut=[]),temp,xml)}i=matcherOut.length;while(i--){if((elem=matcherOut[i])&&(temp=postFinder?indexOf(seed,elem):preMap[i])>-1){seed[temp]=!(results[temp]=elem)}}}}else{matcherOut=condense(matcherOut===results?matcherOut.splice(preexisting,matcherOut.length):matcherOut);if(postFinder){postFinder(null,results,matcherOut,xml)}else{push.apply(results,matcherOut)}}})}function matcherFromTokens(tokens){var checkContext,matcher,j,len=tokens.length,leadingRelative=Expr.relative[tokens[0].type],implicitRelative=leadingRelative||Expr.relative[" "],i=leadingRelative?1:0,matchContext=addCombinator(function(elem){return elem===checkContext},implicitRelative,true),matchAnyContext=addCombinator(function(elem){return indexOf(checkContext,elem)>-1},implicitRelative,true),matchers=[function(elem,context,xml){var ret=(!leadingRelative&&(xml||context!==outermostContext))||((checkContext=context).nodeType?matchContext(elem,context,xml):matchAnyContext(elem,context,xml));checkContext=null;return ret}];for(;i<len;i++){if((matcher=Expr.relative[tokens[i].type])){matchers=[addCombinator(elementMatcher(matchers),matcher)]}else{matcher=Expr.filter[tokens[i].type].apply(null,tokens[i].matches);if(matcher[expando]){j=++i;for(;j<len;j++){if(Expr.relative[tokens[j].type]){break}}return setMatcher(i>1&&elementMatcher(matchers),i>1&&toSelector(tokens.slice(0,i-1).concat({value:tokens[i-2].type===" "?"*":""})).replace(rtrim,"$1"),matcher,i<j&&matcherFromTokens(tokens.slice(i,j)),j<len&&matcherFromTokens((tokens=tokens.slice(j))),j<len&&toSelector(tokens))}matchers.push(matcher)}}return elementMatcher(matchers)}function matcherFromGroupMatchers(elementMatchers,setMatchers){var bySet=setMatchers.length>0,byElement=elementMatchers.length>0,superMatcher=function(seed,context,xml,results,outermost){var elem,j,matcher,matchedCount=0,i="0",unmatched=seed&&[],setMatched=[],contextBackup=outermostContext,elems=seed||byElement&&Expr.find.TAG("*",outermost),dirrunsUnique=(dirruns+=contextBackup==null?1:Math.random()||0.1),len=elems.length;if(outermost){outermostContext=context!==document&&context}for(;i!==len&&(elem=elems[i])!=null;i++){if(byElement&&elem){j=0;while((matcher=elementMatchers[j++])){if(matcher(elem,context,xml)){results.push(elem);break}}if(outermost){dirruns=dirrunsUnique}}if(bySet){if((elem=!matcher&&elem)){matchedCount--}if(seed){unmatched.push(elem)}}}matchedCount+=i;if(bySet&&i!==matchedCount){j=0;while((matcher=setMatchers[j++])){matcher(unmatched,setMatched,context,xml)}if(seed){if(matchedCount>0){while(i--){if(!(unmatched[i]||setMatched[i])){setMatched[i]=pop.call(results)}}}setMatched=condense(setMatched)}push.apply(results,setMatched);if(outermost&&!seed&&setMatched.length>0&&(matchedCount+setMatchers.length)>1){Sizzle.uniqueSort(results)}}if(outermost){dirruns=dirrunsUnique;outermostContext=contextBackup}return unmatched};return bySet?markFunction(superMatcher):superMatcher}compile=Sizzle.compile=function(selector,match){var i,setMatchers=[],elementMatchers=[],cached=compilerCache[selector+" "];if(!cached){if(!match){match=tokenize(selector)}i=match.length;while(i--){cached=matcherFromTokens(match[i]);if(cached[expando]){setMatchers.push(cached)}else{elementMatchers.push(cached)}}cached=compilerCache(selector,matcherFromGroupMatchers(elementMatchers,setMatchers));cached.selector=selector}return cached};select=Sizzle.select=function(selector,context,results,seed){var i,tokens,token,type,find,compiled=typeof selector==="function"&&selector,match=!seed&&tokenize((selector=compiled.selector||selector));results=results||[];if(match.length===1){tokens=match[0]=match[0].slice(0);if(tokens.length>2&&(token=tokens[0]).type==="ID"&&support.getById&&context.nodeType===9&&documentIsHTML&&Expr.relative[tokens[1].type]){context=(Expr.find.ID(token.matches[0].replace(runescape,funescape),context)||[])[0];if(!context){return results}else{if(compiled){context=context.parentNode}}selector=selector.slice(tokens.shift().value.length)}i=matchExpr.needsContext.test(selector)?0:tokens.length;while(i--){token=tokens[i];if(Expr.relative[(type=token.type)]){break}if((find=Expr.find[type])){if((seed=find(token.matches[0].replace(runescape,funescape),rsibling.test(tokens[0].type)&&testContext(context.parentNode)||context))){tokens.splice(i,1);selector=seed.length&&toSelector(tokens);if(!selector){push.apply(results,seed);return results}break}}}}(compiled||compile(selector,match))(seed,context,!documentIsHTML,results,rsibling.test(selector)&&testContext(context.parentNode)||context);return results};support.sortStable=expando.split("").sort(sortOrder).join("")===expando;support.detectDuplicates=!!hasDuplicate;setDocument();support.sortDetached=assert(function(div1){return div1.compareDocumentPosition(document.createElement("div"))&1});if(!assert(function(div){div.innerHTML="<a href='#'></a>";return div.firstChild.getAttribute("href")==="#"})){addHandle("type|href|height|width",function(elem,name,isXML){if(!isXML){return elem.getAttribute(name,name.toLowerCase()==="type"?1:2)}})}if(!support.attributes||!assert(function(div){div.innerHTML="<input/>";div.firstChild.setAttribute("value","");return div.firstChild.getAttribute("value")===""})){addHandle("value",function(elem,name,isXML){if(!isXML&&elem.nodeName.toLowerCase()==="input"){return elem.defaultValue}})}if(!assert(function(div){return div.getAttribute("disabled")==null})){addHandle(booleans,function(elem,name,isXML){var val;if(!isXML){return elem[name]===true?name.toLowerCase():(val=elem.getAttributeNode(name))&&val.specified?val.value:null}})}return Sizzle})(window);jQuery.find=Sizzle;jQuery.expr=Sizzle.selectors;jQuery.expr[":"]=jQuery.expr.pseudos;jQuery.unique=Sizzle.uniqueSort;jQuery.text=Sizzle.getText;jQuery.isXMLDoc=Sizzle.isXML;jQuery.contains=Sizzle.contains;var rneedsContext=jQuery.expr.match.needsContext;var rsingleTag=(/^<(\w+)\s*\/?>(?:<\/\1>|)$/);var risSimple=/^.[^:#\[\.,]*$/;function winnow(elements,qualifier,not){if(jQuery.isFunction(qualifier)){return jQuery.grep(elements,function(elem,i){return !!qualifier.call(elem,i,elem)!==not})}if(qualifier.nodeType){return jQuery.grep(elements,function(elem){return(elem===qualifier)!==not})}if(typeof qualifier==="string"){if(risSimple.test(qualifier)){return jQuery.filter(qualifier,elements,not)}qualifier=jQuery.filter(qualifier,elements)}return jQuery.grep(elements,function(elem){return(indexOf.call(qualifier,elem)>=0)!==not})}jQuery.filter=function(expr,elems,not){var elem=elems[0];if(not){expr=":not("+expr+")"}return elems.length===1&&elem.nodeType===1?jQuery.find.matchesSelector(elem,expr)?[elem]:[]:jQuery.find.matches(expr,jQuery.grep(elems,function(elem){return elem.nodeType===1}))};jQuery.fn.extend({find:function(selector){var i,len=this.length,ret=[],self=this;if(typeof selector!=="string"){return this.pushStack(jQuery(selector).filter(function(){for(i=0;i<len;i++){if(jQuery.contains(self[i],this)){return true}}}))}for(i=0;i<len;i++){jQuery.find(selector,self[i],ret)}ret=this.pushStack(len>1?jQuery.unique(ret):ret);ret.selector=this.selector?this.selector+" "+selector:selector;return ret},filter:function(selector){return this.pushStack(winnow(this,selector||[],false))},not:function(selector){return this.pushStack(winnow(this,selector||[],true))},is:function(selector){return !!winnow(this,typeof selector==="string"&&rneedsContext.test(selector)?jQuery(selector):selector||[],false).length}});var rootjQuery,rquickExpr=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,init=jQuery.fn.init=function(selector,context){var match,elem;if(!selector){return this}if(typeof selector==="string"){if(selector[0]==="<"&&selector[selector.length-1]===">"&&selector.length>=3){match=[null,selector,null]}else{match=rquickExpr.exec(selector)}if(match&&(match[1]||!context)){if(match[1]){context=context instanceof jQuery?context[0]:context;jQuery.merge(this,jQuery.parseHTML(match[1],context&&context.nodeType?context.ownerDocument||context:document,true));if(rsingleTag.test(match[1])&&jQuery.isPlainObject(context)){for(match in context){if(jQuery.isFunction(this[match])){this[match](context[match])}else{this.attr(match,context[match])}}}return this}else{elem=document.getElementById(match[2]);if(elem&&elem.parentNode){this.length=1;this[0]=elem}this.context=document;this.selector=selector;return this}}else{if(!context||context.jquery){return(context||rootjQuery).find(selector)}else{return this.constructor(context).find(selector)}}}else{if(selector.nodeType){this.context=this[0]=selector;this.length=1;return this}else{if(jQuery.isFunction(selector)){return typeof rootjQuery.ready!=="undefined"?rootjQuery.ready(selector):selector(jQuery)}}}if(selector.selector!==undefined){this.selector=selector.selector;this.context=selector.context}return jQuery.makeArray(selector,this)};init.prototype=jQuery.fn;rootjQuery=jQuery(document);var rparentsprev=/^(?:parents|prev(?:Until|All))/,guaranteedUnique={children:true,contents:true,next:true,prev:true};jQuery.extend({dir:function(elem,dir,until){var matched=[],truncate=until!==undefined;while((elem=elem[dir])&&elem.nodeType!==9){if(elem.nodeType===1){if(truncate&&jQuery(elem).is(until)){break}matched.push(elem)}}return matched},sibling:function(n,elem){var matched=[];for(;n;n=n.nextSibling){if(n.nodeType===1&&n!==elem){matched.push(n)}}return matched}});jQuery.fn.extend({has:function(target){var targets=jQuery(target,this),l=targets.length;return this.filter(function(){var i=0;for(;i<l;i++){if(jQuery.contains(this,targets[i])){return true}}})},closest:function(selectors,context){var cur,i=0,l=this.length,matched=[],pos=rneedsContext.test(selectors)||typeof selectors!=="string"?jQuery(selectors,context||this.context):0;for(;i<l;i++){for(cur=this[i];cur&&cur!==context;cur=cur.parentNode){if(cur.nodeType<11&&(pos?pos.index(cur)>-1:cur.nodeType===1&&jQuery.find.matchesSelector(cur,selectors))){matched.push(cur);break}}}return this.pushStack(matched.length>1?jQuery.unique(matched):matched)},index:function(elem){if(!elem){return(this[0]&&this[0].parentNode)?this.first().prevAll().length:-1}if(typeof elem==="string"){return indexOf.call(jQuery(elem),this[0])}return indexOf.call(this,elem.jquery?elem[0]:elem)},add:function(selector,context){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),jQuery(selector,context))))},addBack:function(selector){return this.add(selector==null?this.prevObject:this.prevObject.filter(selector))}});function sibling(cur,dir){while((cur=cur[dir])&&cur.nodeType!==1){}return cur}jQuery.each({parent:function(elem){var parent=elem.parentNode;return parent&&parent.nodeType!==11?parent:null},parents:function(elem){return jQuery.dir(elem,"parentNode")},parentsUntil:function(elem,i,until){return jQuery.dir(elem,"parentNode",until)},next:function(elem){return sibling(elem,"nextSibling")},prev:function(elem){return sibling(elem,"previousSibling")},nextAll:function(elem){return jQuery.dir(elem,"nextSibling")},prevAll:function(elem){return jQuery.dir(elem,"previousSibling")},nextUntil:function(elem,i,until){return jQuery.dir(elem,"nextSibling",until)},prevUntil:function(elem,i,until){return jQuery.dir(elem,"previousSibling",until)},siblings:function(elem){return jQuery.sibling((elem.parentNode||{}).firstChild,elem)},children:function(elem){return jQuery.sibling(elem.firstChild)},contents:function(elem){return elem.contentDocument||jQuery.merge([],elem.childNodes)}},function(name,fn){jQuery.fn[name]=function(until,selector){var matched=jQuery.map(this,fn,until);if(name.slice(-5)!=="Until"){selector=until}if(selector&&typeof selector==="string"){matched=jQuery.filter(selector,matched)}if(this.length>1){if(!guaranteedUnique[name]){jQuery.unique(matched)}if(rparentsprev.test(name)){matched.reverse()}}return this.pushStack(matched)}});var rnotwhite=(/\S+/g);var optionsCache={};function createOptions(options){var object=optionsCache[options]={};jQuery.each(options.match(rnotwhite)||[],function(_,flag){object[flag]=true});return object}jQuery.Callbacks=function(options){options=typeof options==="string"?(optionsCache[options]||createOptions(options)):jQuery.extend({},options);var memory,fired,firing,firingStart,firingLength,firingIndex,list=[],stack=!options.once&&[],fire=function(data){memory=options.memory&&data;fired=true;firingIndex=firingStart||0;firingStart=0;firingLength=list.length;firing=true;for(;list&&firingIndex<firingLength;firingIndex++){if(list[firingIndex].apply(data[0],data[1])===false&&options.stopOnFalse){memory=false;break}}firing=false;if(list){if(stack){if(stack.length){fire(stack.shift())}}else{if(memory){list=[]}else{self.disable()}}}},self={add:function(){if(list){var start=list.length;(function add(args){jQuery.each(args,function(_,arg){var type=jQuery.type(arg);if(type==="function"){if(!options.unique||!self.has(arg)){list.push(arg)}}else{if(arg&&arg.length&&type!=="string"){add(arg)}}})})(arguments);if(firing){firingLength=list.length}else{if(memory){firingStart=start;fire(memory)}}}return this},remove:function(){if(list){jQuery.each(arguments,function(_,arg){var index;while((index=jQuery.inArray(arg,list,index))>-1){list.splice(index,1);if(firing){if(index<=firingLength){firingLength--}if(index<=firingIndex){firingIndex--}}}})}return this},has:function(fn){return fn?jQuery.inArray(fn,list)>-1:!!(list&&list.length)},empty:function(){list=[];firingLength=0;return this},disable:function(){list=stack=memory=undefined;return this},disabled:function(){return !list},lock:function(){stack=undefined;if(!memory){self.disable()}return this},locked:function(){return !stack},fireWith:function(context,args){if(list&&(!fired||stack)){args=args||[];args=[context,args.slice?args.slice():args];if(firing){stack.push(args)}else{fire(args)}}return this},fire:function(){self.fireWith(this,arguments);return this},fired:function(){return !!fired}};return self};jQuery.extend({Deferred:function(func){var tuples=[["resolve","done",jQuery.Callbacks("once memory"),"resolved"],["reject","fail",jQuery.Callbacks("once memory"),"rejected"],["notify","progress",jQuery.Callbacks("memory")]],state="pending",promise={state:function(){return state},always:function(){deferred.done(arguments).fail(arguments);return this},then:function(){var fns=arguments;return jQuery.Deferred(function(newDefer){jQuery.each(tuples,function(i,tuple){var fn=jQuery.isFunction(fns[i])&&fns[i];deferred[tuple[1]](function(){var returned=fn&&fn.apply(this,arguments);if(returned&&jQuery.isFunction(returned.promise)){returned.promise().done(newDefer.resolve).fail(newDefer.reject).progress(newDefer.notify)}else{newDefer[tuple[0]+"With"](this===promise?newDefer.promise():this,fn?[returned]:arguments)}})});fns=null}).promise()},promise:function(obj){return obj!=null?jQuery.extend(obj,promise):promise}},deferred={};promise.pipe=promise.then;jQuery.each(tuples,function(i,tuple){var list=tuple[2],stateString=tuple[3];promise[tuple[1]]=list.add;if(stateString){list.add(function(){state=stateString},tuples[i^1][2].disable,tuples[2][2].lock)}deferred[tuple[0]]=function(){deferred[tuple[0]+"With"](this===deferred?promise:this,arguments);return this};deferred[tuple[0]+"With"]=list.fireWith});promise.promise(deferred);if(func){func.call(deferred,deferred)}return deferred},when:function(subordinate){var i=0,resolveValues=slice.call(arguments),length=resolveValues.length,remaining=length!==1||(subordinate&&jQuery.isFunction(subordinate.promise))?length:0,deferred=remaining===1?subordinate:jQuery.Deferred(),updateFunc=function(i,contexts,values){return function(value){contexts[i]=this;values[i]=arguments.length>1?slice.call(arguments):value;if(values===progressValues){deferred.notifyWith(contexts,values)}else{if(!(--remaining)){deferred.resolveWith(contexts,values)}}}},progressValues,progressContexts,resolveContexts;if(length>1){progressValues=new Array(length);progressContexts=new Array(length);resolveContexts=new Array(length);for(;i<length;i++){if(resolveValues[i]&&jQuery.isFunction(resolveValues[i].promise)){resolveValues[i].promise().done(updateFunc(i,resolveContexts,resolveValues)).fail(deferred.reject).progress(updateFunc(i,progressContexts,progressValues))}else{--remaining}}}if(!remaining){deferred.resolveWith(resolveContexts,resolveValues)}return deferred.promise()}});var readyList;jQuery.fn.ready=function(fn){jQuery.ready.promise().done(fn);return this};jQuery.extend({isReady:false,readyWait:1,holdReady:function(hold){if(hold){jQuery.readyWait++}else{jQuery.ready(true)}},ready:function(wait){if(wait===true?--jQuery.readyWait:jQuery.isReady){return}jQuery.isReady=true;if(wait!==true&&--jQuery.readyWait>0){return}readyList.resolveWith(document,[jQuery]);if(jQuery.fn.triggerHandler){jQuery(document).triggerHandler("ready");jQuery(document).off("ready")}}});function completed(){document.removeEventListener("DOMContentLoaded",completed,false);window.removeEventListener("load",completed,false);jQuery.ready()}jQuery.ready.promise=function(obj){if(!readyList){readyList=jQuery.Deferred();if(document.readyState==="complete"){setTimeout(jQuery.ready)}else{document.addEventListener("DOMContentLoaded",completed,false);window.addEventListener("load",completed,false)}}return readyList.promise(obj)};jQuery.ready.promise();var access=jQuery.access=function(elems,fn,key,value,chainable,emptyGet,raw){var i=0,len=elems.length,bulk=key==null;if(jQuery.type(key)==="object"){chainable=true;for(i in key){jQuery.access(elems,fn,i,key[i],true,emptyGet,raw)}}else{if(value!==undefined){chainable=true;if(!jQuery.isFunction(value)){raw=true}if(bulk){if(raw){fn.call(elems,value);fn=null}else{bulk=fn;fn=function(elem,key,value){return bulk.call(jQuery(elem),value)}}}if(fn){for(;i<len;i++){fn(elems[i],key,raw?value:value.call(elems[i],i,fn(elems[i],key)))}}}}return chainable?elems:bulk?fn.call(elems):len?fn(elems[0],key):emptyGet};jQuery.acceptData=function(owner){return owner.nodeType===1||owner.nodeType===9||!(+owner.nodeType)};function Data(){Object.defineProperty(this.cache={},0,{get:function(){return{}}});this.expando=jQuery.expando+Data.uid++}Data.uid=1;Data.accepts=jQuery.acceptData;Data.prototype={key:function(owner){if(!Data.accepts(owner)){return 0}var descriptor={},unlock=owner[this.expando];if(!unlock){unlock=Data.uid++;try{descriptor[this.expando]={value:unlock};Object.defineProperties(owner,descriptor)}catch(e){descriptor[this.expando]=unlock;jQuery.extend(owner,descriptor)}}if(!this.cache[unlock]){this.cache[unlock]={}}return unlock},set:function(owner,data,value){var prop,unlock=this.key(owner),cache=this.cache[unlock];if(typeof data==="string"){cache[data]=value}else{if(jQuery.isEmptyObject(cache)){jQuery.extend(this.cache[unlock],data)}else{for(prop in data){cache[prop]=data[prop]}}}return cache},get:function(owner,key){var cache=this.cache[this.key(owner)];return key===undefined?cache:cache[key]},access:function(owner,key,value){var stored;if(key===undefined||((key&&typeof key==="string")&&value===undefined)){stored=this.get(owner,key);return stored!==undefined?stored:this.get(owner,jQuery.camelCase(key))}this.set(owner,key,value);return value!==undefined?value:key},remove:function(owner,key){var i,name,camel,unlock=this.key(owner),cache=this.cache[unlock];if(key===undefined){this.cache[unlock]={}}else{if(jQuery.isArray(key)){name=key.concat(key.map(jQuery.camelCase))}else{camel=jQuery.camelCase(key);if(key in cache){name=[key,camel]}else{name=camel;name=name in cache?[name]:(name.match(rnotwhite)||[])}}i=name.length;while(i--){delete cache[name[i]]}}},hasData:function(owner){return !jQuery.isEmptyObject(this.cache[owner[this.expando]]||{})},discard:function(owner){if(owner[this.expando]){delete this.cache[owner[this.expando]]}}};var data_priv=new Data();var data_user=new Data();var rbrace=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,rmultiDash=/([A-Z])/g;function dataAttr(elem,key,data){var name;if(data===undefined&&elem.nodeType===1){name="data-"+key.replace(rmultiDash,"-$1").toLowerCase();data=elem.getAttribute(name);if(typeof data==="string"){try{data=data==="true"?true:data==="false"?false:data==="null"?null:+data+""===data?+data:rbrace.test(data)?jQuery.parseJSON(data):data}catch(e){}data_user.set(elem,key,data)}else{data=undefined}}return data}jQuery.extend({hasData:function(elem){return data_user.hasData(elem)||data_priv.hasData(elem)},data:function(elem,name,data){return data_user.access(elem,name,data)},removeData:function(elem,name){data_user.remove(elem,name)},_data:function(elem,name,data){return data_priv.access(elem,name,data)},_removeData:function(elem,name){data_priv.remove(elem,name)}});jQuery.fn.extend({data:function(key,value){var i,name,data,elem=this[0],attrs=elem&&elem.attributes;if(key===undefined){if(this.length){data=data_user.get(elem);if(elem.nodeType===1&&!data_priv.get(elem,"hasDataAttrs")){i=attrs.length;while(i--){if(attrs[i]){name=attrs[i].name;if(name.indexOf("data-")===0){name=jQuery.camelCase(name.slice(5));dataAttr(elem,name,data[name])}}}data_priv.set(elem,"hasDataAttrs",true)}}return data}if(typeof key==="object"){return this.each(function(){data_user.set(this,key)})}return access(this,function(value){var data,camelKey=jQuery.camelCase(key);if(elem&&value===undefined){data=data_user.get(elem,key);if(data!==undefined){return data}data=data_user.get(elem,camelKey);if(data!==undefined){return data}data=dataAttr(elem,camelKey,undefined);if(data!==undefined){return data}return}this.each(function(){var data=data_user.get(this,camelKey);data_user.set(this,camelKey,value);if(key.indexOf("-")!==-1&&data!==undefined){data_user.set(this,key,value)}})},null,value,arguments.length>1,null,true)},removeData:function(key){return this.each(function(){data_user.remove(this,key)})}});jQuery.extend({queue:function(elem,type,data){var queue;if(elem){type=(type||"fx")+"queue";queue=data_priv.get(elem,type);if(data){if(!queue||jQuery.isArray(data)){queue=data_priv.access(elem,type,jQuery.makeArray(data))}else{queue.push(data)}}return queue||[]}},dequeue:function(elem,type){type=type||"fx";var queue=jQuery.queue(elem,type),startLength=queue.length,fn=queue.shift(),hooks=jQuery._queueHooks(elem,type),next=function(){jQuery.dequeue(elem,type)};if(fn==="inprogress"){fn=queue.shift();startLength--}if(fn){if(type==="fx"){queue.unshift("inprogress")}delete hooks.stop;fn.call(elem,next,hooks)}if(!startLength&&hooks){hooks.empty.fire()}},_queueHooks:function(elem,type){var key=type+"queueHooks";return data_priv.get(elem,key)||data_priv.access(elem,key,{empty:jQuery.Callbacks("once memory").add(function(){data_priv.remove(elem,[type+"queue",key])})})}});jQuery.fn.extend({queue:function(type,data){var setter=2;if(typeof type!=="string"){data=type;type="fx";setter--}if(arguments.length<setter){return jQuery.queue(this[0],type)}return data===undefined?this:this.each(function(){var queue=jQuery.queue(this,type,data);jQuery._queueHooks(this,type);if(type==="fx"&&queue[0]!=="inprogress"){jQuery.dequeue(this,type)}})},dequeue:function(type){return this.each(function(){jQuery.dequeue(this,type)})},clearQueue:function(type){return this.queue(type||"fx",[])},promise:function(type,obj){var tmp,count=1,defer=jQuery.Deferred(),elements=this,i=this.length,resolve=function(){if(!(--count)){defer.resolveWith(elements,[elements])}};if(typeof type!=="string"){obj=type;type=undefined}type=type||"fx";while(i--){tmp=data_priv.get(elements[i],type+"queueHooks");if(tmp&&tmp.empty){count++;tmp.empty.add(resolve)}}resolve();return defer.promise(obj)}});var pnum=(/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;var cssExpand=["Top","Right","Bottom","Left"];var isHidden=function(elem,el){elem=el||elem;return jQuery.css(elem,"display")==="none"||!jQuery.contains(elem.ownerDocument,elem)};var rcheckableType=(/^(?:checkbox|radio)$/i);(function(){var fragment=document.createDocumentFragment(),div=fragment.appendChild(document.createElement("div")),input=document.createElement("input");input.setAttribute("type","radio");input.setAttribute("checked","checked");input.setAttribute("name","t");div.appendChild(input);support.checkClone=div.cloneNode(true).cloneNode(true).lastChild.checked;div.innerHTML="<textarea>x</textarea>";support.noCloneChecked=!!div.cloneNode(true).lastChild.defaultValue})();var strundefined=typeof undefined;support.focusinBubbles="onfocusin" in window;var rkeyEvent=/^key/,rmouseEvent=/^(?:mouse|pointer|contextmenu)|click/,rfocusMorph=/^(?:focusinfocus|focusoutblur)$/,rtypenamespace=/^([^.]*)(?:\.(.+)|)$/;function returnTrue(){return true}function returnFalse(){return false}function safeActiveElement(){try{return document.activeElement}catch(err){}}jQuery.event={global:{},add:function(elem,types,handler,data,selector){var handleObjIn,eventHandle,tmp,events,t,handleObj,special,handlers,type,namespaces,origType,elemData=data_priv.get(elem);if(!elemData){return}if(handler.handler){handleObjIn=handler;handler=handleObjIn.handler;selector=handleObjIn.selector}if(!handler.guid){handler.guid=jQuery.guid++}if(!(events=elemData.events)){events=elemData.events={}}if(!(eventHandle=elemData.handle)){eventHandle=elemData.handle=function(e){return typeof jQuery!==strundefined&&jQuery.event.triggered!==e.type?jQuery.event.dispatch.apply(elem,arguments):undefined}}types=(types||"").match(rnotwhite)||[""];t=types.length;while(t--){tmp=rtypenamespace.exec(types[t])||[];type=origType=tmp[1];namespaces=(tmp[2]||"").split(".").sort();if(!type){continue}special=jQuery.event.special[type]||{};type=(selector?special.delegateType:special.bindType)||type;special=jQuery.event.special[type]||{};handleObj=jQuery.extend({type:type,origType:origType,data:data,handler:handler,guid:handler.guid,selector:selector,needsContext:selector&&jQuery.expr.match.needsContext.test(selector),namespace:namespaces.join(".")},handleObjIn);if(!(handlers=events[type])){handlers=events[type]=[];handlers.delegateCount=0;if(!special.setup||special.setup.call(elem,data,namespaces,eventHandle)===false){if(elem.addEventListener){elem.addEventListener(type,eventHandle,false)}}}if(special.add){special.add.call(elem,handleObj);if(!handleObj.handler.guid){handleObj.handler.guid=handler.guid}}if(selector){handlers.splice(handlers.delegateCount++,0,handleObj)}else{handlers.push(handleObj)}jQuery.event.global[type]=true}},remove:function(elem,types,handler,selector,mappedTypes){var j,origCount,tmp,events,t,handleObj,special,handlers,type,namespaces,origType,elemData=data_priv.hasData(elem)&&data_priv.get(elem);if(!elemData||!(events=elemData.events)){return}types=(types||"").match(rnotwhite)||[""];t=types.length;while(t--){tmp=rtypenamespace.exec(types[t])||[];type=origType=tmp[1];namespaces=(tmp[2]||"").split(".").sort();if(!type){for(type in events){jQuery.event.remove(elem,type+types[t],handler,selector,true)}continue}special=jQuery.event.special[type]||{};type=(selector?special.delegateType:special.bindType)||type;handlers=events[type]||[];tmp=tmp[2]&&new RegExp("(^|\\.)"+namespaces.join("\\.(?:.*\\.|)")+"(\\.|$)");origCount=j=handlers.length;while(j--){handleObj=handlers[j];if((mappedTypes||origType===handleObj.origType)&&(!handler||handler.guid===handleObj.guid)&&(!tmp||tmp.test(handleObj.namespace))&&(!selector||selector===handleObj.selector||selector==="**"&&handleObj.selector)){handlers.splice(j,1);if(handleObj.selector){handlers.delegateCount--}if(special.remove){special.remove.call(elem,handleObj)}}}if(origCount&&!handlers.length){if(!special.teardown||special.teardown.call(elem,namespaces,elemData.handle)===false){jQuery.removeEvent(elem,type,elemData.handle)}delete events[type]}}if(jQuery.isEmptyObject(events)){delete elemData.handle;data_priv.remove(elem,"events")}},trigger:function(event,data,elem,onlyHandlers){var i,cur,tmp,bubbleType,ontype,handle,special,eventPath=[elem||document],type=hasOwn.call(event,"type")?event.type:event,namespaces=hasOwn.call(event,"namespace")?event.namespace.split("."):[];cur=tmp=elem=elem||document;if(elem.nodeType===3||elem.nodeType===8){return}if(rfocusMorph.test(type+jQuery.event.triggered)){return}if(type.indexOf(".")>=0){namespaces=type.split(".");type=namespaces.shift();namespaces.sort()}ontype=type.indexOf(":")<0&&"on"+type;event=event[jQuery.expando]?event:new jQuery.Event(type,typeof event==="object"&&event);event.isTrigger=onlyHandlers?2:3;event.namespace=namespaces.join(".");event.namespace_re=event.namespace?new RegExp("(^|\\.)"+namespaces.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;event.result=undefined;if(!event.target){event.target=elem}data=data==null?[event]:jQuery.makeArray(data,[event]);special=jQuery.event.special[type]||{};if(!onlyHandlers&&special.trigger&&special.trigger.apply(elem,data)===false){return}if(!onlyHandlers&&!special.noBubble&&!jQuery.isWindow(elem)){bubbleType=special.delegateType||type;if(!rfocusMorph.test(bubbleType+type)){cur=cur.parentNode}for(;cur;cur=cur.parentNode){eventPath.push(cur);tmp=cur}if(tmp===(elem.ownerDocument||document)){eventPath.push(tmp.defaultView||tmp.parentWindow||window)}}i=0;while((cur=eventPath[i++])&&!event.isPropagationStopped()){event.type=i>1?bubbleType:special.bindType||type;handle=(data_priv.get(cur,"events")||{})[event.type]&&data_priv.get(cur,"handle");if(handle){handle.apply(cur,data)}handle=ontype&&cur[ontype];if(handle&&handle.apply&&jQuery.acceptData(cur)){event.result=handle.apply(cur,data);if(event.result===false){event.preventDefault()}}}event.type=type;if(!onlyHandlers&&!event.isDefaultPrevented()){if((!special._default||special._default.apply(eventPath.pop(),data)===false)&&jQuery.acceptData(elem)){if(ontype&&jQuery.isFunction(elem[type])&&!jQuery.isWindow(elem)){tmp=elem[ontype];if(tmp){elem[ontype]=null}jQuery.event.triggered=type;elem[type]();jQuery.event.triggered=undefined;if(tmp){elem[ontype]=tmp}}}}return event.result},dispatch:function(event){event=jQuery.event.fix(event);var i,j,ret,matched,handleObj,handlerQueue=[],args=slice.call(arguments),handlers=(data_priv.get(this,"events")||{})[event.type]||[],special=jQuery.event.special[event.type]||{};args[0]=event;event.delegateTarget=this;if(special.preDispatch&&special.preDispatch.call(this,event)===false){return}handlerQueue=jQuery.event.handlers.call(this,event,handlers);i=0;while((matched=handlerQueue[i++])&&!event.isPropagationStopped()){event.currentTarget=matched.elem;j=0;while((handleObj=matched.handlers[j++])&&!event.isImmediatePropagationStopped()){if(!event.namespace_re||event.namespace_re.test(handleObj.namespace)){event.handleObj=handleObj;event.data=handleObj.data;ret=((jQuery.event.special[handleObj.origType]||{}).handle||handleObj.handler).apply(matched.elem,args);if(ret!==undefined){if((event.result=ret)===false){event.preventDefault();event.stopPropagation()}}}}}if(special.postDispatch){special.postDispatch.call(this,event)}return event.result},handlers:function(event,handlers){var i,matches,sel,handleObj,handlerQueue=[],delegateCount=handlers.delegateCount,cur=event.target;if(delegateCount&&cur.nodeType&&(!event.button||event.type!=="click")){for(;cur!==this;cur=cur.parentNode||this){if(cur.disabled!==true||event.type!=="click"){matches=[];for(i=0;i<delegateCount;i++){handleObj=handlers[i];sel=handleObj.selector+" ";if(matches[sel]===undefined){matches[sel]=handleObj.needsContext?jQuery(sel,this).index(cur)>=0:jQuery.find(sel,this,null,[cur]).length}if(matches[sel]){matches.push(handleObj)}}if(matches.length){handlerQueue.push({elem:cur,handlers:matches})}}}}if(delegateCount<handlers.length){handlerQueue.push({elem:this,handlers:handlers.slice(delegateCount)})}return handlerQueue},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(event,original){if(event.which==null){event.which=original.charCode!=null?original.charCode:original.keyCode}return event}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(event,original){var eventDoc,doc,body,button=original.button;if(event.pageX==null&&original.clientX!=null){eventDoc=event.target.ownerDocument||document;doc=eventDoc.documentElement;body=eventDoc.body;event.pageX=original.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc&&doc.clientLeft||body&&body.clientLeft||0);event.pageY=original.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc&&doc.clientTop||body&&body.clientTop||0)}if(!event.which&&button!==undefined){event.which=(button&1?1:(button&2?3:(button&4?2:0)))}return event}},fix:function(event){if(event[jQuery.expando]){return event}var i,prop,copy,type=event.type,originalEvent=event,fixHook=this.fixHooks[type];if(!fixHook){this.fixHooks[type]=fixHook=rmouseEvent.test(type)?this.mouseHooks:rkeyEvent.test(type)?this.keyHooks:{}}copy=fixHook.props?this.props.concat(fixHook.props):this.props;event=new jQuery.Event(originalEvent);i=copy.length;while(i--){prop=copy[i];event[prop]=originalEvent[prop]}if(!event.target){event.target=document}if(event.target.nodeType===3){event.target=event.target.parentNode}return fixHook.filter?fixHook.filter(event,originalEvent):event},special:{load:{noBubble:true},focus:{trigger:function(){if(this!==safeActiveElement()&&this.focus){this.focus();return false}},delegateType:"focusin"},blur:{trigger:function(){if(this===safeActiveElement()&&this.blur){this.blur();return false}},delegateType:"focusout"},click:{trigger:function(){if(this.type==="checkbox"&&this.click&&jQuery.nodeName(this,"input")){this.click();return false}},_default:function(event){return jQuery.nodeName(event.target,"a")}},beforeunload:{postDispatch:function(event){if(event.result!==undefined&&event.originalEvent){event.originalEvent.returnValue=event.result}}}},simulate:function(type,elem,event,bubble){var e=jQuery.extend(new jQuery.Event(),event,{type:type,isSimulated:true,originalEvent:{}});if(bubble){jQuery.event.trigger(e,null,elem)}else{jQuery.event.dispatch.call(elem,e)}if(e.isDefaultPrevented()){event.preventDefault()}}};jQuery.removeEvent=function(elem,type,handle){if(elem.removeEventListener){elem.removeEventListener(type,handle,false)}};jQuery.Event=function(src,props){if(!(this instanceof jQuery.Event)){return new jQuery.Event(src,props)}if(src&&src.type){this.originalEvent=src;this.type=src.type;this.isDefaultPrevented=src.defaultPrevented||src.defaultPrevented===undefined&&src.returnValue===false?returnTrue:returnFalse}else{this.type=src}if(props){jQuery.extend(this,props)}this.timeStamp=src&&src.timeStamp||jQuery.now();this[jQuery.expando]=true};jQuery.Event.prototype={isDefaultPrevented:returnFalse,isPropagationStopped:returnFalse,isImmediatePropagationStopped:returnFalse,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=returnTrue;if(e&&e.preventDefault){e.preventDefault()}},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=returnTrue;if(e&&e.stopPropagation){e.stopPropagation()}},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=returnTrue;if(e&&e.stopImmediatePropagation){e.stopImmediatePropagation()}this.stopPropagation()}};jQuery.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(orig,fix){jQuery.event.special[orig]={delegateType:fix,bindType:fix,handle:function(event){var ret,target=this,related=event.relatedTarget,handleObj=event.handleObj;if(!related||(related!==target&&!jQuery.contains(target,related))){event.type=handleObj.origType;ret=handleObj.handler.apply(this,arguments);event.type=fix}return ret}}});if(!support.focusinBubbles){jQuery.each({focus:"focusin",blur:"focusout"},function(orig,fix){var handler=function(event){jQuery.event.simulate(fix,event.target,jQuery.event.fix(event),true)};jQuery.event.special[fix]={setup:function(){var doc=this.ownerDocument||this,attaches=data_priv.access(doc,fix);if(!attaches){doc.addEventListener(orig,handler,true)}data_priv.access(doc,fix,(attaches||0)+1)},teardown:function(){var doc=this.ownerDocument||this,attaches=data_priv.access(doc,fix)-1;if(!attaches){doc.removeEventListener(orig,handler,true);data_priv.remove(doc,fix)}else{data_priv.access(doc,fix,attaches)}}}})}jQuery.fn.extend({on:function(types,selector,data,fn,one){var origFn,type;if(typeof types==="object"){if(typeof selector!=="string"){data=data||selector;selector=undefined}for(type in types){this.on(type,selector,data,types[type],one)}return this}if(data==null&&fn==null){fn=selector;data=selector=undefined}else{if(fn==null){if(typeof selector==="string"){fn=data;data=undefined}else{fn=data;data=selector;selector=undefined}}}if(fn===false){fn=returnFalse}else{if(!fn){return this}}if(one===1){origFn=fn;fn=function(event){jQuery().off(event);return origFn.apply(this,arguments)};fn.guid=origFn.guid||(origFn.guid=jQuery.guid++)}return this.each(function(){jQuery.event.add(this,types,fn,data,selector)})},one:function(types,selector,data,fn){return this.on(types,selector,data,fn,1)},off:function(types,selector,fn){var handleObj,type;if(types&&types.preventDefault&&types.handleObj){handleObj=types.handleObj;jQuery(types.delegateTarget).off(handleObj.namespace?handleObj.origType+"."+handleObj.namespace:handleObj.origType,handleObj.selector,handleObj.handler);return this}if(typeof types==="object"){for(type in types){this.off(type,selector,types[type])}return this}if(selector===false||typeof selector==="function"){fn=selector;selector=undefined}if(fn===false){fn=returnFalse}return this.each(function(){jQuery.event.remove(this,types,fn,selector)})},trigger:function(type,data){return this.each(function(){jQuery.event.trigger(type,data,this)})},triggerHandler:function(type,data){var elem=this[0];if(elem){return jQuery.event.trigger(type,data,elem,true)}}});var rxhtmlTag=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,rtagName=/<([\w:]+)/,rhtml=/<|&#?\w+;/,rnoInnerhtml=/<(?:script|style|link)/i,rchecked=/checked\s*(?:[^=]|=\s*.checked.)/i,rscriptType=/^$|\/(?:java|ecma)script/i,rscriptTypeMasked=/^true\/(.*)/,rcleanScript=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,wrapMap={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};wrapMap.optgroup=wrapMap.option;wrapMap.tbody=wrapMap.tfoot=wrapMap.colgroup=wrapMap.caption=wrapMap.thead;wrapMap.th=wrapMap.td;function manipulationTarget(elem,content){return jQuery.nodeName(elem,"table")&&jQuery.nodeName(content.nodeType!==11?content:content.firstChild,"tr")?elem.getElementsByTagName("tbody")[0]||elem.appendChild(elem.ownerDocument.createElement("tbody")):elem}function disableScript(elem){elem.type=(elem.getAttribute("type")!==null)+"/"+elem.type;return elem}function restoreScript(elem){var match=rscriptTypeMasked.exec(elem.type);if(match){elem.type=match[1]}else{elem.removeAttribute("type")}return elem}function setGlobalEval(elems,refElements){var i=0,l=elems.length;for(;i<l;i++){data_priv.set(elems[i],"globalEval",!refElements||data_priv.get(refElements[i],"globalEval"))}}function cloneCopyEvent(src,dest){var i,l,type,pdataOld,pdataCur,udataOld,udataCur,events;if(dest.nodeType!==1){return}if(data_priv.hasData(src)){pdataOld=data_priv.access(src);pdataCur=data_priv.set(dest,pdataOld);events=pdataOld.events;if(events){delete pdataCur.handle;pdataCur.events={};for(type in events){for(i=0,l=events[type].length;i<l;i++){jQuery.event.add(dest,type,events[type][i])}}}}if(data_user.hasData(src)){udataOld=data_user.access(src);udataCur=jQuery.extend({},udataOld);data_user.set(dest,udataCur)}}function getAll(context,tag){var ret=context.getElementsByTagName?context.getElementsByTagName(tag||"*"):context.querySelectorAll?context.querySelectorAll(tag||"*"):[];return tag===undefined||tag&&jQuery.nodeName(context,tag)?jQuery.merge([context],ret):ret}function fixInput(src,dest){var nodeName=dest.nodeName.toLowerCase();if(nodeName==="input"&&rcheckableType.test(src.type)){dest.checked=src.checked}else{if(nodeName==="input"||nodeName==="textarea"){dest.defaultValue=src.defaultValue}}}jQuery.extend({clone:function(elem,dataAndEvents,deepDataAndEvents){var i,l,srcElements,destElements,clone=elem.cloneNode(true),inPage=jQuery.contains(elem.ownerDocument,elem);if(!support.noCloneChecked&&(elem.nodeType===1||elem.nodeType===11)&&!jQuery.isXMLDoc(elem)){destElements=getAll(clone);srcElements=getAll(elem);for(i=0,l=srcElements.length;i<l;i++){fixInput(srcElements[i],destElements[i])}}if(dataAndEvents){if(deepDataAndEvents){srcElements=srcElements||getAll(elem);destElements=destElements||getAll(clone);for(i=0,l=srcElements.length;i<l;i++){cloneCopyEvent(srcElements[i],destElements[i])}}else{cloneCopyEvent(elem,clone)}}destElements=getAll(clone,"script");if(destElements.length>0){setGlobalEval(destElements,!inPage&&getAll(elem,"script"))}return clone},buildFragment:function(elems,context,scripts,selection){var elem,tmp,tag,wrap,contains,j,fragment=context.createDocumentFragment(),nodes=[],i=0,l=elems.length;for(;i<l;i++){elem=elems[i];if(elem||elem===0){if(jQuery.type(elem)==="object"){jQuery.merge(nodes,elem.nodeType?[elem]:elem)}else{if(!rhtml.test(elem)){nodes.push(context.createTextNode(elem))}else{tmp=tmp||fragment.appendChild(context.createElement("div"));tag=(rtagName.exec(elem)||["",""])[1].toLowerCase();wrap=wrapMap[tag]||wrapMap._default;tmp.innerHTML=wrap[1]+elem.replace(rxhtmlTag,"<$1></$2>")+wrap[2];j=wrap[0];while(j--){tmp=tmp.lastChild}jQuery.merge(nodes,tmp.childNodes);tmp=fragment.firstChild;tmp.textContent=""}}}}fragment.textContent="";i=0;while((elem=nodes[i++])){if(selection&&jQuery.inArray(elem,selection)!==-1){continue}contains=jQuery.contains(elem.ownerDocument,elem);tmp=getAll(fragment.appendChild(elem),"script");if(contains){setGlobalEval(tmp)}if(scripts){j=0;while((elem=tmp[j++])){if(rscriptType.test(elem.type||"")){scripts.push(elem)}}}}return fragment},cleanData:function(elems){var data,elem,type,key,special=jQuery.event.special,i=0;for(;(elem=elems[i])!==undefined;i++){if(jQuery.acceptData(elem)){key=elem[data_priv.expando];if(key&&(data=data_priv.cache[key])){if(data.events){for(type in data.events){if(special[type]){jQuery.event.remove(elem,type)}else{jQuery.removeEvent(elem,type,data.handle)}}}if(data_priv.cache[key]){delete data_priv.cache[key]}}}delete data_user.cache[elem[data_user.expando]]}}});jQuery.fn.extend({text:function(value){return access(this,function(value){return value===undefined?jQuery.text(this):this.empty().each(function(){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){this.textContent=value}})},null,value,arguments.length)},append:function(){return this.domManip(arguments,function(elem){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var target=manipulationTarget(this,elem);target.appendChild(elem)}})},prepend:function(){return this.domManip(arguments,function(elem){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var target=manipulationTarget(this,elem);target.insertBefore(elem,target.firstChild)}})},before:function(){return this.domManip(arguments,function(elem){if(this.parentNode){this.parentNode.insertBefore(elem,this)}})},after:function(){return this.domManip(arguments,function(elem){if(this.parentNode){this.parentNode.insertBefore(elem,this.nextSibling)}})},remove:function(selector,keepData){var elem,elems=selector?jQuery.filter(selector,this):this,i=0;for(;(elem=elems[i])!=null;i++){if(!keepData&&elem.nodeType===1){jQuery.cleanData(getAll(elem))}if(elem.parentNode){if(keepData&&jQuery.contains(elem.ownerDocument,elem)){setGlobalEval(getAll(elem,"script"))}elem.parentNode.removeChild(elem)}}return this},empty:function(){var elem,i=0;for(;(elem=this[i])!=null;i++){if(elem.nodeType===1){jQuery.cleanData(getAll(elem,false));elem.textContent=""}}return this},clone:function(dataAndEvents,deepDataAndEvents){dataAndEvents=dataAndEvents==null?false:dataAndEvents;deepDataAndEvents=deepDataAndEvents==null?dataAndEvents:deepDataAndEvents;return this.map(function(){return jQuery.clone(this,dataAndEvents,deepDataAndEvents)})},html:function(value){return access(this,function(value){var elem=this[0]||{},i=0,l=this.length;if(value===undefined&&elem.nodeType===1){return elem.innerHTML}if(typeof value==="string"&&!rnoInnerhtml.test(value)&&!wrapMap[(rtagName.exec(value)||["",""])[1].toLowerCase()]){value=value.replace(rxhtmlTag,"<$1></$2>");try{for(;i<l;i++){elem=this[i]||{};if(elem.nodeType===1){jQuery.cleanData(getAll(elem,false));elem.innerHTML=value}}elem=0}catch(e){}}if(elem){this.empty().append(value)}},null,value,arguments.length)},replaceWith:function(){var arg=arguments[0];this.domManip(arguments,function(elem){arg=this.parentNode;jQuery.cleanData(getAll(this));if(arg){arg.replaceChild(elem,this)}});return arg&&(arg.length||arg.nodeType)?this:this.remove()},detach:function(selector){return this.remove(selector,true)},domManip:function(args,callback){args=concat.apply([],args);var fragment,first,scripts,hasScripts,node,doc,i=0,l=this.length,set=this,iNoClone=l-1,value=args[0],isFunction=jQuery.isFunction(value);if(isFunction||(l>1&&typeof value==="string"&&!support.checkClone&&rchecked.test(value))){return this.each(function(index){var self=set.eq(index);if(isFunction){args[0]=value.call(this,index,self.html())}self.domManip(args,callback)})}if(l){fragment=jQuery.buildFragment(args,this[0].ownerDocument,false,this);first=fragment.firstChild;if(fragment.childNodes.length===1){fragment=first}if(first){scripts=jQuery.map(getAll(fragment,"script"),disableScript);hasScripts=scripts.length;for(;i<l;i++){node=fragment;if(i!==iNoClone){node=jQuery.clone(node,true,true);if(hasScripts){jQuery.merge(scripts,getAll(node,"script"))}}callback.call(this[i],node,i)}if(hasScripts){doc=scripts[scripts.length-1].ownerDocument;jQuery.map(scripts,restoreScript);for(i=0;i<hasScripts;i++){node=scripts[i];if(rscriptType.test(node.type||"")&&!data_priv.access(node,"globalEval")&&jQuery.contains(doc,node)){if(node.src){if(jQuery._evalUrl){jQuery._evalUrl(node.src)}}else{jQuery.globalEval(node.textContent.replace(rcleanScript,""))}}}}}}return this}});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(selector){var elems,ret=[],insert=jQuery(selector),last=insert.length-1,i=0;for(;i<=last;i++){elems=i===last?this:this.clone(true);jQuery(insert[i])[original](elems);push.apply(ret,elems.get())}return this.pushStack(ret)}});var iframe,elemdisplay={};function actualDisplay(name,doc){var style,elem=jQuery(doc.createElement(name)).appendTo(doc.body),display=window.getDefaultComputedStyle&&(style=window.getDefaultComputedStyle(elem[0]))?style.display:jQuery.css(elem[0],"display");elem.detach();return display}function defaultDisplay(nodeName){var doc=document,display=elemdisplay[nodeName];if(!display){display=actualDisplay(nodeName,doc);if(display==="none"||!display){iframe=(iframe||jQuery("<iframe frameborder='0' width='0' height='0'/>")).appendTo(doc.documentElement);doc=iframe[0].contentDocument;doc.write();doc.close();display=actualDisplay(nodeName,doc);iframe.detach()}elemdisplay[nodeName]=display}return display}var rmargin=(/^margin/);var rnumnonpx=new RegExp("^("+pnum+")(?!px)[a-z%]+$","i");var getStyles=function(elem){if(elem.ownerDocument.defaultView.opener){return elem.ownerDocument.defaultView.getComputedStyle(elem,null)}return window.getComputedStyle(elem,null)};function curCSS(elem,name,computed){var width,minWidth,maxWidth,ret,style=elem.style;computed=computed||getStyles(elem);if(computed){ret=computed.getPropertyValue(name)||computed[name]}if(computed){if(ret===""&&!jQuery.contains(elem.ownerDocument,elem)){ret=jQuery.style(elem,name)}if(rnumnonpx.test(ret)&&rmargin.test(name)){width=style.width;minWidth=style.minWidth;maxWidth=style.maxWidth;style.minWidth=style.maxWidth=style.width=ret;ret=computed.width;style.width=width;style.minWidth=minWidth;style.maxWidth=maxWidth}}return ret!==undefined?ret+"":ret}function addGetHookIf(conditionFn,hookFn){return{get:function(){if(conditionFn()){delete this.get;return}return(this.get=hookFn).apply(this,arguments)}}}(function(){var pixelPositionVal,boxSizingReliableVal,docElem=document.documentElement,container=document.createElement("div"),div=document.createElement("div");if(!div.style){return}div.style.backgroundClip="content-box";div.cloneNode(true).style.backgroundClip="";support.clearCloneStyle=div.style.backgroundClip==="content-box";container.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute";container.appendChild(div);function computePixelPositionAndBoxSizingReliable(){div.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute";div.innerHTML="";docElem.appendChild(container);var divStyle=window.getComputedStyle(div,null);pixelPositionVal=divStyle.top!=="1%";boxSizingReliableVal=divStyle.width==="4px";docElem.removeChild(container)}if(window.getComputedStyle){jQuery.extend(support,{pixelPosition:function(){computePixelPositionAndBoxSizingReliable();return pixelPositionVal},boxSizingReliable:function(){if(boxSizingReliableVal==null){computePixelPositionAndBoxSizingReliable()}return boxSizingReliableVal},reliableMarginRight:function(){var ret,marginDiv=div.appendChild(document.createElement("div"));marginDiv.style.cssText=div.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0";marginDiv.style.marginRight=marginDiv.style.width="0";div.style.width="1px";docElem.appendChild(container);ret=!parseFloat(window.getComputedStyle(marginDiv,null).marginRight);docElem.removeChild(container);div.removeChild(marginDiv);return ret}})}})();jQuery.swap=function(elem,options,callback,args){var ret,name,old={};for(name in options){old[name]=elem.style[name];elem.style[name]=options[name]}ret=callback.apply(elem,args||[]);for(name in options){elem.style[name]=old[name]}return ret};var rdisplayswap=/^(none|table(?!-c[ea]).+)/,rnumsplit=new RegExp("^("+pnum+")(.*)$","i"),rrelNum=new RegExp("^([+-])=("+pnum+")","i"),cssShow={position:"absolute",visibility:"hidden",display:"block"},cssNormalTransform={letterSpacing:"0",fontWeight:"400"},cssPrefixes=["Webkit","O","Moz","ms"];function vendorPropName(style,name){if(name in style){return name}var capName=name[0].toUpperCase()+name.slice(1),origName=name,i=cssPrefixes.length;while(i--){name=cssPrefixes[i]+capName;if(name in style){return name}}return origName}function setPositiveNumber(elem,value,subtract){var matches=rnumsplit.exec(value);return matches?Math.max(0,matches[1]-(subtract||0))+(matches[2]||"px"):value}function augmentWidthOrHeight(elem,name,extra,isBorderBox,styles){var i=extra===(isBorderBox?"border":"content")?4:name==="width"?1:0,val=0;for(;i<4;i+=2){if(extra==="margin"){val+=jQuery.css(elem,extra+cssExpand[i],true,styles)}if(isBorderBox){if(extra==="content"){val-=jQuery.css(elem,"padding"+cssExpand[i],true,styles)}if(extra!=="margin"){val-=jQuery.css(elem,"border"+cssExpand[i]+"Width",true,styles)}}else{val+=jQuery.css(elem,"padding"+cssExpand[i],true,styles);if(extra!=="padding"){val+=jQuery.css(elem,"border"+cssExpand[i]+"Width",true,styles)}}}return val}function getWidthOrHeight(elem,name,extra){var valueIsBorderBox=true,val=name==="width"?elem.offsetWidth:elem.offsetHeight,styles=getStyles(elem),isBorderBox=jQuery.css(elem,"boxSizing",false,styles)==="border-box";if(val<=0||val==null){val=curCSS(elem,name,styles);if(val<0||val==null){val=elem.style[name]}if(rnumnonpx.test(val)){return val}valueIsBorderBox=isBorderBox&&(support.boxSizingReliable()||val===elem.style[name]);val=parseFloat(val)||0}return(val+augmentWidthOrHeight(elem,name,extra||(isBorderBox?"border":"content"),valueIsBorderBox,styles))+"px"}function showHide(elements,show){var display,elem,hidden,values=[],index=0,length=elements.length;for(;index<length;index++){elem=elements[index];if(!elem.style){continue}values[index]=data_priv.get(elem,"olddisplay");display=elem.style.display;if(show){if(!values[index]&&display==="none"){elem.style.display=""}if(elem.style.display===""&&isHidden(elem)){values[index]=data_priv.access(elem,"olddisplay",defaultDisplay(elem.nodeName))}}else{hidden=isHidden(elem);if(display!=="none"||!hidden){data_priv.set(elem,"olddisplay",hidden?display:jQuery.css(elem,"display"))}}}for(index=0;index<length;index++){elem=elements[index];if(!elem.style){continue}if(!show||elem.style.display==="none"||elem.style.display===""){elem.style.display=show?values[index]||"":"none"}}return elements}jQuery.extend({cssHooks:{opacity:{get:function(elem,computed){if(computed){var ret=curCSS(elem,"opacity");return ret===""?"1":ret}}}},cssNumber:{columnCount:true,fillOpacity:true,flexGrow:true,flexShrink:true,fontWeight:true,lineHeight:true,opacity:true,order:true,orphans:true,widows:true,zIndex:true,zoom:true},cssProps:{"float":"cssFloat"},style:function(elem,name,value,extra){if(!elem||elem.nodeType===3||elem.nodeType===8||!elem.style){return}var ret,type,hooks,origName=jQuery.camelCase(name),style=elem.style;name=jQuery.cssProps[origName]||(jQuery.cssProps[origName]=vendorPropName(style,origName));hooks=jQuery.cssHooks[name]||jQuery.cssHooks[origName];if(value!==undefined){type=typeof value;if(type==="string"&&(ret=rrelNum.exec(value))){value=(ret[1]+1)*ret[2]+parseFloat(jQuery.css(elem,name));type="number"}if(value==null||value!==value){return}if(type==="number"&&!jQuery.cssNumber[origName]){value+="px"}if(!support.clearCloneStyle&&value===""&&name.indexOf("background")===0){style[name]="inherit"}if(!hooks||!("set" in hooks)||(value=hooks.set(elem,value,extra))!==undefined){style[name]=value}}else{if(hooks&&"get" in hooks&&(ret=hooks.get(elem,false,extra))!==undefined){return ret}return style[name]}},css:function(elem,name,extra,styles){var val,num,hooks,origName=jQuery.camelCase(name);name=jQuery.cssProps[origName]||(jQuery.cssProps[origName]=vendorPropName(elem.style,origName));hooks=jQuery.cssHooks[name]||jQuery.cssHooks[origName];if(hooks&&"get" in hooks){val=hooks.get(elem,true,extra)}if(val===undefined){val=curCSS(elem,name,styles)}if(val==="normal"&&name in cssNormalTransform){val=cssNormalTransform[name]}if(extra===""||extra){num=parseFloat(val);return extra===true||jQuery.isNumeric(num)?num||0:val}return val}});jQuery.each(["height","width"],function(i,name){jQuery.cssHooks[name]={get:function(elem,computed,extra){if(computed){return rdisplayswap.test(jQuery.css(elem,"display"))&&elem.offsetWidth===0?jQuery.swap(elem,cssShow,function(){return getWidthOrHeight(elem,name,extra)}):getWidthOrHeight(elem,name,extra)}},set:function(elem,value,extra){var styles=extra&&getStyles(elem);return setPositiveNumber(elem,value,extra?augmentWidthOrHeight(elem,name,extra,jQuery.css(elem,"boxSizing",false,styles)==="border-box",styles):0)}}});jQuery.cssHooks.marginRight=addGetHookIf(support.reliableMarginRight,function(elem,computed){if(computed){return jQuery.swap(elem,{display:"inline-block"},curCSS,[elem,"marginRight"])}});jQuery.each({margin:"",padding:"",border:"Width"},function(prefix,suffix){jQuery.cssHooks[prefix+suffix]={expand:function(value){var i=0,expanded={},parts=typeof value==="string"?value.split(" "):[value];for(;i<4;i++){expanded[prefix+cssExpand[i]+suffix]=parts[i]||parts[i-2]||parts[0]}return expanded}};if(!rmargin.test(prefix)){jQuery.cssHooks[prefix+suffix].set=setPositiveNumber}});jQuery.fn.extend({css:function(name,value){return access(this,function(elem,name,value){var styles,len,map={},i=0;if(jQuery.isArray(name)){styles=getStyles(elem);len=name.length;for(;i<len;i++){map[name[i]]=jQuery.css(elem,name[i],false,styles)}return map}return value!==undefined?jQuery.style(elem,name,value):jQuery.css(elem,name)},name,value,arguments.length>1)},show:function(){return showHide(this,true)},hide:function(){return showHide(this)},toggle:function(state){if(typeof state==="boolean"){return state?this.show():this.hide()}return this.each(function(){if(isHidden(this)){jQuery(this).show()}else{jQuery(this).hide()}})}});function Tween(elem,options,prop,end,easing){return new Tween.prototype.init(elem,options,prop,end,easing)}jQuery.Tween=Tween;Tween.prototype={constructor:Tween,init:function(elem,options,prop,end,easing,unit){this.elem=elem;this.prop=prop;this.easing=easing||"swing";this.options=options;this.start=this.now=this.cur();this.end=end;this.unit=unit||(jQuery.cssNumber[prop]?"":"px")},cur:function(){var hooks=Tween.propHooks[this.prop];return hooks&&hooks.get?hooks.get(this):Tween.propHooks._default.get(this)},run:function(percent){var eased,hooks=Tween.propHooks[this.prop];if(this.options.duration){this.pos=eased=jQuery.easing[this.easing](percent,this.options.duration*percent,0,1,this.options.duration)}else{this.pos=eased=percent}this.now=(this.end-this.start)*eased+this.start;if(this.options.step){this.options.step.call(this.elem,this.now,this)}if(hooks&&hooks.set){hooks.set(this)}else{Tween.propHooks._default.set(this)}return this}};Tween.prototype.init.prototype=Tween.prototype;Tween.propHooks={_default:{get:function(tween){var result;if(tween.elem[tween.prop]!=null&&(!tween.elem.style||tween.elem.style[tween.prop]==null)){return tween.elem[tween.prop]}result=jQuery.css(tween.elem,tween.prop,"");return !result||result==="auto"?0:result},set:function(tween){if(jQuery.fx.step[tween.prop]){jQuery.fx.step[tween.prop](tween)}else{if(tween.elem.style&&(tween.elem.style[jQuery.cssProps[tween.prop]]!=null||jQuery.cssHooks[tween.prop])){jQuery.style(tween.elem,tween.prop,tween.now+tween.unit)}else{tween.elem[tween.prop]=tween.now}}}}};Tween.propHooks.scrollTop=Tween.propHooks.scrollLeft={set:function(tween){if(tween.elem.nodeType&&tween.elem.parentNode){tween.elem[tween.prop]=tween.now}}};jQuery.easing={linear:function(p){return p},swing:function(p){return 0.5-Math.cos(p*Math.PI)/2}};jQuery.fx=Tween.prototype.init;jQuery.fx.step={};var fxNow,timerId,rfxtypes=/^(?:toggle|show|hide)$/,rfxnum=new RegExp("^(?:([+-])=|)("+pnum+")([a-z%]*)$","i"),rrun=/queueHooks$/,animationPrefilters=[defaultPrefilter],tweeners={"*":[function(prop,value){var tween=this.createTween(prop,value),target=tween.cur(),parts=rfxnum.exec(value),unit=parts&&parts[3]||(jQuery.cssNumber[prop]?"":"px"),start=(jQuery.cssNumber[prop]||unit!=="px"&&+target)&&rfxnum.exec(jQuery.css(tween.elem,prop)),scale=1,maxIterations=20;if(start&&start[3]!==unit){unit=unit||start[3];parts=parts||[];start=+target||1;do{scale=scale||".5";start=start/scale;jQuery.style(tween.elem,prop,start+unit)}while(scale!==(scale=tween.cur()/target)&&scale!==1&&--maxIterations)}if(parts){start=tween.start=+start||+target||0;tween.unit=unit;tween.end=parts[1]?start+(parts[1]+1)*parts[2]:+parts[2]}return tween}]};function createFxNow(){setTimeout(function(){fxNow=undefined});return(fxNow=jQuery.now())}function genFx(type,includeWidth){var which,i=0,attrs={height:type};includeWidth=includeWidth?1:0;for(;i<4;i+=2-includeWidth){which=cssExpand[i];attrs["margin"+which]=attrs["padding"+which]=type}if(includeWidth){attrs.opacity=attrs.width=type}return attrs}function createTween(value,prop,animation){var tween,collection=(tweeners[prop]||[]).concat(tweeners["*"]),index=0,length=collection.length;for(;index<length;index++){if((tween=collection[index].call(animation,prop,value))){return tween}}}function defaultPrefilter(elem,props,opts){var prop,value,toggle,tween,hooks,oldfire,display,checkDisplay,anim=this,orig={},style=elem.style,hidden=elem.nodeType&&isHidden(elem),dataShow=data_priv.get(elem,"fxshow");if(!opts.queue){hooks=jQuery._queueHooks(elem,"fx");if(hooks.unqueued==null){hooks.unqueued=0;oldfire=hooks.empty.fire;hooks.empty.fire=function(){if(!hooks.unqueued){oldfire()}}}hooks.unqueued++;anim.always(function(){anim.always(function(){hooks.unqueued--;if(!jQuery.queue(elem,"fx").length){hooks.empty.fire()}})})}if(elem.nodeType===1&&("height" in props||"width" in props)){opts.overflow=[style.overflow,style.overflowX,style.overflowY];display=jQuery.css(elem,"display");checkDisplay=display==="none"?data_priv.get(elem,"olddisplay")||defaultDisplay(elem.nodeName):display;if(checkDisplay==="inline"&&jQuery.css(elem,"float")==="none"){style.display="inline-block"}}if(opts.overflow){style.overflow="hidden";anim.always(function(){style.overflow=opts.overflow[0];style.overflowX=opts.overflow[1];style.overflowY=opts.overflow[2]})}for(prop in props){value=props[prop];if(rfxtypes.exec(value)){delete props[prop];toggle=toggle||value==="toggle";if(value===(hidden?"hide":"show")){if(value==="show"&&dataShow&&dataShow[prop]!==undefined){hidden=true}else{continue}}orig[prop]=dataShow&&dataShow[prop]||jQuery.style(elem,prop)}else{display=undefined}}if(!jQuery.isEmptyObject(orig)){if(dataShow){if("hidden" in dataShow){hidden=dataShow.hidden}}else{dataShow=data_priv.access(elem,"fxshow",{})}if(toggle){dataShow.hidden=!hidden}if(hidden){jQuery(elem).show()}else{anim.done(function(){jQuery(elem).hide()})}anim.done(function(){var prop;data_priv.remove(elem,"fxshow");for(prop in orig){jQuery.style(elem,prop,orig[prop])}});for(prop in orig){tween=createTween(hidden?dataShow[prop]:0,prop,anim);if(!(prop in dataShow)){dataShow[prop]=tween.start;if(hidden){tween.end=tween.start;tween.start=prop==="width"||prop==="height"?1:0}}}}else{if((display==="none"?defaultDisplay(elem.nodeName):display)==="inline"){style.display=display}}}function propFilter(props,specialEasing){var index,name,easing,value,hooks;for(index in props){name=jQuery.camelCase(index);easing=specialEasing[name];value=props[index];if(jQuery.isArray(value)){easing=value[1];value=props[index]=value[0]}if(index!==name){props[name]=value;delete props[index]}hooks=jQuery.cssHooks[name];if(hooks&&"expand" in hooks){value=hooks.expand(value);delete props[name];for(index in value){if(!(index in props)){props[index]=value[index];specialEasing[index]=easing}}}else{specialEasing[name]=easing}}}function Animation(elem,properties,options){var result,stopped,index=0,length=animationPrefilters.length,deferred=jQuery.Deferred().always(function(){delete tick.elem}),tick=function(){if(stopped){return false}var currentTime=fxNow||createFxNow(),remaining=Math.max(0,animation.startTime+animation.duration-currentTime),temp=remaining/animation.duration||0,percent=1-temp,index=0,length=animation.tweens.length;for(;index<length;index++){animation.tweens[index].run(percent)}deferred.notifyWith(elem,[animation,percent,remaining]);if(percent<1&&length){return remaining}else{deferred.resolveWith(elem,[animation]);return false}},animation=deferred.promise({elem:elem,props:jQuery.extend({},properties),opts:jQuery.extend(true,{specialEasing:{}},options),originalProperties:properties,originalOptions:options,startTime:fxNow||createFxNow(),duration:options.duration,tweens:[],createTween:function(prop,end){var tween=jQuery.Tween(elem,animation.opts,prop,end,animation.opts.specialEasing[prop]||animation.opts.easing);animation.tweens.push(tween);return tween},stop:function(gotoEnd){var index=0,length=gotoEnd?animation.tweens.length:0;if(stopped){return this}stopped=true;for(;index<length;index++){animation.tweens[index].run(1)}if(gotoEnd){deferred.resolveWith(elem,[animation,gotoEnd])}else{deferred.rejectWith(elem,[animation,gotoEnd])}return this}}),props=animation.props;propFilter(props,animation.opts.specialEasing);for(;index<length;index++){result=animationPrefilters[index].call(animation,elem,props,animation.opts);if(result){return result}}jQuery.map(props,createTween,animation);if(jQuery.isFunction(animation.opts.start)){animation.opts.start.call(elem,animation)}jQuery.fx.timer(jQuery.extend(tick,{elem:elem,anim:animation,queue:animation.opts.queue}));return animation.progress(animation.opts.progress).done(animation.opts.done,animation.opts.complete).fail(animation.opts.fail).always(animation.opts.always)}jQuery.Animation=jQuery.extend(Animation,{tweener:function(props,callback){if(jQuery.isFunction(props)){callback=props;props=["*"]}else{props=props.split(" ")}var prop,index=0,length=props.length;for(;index<length;index++){prop=props[index];tweeners[prop]=tweeners[prop]||[];tweeners[prop].unshift(callback)}},prefilter:function(callback,prepend){if(prepend){animationPrefilters.unshift(callback)}else{animationPrefilters.push(callback)}}});jQuery.speed=function(speed,easing,fn){var opt=speed&&typeof speed==="object"?jQuery.extend({},speed):{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&!jQuery.isFunction(easing)&&easing};opt.duration=jQuery.fx.off?0:typeof opt.duration==="number"?opt.duration:opt.duration in jQuery.fx.speeds?jQuery.fx.speeds[opt.duration]:jQuery.fx.speeds._default;if(opt.queue==null||opt.queue===true){opt.queue="fx"}opt.old=opt.complete;opt.complete=function(){if(jQuery.isFunction(opt.old)){opt.old.call(this)}if(opt.queue){jQuery.dequeue(this,opt.queue)}};return opt};jQuery.fn.extend({fadeTo:function(speed,to,easing,callback){return this.filter(isHidden).css("opacity",0).show().end().animate({opacity:to},speed,easing,callback)},animate:function(prop,speed,easing,callback){var empty=jQuery.isEmptyObject(prop),optall=jQuery.speed(speed,easing,callback),doAnimation=function(){var anim=Animation(this,jQuery.extend({},prop),optall);if(empty||data_priv.get(this,"finish")){anim.stop(true)}};doAnimation.finish=doAnimation;return empty||optall.queue===false?this.each(doAnimation):this.queue(optall.queue,doAnimation)},stop:function(type,clearQueue,gotoEnd){var stopQueue=function(hooks){var stop=hooks.stop;delete hooks.stop;stop(gotoEnd)};if(typeof type!=="string"){gotoEnd=clearQueue;clearQueue=type;type=undefined}if(clearQueue&&type!==false){this.queue(type||"fx",[])}return this.each(function(){var dequeue=true,index=type!=null&&type+"queueHooks",timers=jQuery.timers,data=data_priv.get(this);if(index){if(data[index]&&data[index].stop){stopQueue(data[index])}}else{for(index in data){if(data[index]&&data[index].stop&&rrun.test(index)){stopQueue(data[index])}}}for(index=timers.length;index--;){if(timers[index].elem===this&&(type==null||timers[index].queue===type)){timers[index].anim.stop(gotoEnd);dequeue=false;timers.splice(index,1)}}if(dequeue||!gotoEnd){jQuery.dequeue(this,type)}})},finish:function(type){if(type!==false){type=type||"fx"}return this.each(function(){var index,data=data_priv.get(this),queue=data[type+"queue"],hooks=data[type+"queueHooks"],timers=jQuery.timers,length=queue?queue.length:0;data.finish=true;jQuery.queue(this,type,[]);if(hooks&&hooks.stop){hooks.stop.call(this,true)}for(index=timers.length;index--;){if(timers[index].elem===this&&timers[index].queue===type){timers[index].anim.stop(true);timers.splice(index,1)}}for(index=0;index<length;index++){if(queue[index]&&queue[index].finish){queue[index].finish.call(this)}}delete data.finish})}});jQuery.each(["toggle","show","hide"],function(i,name){var cssFn=jQuery.fn[name];jQuery.fn[name]=function(speed,easing,callback){return speed==null||typeof speed==="boolean"?cssFn.apply(this,arguments):this.animate(genFx(name,true),speed,easing,callback)}});jQuery.each({slideDown:genFx("show"),slideUp:genFx("hide"),slideToggle:genFx("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(name,props){jQuery.fn[name]=function(speed,easing,callback){return this.animate(props,speed,easing,callback)}});jQuery.timers=[];jQuery.fx.tick=function(){var timer,i=0,timers=jQuery.timers;fxNow=jQuery.now();for(;i<timers.length;i++){timer=timers[i];if(!timer()&&timers[i]===timer){timers.splice(i--,1)}}if(!timers.length){jQuery.fx.stop()}fxNow=undefined};jQuery.fx.timer=function(timer){jQuery.timers.push(timer);if(timer()){jQuery.fx.start()}else{jQuery.timers.pop()}};jQuery.fx.interval=13;jQuery.fx.start=function(){if(!timerId){timerId=setInterval(jQuery.fx.tick,jQuery.fx.interval)}};jQuery.fx.stop=function(){clearInterval(timerId);timerId=null};jQuery.fx.speeds={slow:600,fast:200,_default:400};jQuery.fn.delay=function(time,type){time=jQuery.fx?jQuery.fx.speeds[time]||time:time;type=type||"fx";return this.queue(type,function(next,hooks){var timeout=setTimeout(next,time);hooks.stop=function(){clearTimeout(timeout)}})};(function(){var input=document.createElement("input"),select=document.createElement("select"),opt=select.appendChild(document.createElement("option"));input.type="checkbox";support.checkOn=input.value!=="";support.optSelected=opt.selected;select.disabled=true;support.optDisabled=!opt.disabled;input=document.createElement("input");input.value="t";input.type="radio";support.radioValue=input.value==="t"})();var nodeHook,boolHook,attrHandle=jQuery.expr.attrHandle;jQuery.fn.extend({attr:function(name,value){return access(this,jQuery.attr,name,value,arguments.length>1)},removeAttr:function(name){return this.each(function(){jQuery.removeAttr(this,name)})}});jQuery.extend({attr:function(elem,name,value){var hooks,ret,nType=elem.nodeType;if(!elem||nType===3||nType===8||nType===2){return}if(typeof elem.getAttribute===strundefined){return jQuery.prop(elem,name,value)}if(nType!==1||!jQuery.isXMLDoc(elem)){name=name.toLowerCase();hooks=jQuery.attrHooks[name]||(jQuery.expr.match.bool.test(name)?boolHook:nodeHook)}if(value!==undefined){if(value===null){jQuery.removeAttr(elem,name)}else{if(hooks&&"set" in hooks&&(ret=hooks.set(elem,value,name))!==undefined){return ret}else{elem.setAttribute(name,value+"");return value}}}else{if(hooks&&"get" in hooks&&(ret=hooks.get(elem,name))!==null){return ret}else{ret=jQuery.find.attr(elem,name);return ret==null?undefined:ret}}},removeAttr:function(elem,value){var name,propName,i=0,attrNames=value&&value.match(rnotwhite);if(attrNames&&elem.nodeType===1){while((name=attrNames[i++])){propName=jQuery.propFix[name]||name;if(jQuery.expr.match.bool.test(name)){elem[propName]=false}elem.removeAttribute(name)}}},attrHooks:{type:{set:function(elem,value){if(!support.radioValue&&value==="radio"&&jQuery.nodeName(elem,"input")){var val=elem.value;elem.setAttribute("type",value);if(val){elem.value=val}return value}}}}});boolHook={set:function(elem,value,name){if(value===false){jQuery.removeAttr(elem,name)}else{elem.setAttribute(name,name)}return name}};jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g),function(i,name){var getter=attrHandle[name]||jQuery.find.attr;attrHandle[name]=function(elem,name,isXML){var ret,handle;if(!isXML){handle=attrHandle[name];attrHandle[name]=ret;ret=getter(elem,name,isXML)!=null?name.toLowerCase():null;attrHandle[name]=handle}return ret}});var rfocusable=/^(?:input|select|textarea|button)$/i;jQuery.fn.extend({prop:function(name,value){return access(this,jQuery.prop,name,value,arguments.length>1)},removeProp:function(name){return this.each(function(){delete this[jQuery.propFix[name]||name]})}});jQuery.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(elem,name,value){var ret,hooks,notxml,nType=elem.nodeType;if(!elem||nType===3||nType===8||nType===2){return}notxml=nType!==1||!jQuery.isXMLDoc(elem);if(notxml){name=jQuery.propFix[name]||name;hooks=jQuery.propHooks[name]}if(value!==undefined){return hooks&&"set" in hooks&&(ret=hooks.set(elem,value,name))!==undefined?ret:(elem[name]=value)}else{return hooks&&"get" in hooks&&(ret=hooks.get(elem,name))!==null?ret:elem[name]}},propHooks:{tabIndex:{get:function(elem){return elem.hasAttribute("tabindex")||rfocusable.test(elem.nodeName)||elem.href?elem.tabIndex:-1}}}});if(!support.optSelected){jQuery.propHooks.selected={get:function(elem){var parent=elem.parentNode;if(parent&&parent.parentNode){parent.parentNode.selectedIndex}return null}}}jQuery.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){jQuery.propFix[this.toLowerCase()]=this});var rclass=/[\t\r\n\f]/g;jQuery.fn.extend({addClass:function(value){var classes,elem,cur,clazz,j,finalValue,proceed=typeof value==="string"&&value,i=0,len=this.length;if(jQuery.isFunction(value)){return this.each(function(j){jQuery(this).addClass(value.call(this,j,this.className))})}if(proceed){classes=(value||"").match(rnotwhite)||[];for(;i<len;i++){elem=this[i];cur=elem.nodeType===1&&(elem.className?(" "+elem.className+" ").replace(rclass," "):" ");if(cur){j=0;while((clazz=classes[j++])){if(cur.indexOf(" "+clazz+" ")<0){cur+=clazz+" "}}finalValue=jQuery.trim(cur);if(elem.className!==finalValue){elem.className=finalValue}}}}return this},removeClass:function(value){var classes,elem,cur,clazz,j,finalValue,proceed=arguments.length===0||typeof value==="string"&&value,i=0,len=this.length;if(jQuery.isFunction(value)){return this.each(function(j){jQuery(this).removeClass(value.call(this,j,this.className))})}if(proceed){classes=(value||"").match(rnotwhite)||[];for(;i<len;i++){elem=this[i];cur=elem.nodeType===1&&(elem.className?(" "+elem.className+" ").replace(rclass," "):"");if(cur){j=0;while((clazz=classes[j++])){while(cur.indexOf(" "+clazz+" ")>=0){cur=cur.replace(" "+clazz+" "," ")}}finalValue=value?jQuery.trim(cur):"";if(elem.className!==finalValue){elem.className=finalValue}}}}return this},toggleClass:function(value,stateVal){var type=typeof value;if(typeof stateVal==="boolean"&&type==="string"){return stateVal?this.addClass(value):this.removeClass(value)}if(jQuery.isFunction(value)){return this.each(function(i){jQuery(this).toggleClass(value.call(this,i,this.className,stateVal),stateVal)})}return this.each(function(){if(type==="string"){var className,i=0,self=jQuery(this),classNames=value.match(rnotwhite)||[];while((className=classNames[i++])){if(self.hasClass(className)){self.removeClass(className)}else{self.addClass(className)}}}else{if(type===strundefined||type==="boolean"){if(this.className){data_priv.set(this,"__className__",this.className)}this.className=this.className||value===false?"":data_priv.get(this,"__className__")||""}}})},hasClass:function(selector){var className=" "+selector+" ",i=0,l=this.length;for(;i<l;i++){if(this[i].nodeType===1&&(" "+this[i].className+" ").replace(rclass," ").indexOf(className)>=0){return true}}return false}});var rreturn=/\r/g;jQuery.fn.extend({val:function(value){var hooks,ret,isFunction,elem=this[0];if(!arguments.length){if(elem){hooks=jQuery.valHooks[elem.type]||jQuery.valHooks[elem.nodeName.toLowerCase()];if(hooks&&"get" in hooks&&(ret=hooks.get(elem,"value"))!==undefined){return ret}ret=elem.value;return typeof ret==="string"?ret.replace(rreturn,""):ret==null?"":ret}return}isFunction=jQuery.isFunction(value);return this.each(function(i){var val;if(this.nodeType!==1){return}if(isFunction){val=value.call(this,i,jQuery(this).val())}else{val=value}if(val==null){val=""}else{if(typeof val==="number"){val+=""}else{if(jQuery.isArray(val)){val=jQuery.map(val,function(value){return value==null?"":value+""})}}}hooks=jQuery.valHooks[this.type]||jQuery.valHooks[this.nodeName.toLowerCase()];if(!hooks||!("set" in hooks)||hooks.set(this,val,"value")===undefined){this.value=val}})}});jQuery.extend({valHooks:{option:{get:function(elem){var val=jQuery.find.attr(elem,"value");return val!=null?val:jQuery.trim(jQuery.text(elem))}},select:{get:function(elem){var value,option,options=elem.options,index=elem.selectedIndex,one=elem.type==="select-one"||index<0,values=one?null:[],max=one?index+1:options.length,i=index<0?max:one?index:0;for(;i<max;i++){option=options[i];if((option.selected||i===index)&&(support.optDisabled?!option.disabled:option.getAttribute("disabled")===null)&&(!option.parentNode.disabled||!jQuery.nodeName(option.parentNode,"optgroup"))){value=jQuery(option).val();if(one){return value}values.push(value)}}return values},set:function(elem,value){var optionSet,option,options=elem.options,values=jQuery.makeArray(value),i=options.length;while(i--){option=options[i];if((option.selected=jQuery.inArray(option.value,values)>=0)){optionSet=true}}if(!optionSet){elem.selectedIndex=-1}return values}}}});jQuery.each(["radio","checkbox"],function(){jQuery.valHooks[this]={set:function(elem,value){if(jQuery.isArray(value)){return(elem.checked=jQuery.inArray(jQuery(elem).val(),value)>=0)}}};if(!support.checkOn){jQuery.valHooks[this].get=function(elem){return elem.getAttribute("value")===null?"on":elem.value}}});jQuery.each(("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu").split(" "),function(i,name){jQuery.fn[name]=function(data,fn){return arguments.length>0?this.on(name,null,data,fn):this.trigger(name)}});jQuery.fn.extend({hover:function(fnOver,fnOut){return this.mouseenter(fnOver).mouseleave(fnOut||fnOver)},bind:function(types,data,fn){return this.on(types,null,data,fn)},unbind:function(types,fn){return this.off(types,null,fn)},delegate:function(selector,types,data,fn){return this.on(types,selector,data,fn)},undelegate:function(selector,types,fn){return arguments.length===1?this.off(selector,"**"):this.off(types,selector||"**",fn)}});var nonce=jQuery.now();var rquery=(/\?/);jQuery.parseJSON=function(data){return JSON.parse(data+"")};jQuery.parseXML=function(data){var xml,tmp;if(!data||typeof data!=="string"){return null}try{tmp=new DOMParser();xml=tmp.parseFromString(data,"text/xml")}catch(e){xml=undefined}if(!xml||xml.getElementsByTagName("parsererror").length){jQuery.error("Invalid XML: "+data)}return xml};var rhash=/#.*$/,rts=/([?&])_=[^&]*/,rheaders=/^(.*?):[ \t]*([^\r\n]*)$/mg,rlocalProtocol=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,rnoContent=/^(?:GET|HEAD)$/,rprotocol=/^\/\//,rurl=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,prefilters={},transports={},allTypes="*/".concat("*"),ajaxLocation=window.location.href,ajaxLocParts=rurl.exec(ajaxLocation.toLowerCase())||[];function addToPrefiltersOrTransports(structure){return function(dataTypeExpression,func){if(typeof dataTypeExpression!=="string"){func=dataTypeExpression;dataTypeExpression="*"}var dataType,i=0,dataTypes=dataTypeExpression.toLowerCase().match(rnotwhite)||[];if(jQuery.isFunction(func)){while((dataType=dataTypes[i++])){if(dataType[0]==="+"){dataType=dataType.slice(1)||"*";(structure[dataType]=structure[dataType]||[]).unshift(func)}else{(structure[dataType]=structure[dataType]||[]).push(func)}}}}}function inspectPrefiltersOrTransports(structure,options,originalOptions,jqXHR){var inspected={},seekingTransport=(structure===transports);function inspect(dataType){var selected;inspected[dataType]=true;jQuery.each(structure[dataType]||[],function(_,prefilterOrFactory){var dataTypeOrTransport=prefilterOrFactory(options,originalOptions,jqXHR);if(typeof dataTypeOrTransport==="string"&&!seekingTransport&&!inspected[dataTypeOrTransport]){options.dataTypes.unshift(dataTypeOrTransport);inspect(dataTypeOrTransport);return false}else{if(seekingTransport){return !(selected=dataTypeOrTransport)}}});return selected}return inspect(options.dataTypes[0])||!inspected["*"]&&inspect("*")}function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:(deep||(deep={})))[key]=src[key]}}if(deep){jQuery.extend(true,target,deep)}return target}function ajaxHandleResponses(s,jqXHR,responses){var ct,type,finalDataType,firstDataType,contents=s.contents,dataTypes=s.dataTypes;while(dataTypes[0]==="*"){dataTypes.shift();if(ct===undefined){ct=s.mimeType||jqXHR.getResponseHeader("Content-Type")}}if(ct){for(type in contents){if(contents[type]&&contents[type].test(ct)){dataTypes.unshift(type);break}}}if(dataTypes[0] in responses){finalDataType=dataTypes[0]}else{for(type in responses){if(!dataTypes[0]||s.converters[type+" "+dataTypes[0]]){finalDataType=type;break}if(!firstDataType){firstDataType=type}}finalDataType=finalDataType||firstDataType}if(finalDataType){if(finalDataType!==dataTypes[0]){dataTypes.unshift(finalDataType)}return responses[finalDataType]}}function ajaxConvert(s,response,jqXHR,isSuccess){var conv2,current,conv,tmp,prev,converters={},dataTypes=s.dataTypes.slice();if(dataTypes[1]){for(conv in s.converters){converters[conv.toLowerCase()]=s.converters[conv]}}current=dataTypes.shift();while(current){if(s.responseFields[current]){jqXHR[s.responseFields[current]]=response}if(!prev&&isSuccess&&s.dataFilter){response=s.dataFilter(response,s.dataType)}prev=current;current=dataTypes.shift();if(current){if(current==="*"){current=prev}else{if(prev!=="*"&&prev!==current){conv=converters[prev+" "+current]||converters["* "+current];if(!conv){for(conv2 in converters){tmp=conv2.split(" ");if(tmp[1]===current){conv=converters[prev+" "+tmp[0]]||converters["* "+tmp[0]];if(conv){if(conv===true){conv=converters[conv2]}else{if(converters[conv2]!==true){current=tmp[0];dataTypes.unshift(tmp[1])}}break}}}}if(conv!==true){if(conv&&s["throws"]){response=conv(response)}else{try{response=conv(response)}catch(e){return{state:"parsererror",error:conv?e:"No conversion from "+prev+" to "+current}}}}}}}}return{state:"success",data:response}}jQuery.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:ajaxLocation,type:"GET",isLocal:rlocalProtocol.test(ajaxLocParts[1]),global:true,processData:true,async:true,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":allTypes,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":true,"text json":jQuery.parseJSON,"text xml":jQuery.parseXML},flatOptions:{url:true,context:true}},ajaxSetup:function(target,settings){return settings?ajaxExtend(ajaxExtend(target,jQuery.ajaxSettings),settings):ajaxExtend(jQuery.ajaxSettings,target)},ajaxPrefilter:addToPrefiltersOrTransports(prefilters),ajaxTransport:addToPrefiltersOrTransports(transports),ajax:function(url,options){if(typeof url==="object"){options=url;url=undefined}options=options||{};var transport,cacheURL,responseHeadersString,responseHeaders,timeoutTimer,parts,fireGlobals,i,s=jQuery.ajaxSetup({},options),callbackContext=s.context||s,globalEventContext=s.context&&(callbackContext.nodeType||callbackContext.jquery)?jQuery(callbackContext):jQuery.event,deferred=jQuery.Deferred(),completeDeferred=jQuery.Callbacks("once memory"),statusCode=s.statusCode||{},requestHeaders={},requestHeadersNames={},state=0,strAbort="canceled",jqXHR={readyState:0,getResponseHeader:function(key){var match;if(state===2){if(!responseHeaders){responseHeaders={};while((match=rheaders.exec(responseHeadersString))){responseHeaders[match[1].toLowerCase()]=match[2]}}match=responseHeaders[key.toLowerCase()]}return match==null?null:match},getAllResponseHeaders:function(){return state===2?responseHeadersString:null},setRequestHeader:function(name,value){var lname=name.toLowerCase();if(!state){name=requestHeadersNames[lname]=requestHeadersNames[lname]||name;requestHeaders[name]=value}return this},overrideMimeType:function(type){if(!state){s.mimeType=type}return this},statusCode:function(map){var code;if(map){if(state<2){for(code in map){statusCode[code]=[statusCode[code],map[code]]}}else{jqXHR.always(map[jqXHR.status])}}return this},abort:function(statusText){var finalText=statusText||strAbort;if(transport){transport.abort(finalText)}done(0,finalText);return this}};deferred.promise(jqXHR).complete=completeDeferred.add;jqXHR.success=jqXHR.done;jqXHR.error=jqXHR.fail;s.url=((url||s.url||ajaxLocation)+"").replace(rhash,"").replace(rprotocol,ajaxLocParts[1]+"//");s.type=options.method||options.type||s.method||s.type;s.dataTypes=jQuery.trim(s.dataType||"*").toLowerCase().match(rnotwhite)||[""];if(s.crossDomain==null){parts=rurl.exec(s.url.toLowerCase());s.crossDomain=!!(parts&&(parts[1]!==ajaxLocParts[1]||parts[2]!==ajaxLocParts[2]||(parts[3]||(parts[1]==="http:"?"80":"443"))!==(ajaxLocParts[3]||(ajaxLocParts[1]==="http:"?"80":"443"))))}if(s.data&&s.processData&&typeof s.data!=="string"){s.data=jQuery.param(s.data,s.traditional)}inspectPrefiltersOrTransports(prefilters,s,options,jqXHR);if(state===2){return jqXHR}fireGlobals=jQuery.event&&s.global;if(fireGlobals&&jQuery.active++===0){jQuery.event.trigger("ajaxStart")}s.type=s.type.toUpperCase();s.hasContent=!rnoContent.test(s.type);cacheURL=s.url;if(!s.hasContent){if(s.data){cacheURL=(s.url+=(rquery.test(cacheURL)?"&":"?")+s.data);delete s.data}if(s.cache===false){s.url=rts.test(cacheURL)?cacheURL.replace(rts,"$1_="+nonce++):cacheURL+(rquery.test(cacheURL)?"&":"?")+"_="+nonce++}}if(s.ifModified){if(jQuery.lastModified[cacheURL]){jqXHR.setRequestHeader("If-Modified-Since",jQuery.lastModified[cacheURL])}if(jQuery.etag[cacheURL]){jqXHR.setRequestHeader("If-None-Match",jQuery.etag[cacheURL])}}if(s.data&&s.hasContent&&s.contentType!==false||options.contentType){jqXHR.setRequestHeader("Content-Type",s.contentType)}jqXHR.setRequestHeader("Accept",s.dataTypes[0]&&s.accepts[s.dataTypes[0]]?s.accepts[s.dataTypes[0]]+(s.dataTypes[0]!=="*"?", "+allTypes+"; q=0.01":""):s.accepts["*"]);for(i in s.headers){jqXHR.setRequestHeader(i,s.headers[i])}if(s.beforeSend&&(s.beforeSend.call(callbackContext,jqXHR,s)===false||state===2)){return jqXHR.abort()}strAbort="abort";for(i in {success:1,error:1,complete:1}){jqXHR[i](s[i])}transport=inspectPrefiltersOrTransports(transports,s,options,jqXHR);if(!transport){done(-1,"No Transport")}else{jqXHR.readyState=1;if(fireGlobals){globalEventContext.trigger("ajaxSend",[jqXHR,s])}if(s.async&&s.timeout>0){timeoutTimer=setTimeout(function(){jqXHR.abort("timeout")},s.timeout)}try{state=1;transport.send(requestHeaders,done)}catch(e){if(state<2){done(-1,e)}else{throw e}}}function done(status,nativeStatusText,responses,headers){var isSuccess,success,error,response,modified,statusText=nativeStatusText;if(state===2){return}state=2;if(timeoutTimer){clearTimeout(timeoutTimer)}transport=undefined;responseHeadersString=headers||"";jqXHR.readyState=status>0?4:0;isSuccess=status>=200&&status<300||status===304;if(responses){response=ajaxHandleResponses(s,jqXHR,responses)}response=ajaxConvert(s,response,jqXHR,isSuccess);if(isSuccess){if(s.ifModified){modified=jqXHR.getResponseHeader("Last-Modified");if(modified){jQuery.lastModified[cacheURL]=modified}modified=jqXHR.getResponseHeader("etag");if(modified){jQuery.etag[cacheURL]=modified}}if(status===204||s.type==="HEAD"){statusText="nocontent"}else{if(status===304){statusText="notmodified"}else{statusText=response.state;success=response.data;error=response.error;isSuccess=!error}}}else{error=statusText;if(status||!statusText){statusText="error";if(status<0){status=0}}}jqXHR.status=status;jqXHR.statusText=(nativeStatusText||statusText)+"";if(isSuccess){deferred.resolveWith(callbackContext,[success,statusText,jqXHR])}else{deferred.rejectWith(callbackContext,[jqXHR,statusText,error])}jqXHR.statusCode(statusCode);statusCode=undefined;if(fireGlobals){globalEventContext.trigger(isSuccess?"ajaxSuccess":"ajaxError",[jqXHR,s,isSuccess?success:error])}completeDeferred.fireWith(callbackContext,[jqXHR,statusText]);if(fireGlobals){globalEventContext.trigger("ajaxComplete",[jqXHR,s]);if(!(--jQuery.active)){jQuery.event.trigger("ajaxStop")}}}return jqXHR},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json")},getScript:function(url,callback){return jQuery.get(url,undefined,callback,"script")}});jQuery.each(["get","post"],function(i,method){jQuery[method]=function(url,data,callback,type){if(jQuery.isFunction(data)){type=type||callback;callback=data;data=undefined}return jQuery.ajax({url:url,type:method,dataType:type,data:data,success:callback})}});jQuery._evalUrl=function(url){return jQuery.ajax({url:url,type:"GET",dataType:"script",async:false,global:false,"throws":true})};jQuery.fn.extend({wrapAll:function(html){var wrap;if(jQuery.isFunction(html)){return this.each(function(i){jQuery(this).wrapAll(html.call(this,i))})}if(this[0]){wrap=jQuery(html,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){wrap.insertBefore(this[0])}wrap.map(function(){var elem=this;while(elem.firstElementChild){elem=elem.firstElementChild}return elem}).append(this)}return this},wrapInner:function(html){if(jQuery.isFunction(html)){return this.each(function(i){jQuery(this).wrapInner(html.call(this,i))})}return this.each(function(){var self=jQuery(this),contents=self.contents();if(contents.length){contents.wrapAll(html)}else{self.append(html)}})},wrap:function(html){var isFunction=jQuery.isFunction(html);return this.each(function(i){jQuery(this).wrapAll(isFunction?html.call(this,i):html)})},unwrap:function(){return this.parent().each(function(){if(!jQuery.nodeName(this,"body")){jQuery(this).replaceWith(this.childNodes)}}).end()}});jQuery.expr.filters.hidden=function(elem){return elem.offsetWidth<=0&&elem.offsetHeight<=0};jQuery.expr.filters.visible=function(elem){return !jQuery.expr.filters.hidden(elem)};var r20=/%20/g,rbracket=/\[\]$/,rCRLF=/\r?\n/g,rsubmitterTypes=/^(?:submit|button|image|reset|file)$/i,rsubmittable=/^(?:input|select|textarea|keygen)/i;function buildParams(prefix,obj,traditional,add){var name;if(jQuery.isArray(obj)){jQuery.each(obj,function(i,v){if(traditional||rbracket.test(prefix)){add(prefix,v)}else{buildParams(prefix+"["+(typeof v==="object"?i:"")+"]",v,traditional,add)}})}else{if(!traditional&&jQuery.type(obj)==="object"){for(name in obj){buildParams(prefix+"["+name+"]",obj[name],traditional,add)}}else{add(prefix,obj)}}}jQuery.param=function(a,traditional){var prefix,s=[],add=function(key,value){value=jQuery.isFunction(value)?value():(value==null?"":value);s[s.length]=encodeURIComponent(key)+"="+encodeURIComponent(value)};if(traditional===undefined){traditional=jQuery.ajaxSettings&&jQuery.ajaxSettings.traditional}if(jQuery.isArray(a)||(a.jquery&&!jQuery.isPlainObject(a))){jQuery.each(a,function(){add(this.name,this.value)})}else{for(prefix in a){buildParams(prefix,a[prefix],traditional,add)}}return s.join("&").replace(r20,"+")};jQuery.fn.extend({serialize:function(){return jQuery.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var elements=jQuery.prop(this,"elements");return elements?jQuery.makeArray(elements):this}).filter(function(){var type=this.type;return this.name&&!jQuery(this).is(":disabled")&&rsubmittable.test(this.nodeName)&&!rsubmitterTypes.test(type)&&(this.checked||!rcheckableType.test(type))}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:jQuery.isArray(val)?jQuery.map(val,function(val){return{name:elem.name,value:val.replace(rCRLF,"\r\n")}}):{name:elem.name,value:val.replace(rCRLF,"\r\n")}}).get()}});jQuery.ajaxSettings.xhr=function(){try{return new XMLHttpRequest()}catch(e){}};var xhrId=0,xhrCallbacks={},xhrSuccessStatus={0:200,1223:204},xhrSupported=jQuery.ajaxSettings.xhr();if(window.attachEvent){window.attachEvent("onunload",function(){for(var key in xhrCallbacks){xhrCallbacks[key]()}})}support.cors=!!xhrSupported&&("withCredentials" in xhrSupported);support.ajax=xhrSupported=!!xhrSupported;jQuery.ajaxTransport(function(options){var callback;if(support.cors||xhrSupported&&!options.crossDomain){return{send:function(headers,complete){var i,xhr=options.xhr(),id=++xhrId;xhr.open(options.type,options.url,options.async,options.username,options.password);if(options.xhrFields){for(i in options.xhrFields){xhr[i]=options.xhrFields[i]}}if(options.mimeType&&xhr.overrideMimeType){xhr.overrideMimeType(options.mimeType)}if(!options.crossDomain&&!headers["X-Requested-With"]){headers["X-Requested-With"]="XMLHttpRequest"}for(i in headers){xhr.setRequestHeader(i,headers[i])}callback=function(type){return function(){if(callback){delete xhrCallbacks[id];callback=xhr.onload=xhr.onerror=null;if(type==="abort"){xhr.abort()}else{if(type==="error"){complete(xhr.status,xhr.statusText)}else{complete(xhrSuccessStatus[xhr.status]||xhr.status,xhr.statusText,typeof xhr.responseText==="string"?{text:xhr.responseText}:undefined,xhr.getAllResponseHeaders())}}}}};xhr.onload=callback();xhr.onerror=callback("error");callback=xhrCallbacks[id]=callback("abort");try{xhr.send(options.hasContent&&options.data||null)}catch(e){if(callback){throw e}}},abort:function(){if(callback){callback()}}}}});jQuery.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(text){jQuery.globalEval(text);return text}}});jQuery.ajaxPrefilter("script",function(s){if(s.cache===undefined){s.cache=false}if(s.crossDomain){s.type="GET"}});jQuery.ajaxTransport("script",function(s){if(s.crossDomain){var script,callback;return{send:function(_,complete){script=jQuery("<script>").prop({async:true,charset:s.scriptCharset,src:s.url}).on("load error",callback=function(evt){script.remove();callback=null;if(evt){complete(evt.type==="error"?404:200,evt.type)}});document.head.appendChild(script[0])},abort:function(){if(callback){callback()}}}}});var oldCallbacks=[],rjsonp=/(=)\?(?=&|$)|\?\?/;jQuery.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var callback=oldCallbacks.pop()||(jQuery.expando+"_"+(nonce++));this[callback]=true;return callback}});jQuery.ajaxPrefilter("json jsonp",function(s,originalSettings,jqXHR){var callbackName,overwritten,responseContainer,jsonProp=s.jsonp!==false&&(rjsonp.test(s.url)?"url":typeof s.data==="string"&&!(s.contentType||"").indexOf("application/x-www-form-urlencoded")&&rjsonp.test(s.data)&&"data");if(jsonProp||s.dataTypes[0]==="jsonp"){callbackName=s.jsonpCallback=jQuery.isFunction(s.jsonpCallback)?s.jsonpCallback():s.jsonpCallback;if(jsonProp){s[jsonProp]=s[jsonProp].replace(rjsonp,"$1"+callbackName)}else{if(s.jsonp!==false){s.url+=(rquery.test(s.url)?"&":"?")+s.jsonp+"="+callbackName}}s.converters["script json"]=function(){if(!responseContainer){jQuery.error(callbackName+" was not called")}return responseContainer[0]};s.dataTypes[0]="json";overwritten=window[callbackName];window[callbackName]=function(){responseContainer=arguments};jqXHR.always(function(){window[callbackName]=overwritten;if(s[callbackName]){s.jsonpCallback=originalSettings.jsonpCallback;oldCallbacks.push(callbackName)}if(responseContainer&&jQuery.isFunction(overwritten)){overwritten(responseContainer[0])}responseContainer=overwritten=undefined});return"script"}});jQuery.parseHTML=function(data,context,keepScripts){if(!data||typeof data!=="string"){return null}if(typeof context==="boolean"){keepScripts=context;context=false}context=context||document;var parsed=rsingleTag.exec(data),scripts=!keepScripts&&[];if(parsed){return[context.createElement(parsed[1])]}parsed=jQuery.buildFragment([data],context,scripts);if(scripts&&scripts.length){jQuery(scripts).remove()}return jQuery.merge([],parsed.childNodes)};var _load=jQuery.fn.load;jQuery.fn.load=function(url,params,callback){if(typeof url!=="string"&&_load){return _load.apply(this,arguments)}var selector,type,response,self=this,off=url.indexOf(" ");if(off>=0){selector=jQuery.trim(url.slice(off));url=url.slice(0,off)}if(jQuery.isFunction(params)){callback=params;params=undefined}else{if(params&&typeof params==="object"){type="POST"}}if(self.length>0){jQuery.ajax({url:url,type:type,dataType:"html",data:params}).done(function(responseText){response=arguments;self.html(selector?jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector):responseText)}).complete(callback&&function(jqXHR,status){self.each(callback,response||[jqXHR.responseText,status,jqXHR])})}return this};jQuery.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(i,type){jQuery.fn[type]=function(fn){return this.on(type,fn)}});jQuery.expr.filters.animated=function(elem){return jQuery.grep(jQuery.timers,function(fn){return elem===fn.elem}).length};var docElem=window.document.documentElement;function getWindow(elem){return jQuery.isWindow(elem)?elem:elem.nodeType===9&&elem.defaultView}jQuery.offset={setOffset:function(elem,options,i){var curPosition,curLeft,curCSSTop,curTop,curOffset,curCSSLeft,calculatePosition,position=jQuery.css(elem,"position"),curElem=jQuery(elem),props={};if(position==="static"){elem.style.position="relative"}curOffset=curElem.offset();curCSSTop=jQuery.css(elem,"top");curCSSLeft=jQuery.css(elem,"left");calculatePosition=(position==="absolute"||position==="fixed")&&(curCSSTop+curCSSLeft).indexOf("auto")>-1;if(calculatePosition){curPosition=curElem.position();curTop=curPosition.top;curLeft=curPosition.left}else{curTop=parseFloat(curCSSTop)||0;curLeft=parseFloat(curCSSLeft)||0}if(jQuery.isFunction(options)){options=options.call(elem,i,curOffset)}if(options.top!=null){props.top=(options.top-curOffset.top)+curTop}if(options.left!=null){props.left=(options.left-curOffset.left)+curLeft}if("using" in options){options.using.call(elem,props)}else{curElem.css(props)}}};jQuery.fn.extend({offset:function(options){if(arguments.length){return options===undefined?this:this.each(function(i){jQuery.offset.setOffset(this,options,i)})}var docElem,win,elem=this[0],box={top:0,left:0},doc=elem&&elem.ownerDocument;if(!doc){return}docElem=doc.documentElement;if(!jQuery.contains(docElem,elem)){return box}if(typeof elem.getBoundingClientRect!==strundefined){box=elem.getBoundingClientRect()}win=getWindow(doc);return{top:box.top+win.pageYOffset-docElem.clientTop,left:box.left+win.pageXOffset-docElem.clientLeft}},position:function(){if(!this[0]){return}var offsetParent,offset,elem=this[0],parentOffset={top:0,left:0};if(jQuery.css(elem,"position")==="fixed"){offset=elem.getBoundingClientRect()}else{offsetParent=this.offsetParent();offset=this.offset();if(!jQuery.nodeName(offsetParent[0],"html")){parentOffset=offsetParent.offset()}parentOffset.top+=jQuery.css(offsetParent[0],"borderTopWidth",true);parentOffset.left+=jQuery.css(offsetParent[0],"borderLeftWidth",true)}return{top:offset.top-parentOffset.top-jQuery.css(elem,"marginTop",true),left:offset.left-parentOffset.left-jQuery.css(elem,"marginLeft",true)}},offsetParent:function(){return this.map(function(){var offsetParent=this.offsetParent||docElem;while(offsetParent&&(!jQuery.nodeName(offsetParent,"html")&&jQuery.css(offsetParent,"position")==="static")){offsetParent=offsetParent.offsetParent}return offsetParent||docElem})}});jQuery.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(method,prop){var top="pageYOffset"===prop;jQuery.fn[method]=function(val){return access(this,function(elem,method,val){var win=getWindow(elem);if(val===undefined){return win?win[prop]:elem[method]}if(win){win.scrollTo(!top?val:window.pageXOffset,top?val:window.pageYOffset)}else{elem[method]=val}},method,val,arguments.length,null)}});jQuery.each(["top","left"],function(i,prop){jQuery.cssHooks[prop]=addGetHookIf(support.pixelPosition,function(elem,computed){if(computed){computed=curCSS(elem,prop);return rnumnonpx.test(computed)?jQuery(elem).position()[prop]+"px":computed}})});jQuery.each({Height:"height",Width:"width"},function(name,type){jQuery.each({padding:"inner"+name,content:type,"":"outer"+name},function(defaultExtra,funcName){jQuery.fn[funcName]=function(margin,value){var chainable=arguments.length&&(defaultExtra||typeof margin!=="boolean"),extra=defaultExtra||(margin===true||value===true?"margin":"border");return access(this,function(elem,type,value){var doc;if(jQuery.isWindow(elem)){return elem.document.documentElement["client"+name]}if(elem.nodeType===9){doc=elem.documentElement;return Math.max(elem.body["scroll"+name],doc["scroll"+name],elem.body["offset"+name],doc["offset"+name],doc["client"+name])}return value===undefined?jQuery.css(elem,type,extra):jQuery.style(elem,type,value,extra)},type,chainable?margin:undefined,chainable,null)}})});jQuery.fn.size=function(){return this.length};jQuery.fn.andSelf=jQuery.fn.addBack;if(typeof define==="function"&&define.amd){define("jquery",[],function(){return jQuery})}var _jQuery=window.jQuery,_$=window.$;jQuery.noConflict=function(deep){if(window.$===jQuery){window.$=_$}if(deep&&window.jQuery===jQuery){window.jQuery=_jQuery}return jQuery};if(typeof noGlobal===strundefined){window.jQuery=window.$=jQuery}return jQuery}));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-2.1.3.min.js
jquery-2.1.3.min.js
if(typeof jQuery==="undefined"){throw new Error("Bootstrap's JavaScript requires jQuery")}+function(b){var a=b.fn.jquery.split(" ")[0].split(".");if((a[0]<2&&a[1]<9)||(a[0]==1&&a[1]==9&&a[2]<1)){throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}}(jQuery);+function(b){function a(){var e=document.createElement("bootstrap");var d={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in d){if(e.style[c]!==undefined){return{end:d[c]}}}return false}b.fn.emulateTransitionEnd=function(e){var d=false;var c=this;b(this).one("bsTransitionEnd",function(){d=true});var f=function(){if(!d){b(c).trigger(b.support.transition.end)}};setTimeout(f,e);return this};b(function(){b.support.transition=a();if(!b.support.transition){return}b.event.special.bsTransitionEnd={bindType:b.support.transition.end,delegateType:b.support.transition.end,handle:function(c){if(b(c.target).is(this)){return c.handleObj.handler.apply(this,arguments)}}}})}(jQuery);+function(e){var d='[data-dismiss="alert"]';var b=function(f){e(f).on("click",d,this.close)};b.VERSION="3.3.2";b.TRANSITION_DURATION=150;b.prototype.close=function(j){var i=e(this);var g=i.attr("data-target");if(!g){g=i.attr("href");g=g&&g.replace(/.*(?=#[^\s]*$)/,"")}var h=e(g);if(j){j.preventDefault()}if(!h.length){h=i.closest(".alert")}h.trigger(j=e.Event("close.bs.alert"));if(j.isDefaultPrevented()){return}h.removeClass("in");function f(){h.detach().trigger("closed.bs.alert").remove()}e.support.transition&&h.hasClass("fade")?h.one("bsTransitionEnd",f).emulateTransitionEnd(b.TRANSITION_DURATION):f()};function c(f){return this.each(function(){var h=e(this);var g=h.data("bs.alert");if(!g){h.data("bs.alert",(g=new b(this)))}if(typeof f=="string"){g[f].call(h)}})}var a=e.fn.alert;e.fn.alert=c;e.fn.alert.Constructor=b;e.fn.alert.noConflict=function(){e.fn.alert=a;return this};e(document).on("click.bs.alert.data-api",d,b.prototype.close)}(jQuery);+function(d){var b=function(f,e){this.$element=d(f);this.options=d.extend({},b.DEFAULTS,e);this.isLoading=false};b.VERSION="3.3.2";b.DEFAULTS={loadingText:"loading..."};b.prototype.setState=function(g){var i="disabled";var e=this.$element;var h=e.is("input")?"val":"html";var f=e.data();g=g+"Text";if(f.resetText==null){e.data("resetText",e[h]())}setTimeout(d.proxy(function(){e[h](f[g]==null?this.options[g]:f[g]);if(g=="loadingText"){this.isLoading=true;e.addClass(i).attr(i,i)}else{if(this.isLoading){this.isLoading=false;e.removeClass(i).removeAttr(i)}}},this),0)};b.prototype.toggle=function(){var f=true;var e=this.$element.closest('[data-toggle="buttons"]');if(e.length){var g=this.$element.find("input");if(g.prop("type")=="radio"){if(g.prop("checked")&&this.$element.hasClass("active")){f=false}else{e.find(".active").removeClass("active")}}if(f){g.prop("checked",!this.$element.hasClass("active")).trigger("change")}}else{this.$element.attr("aria-pressed",!this.$element.hasClass("active"))}if(f){this.$element.toggleClass("active")}};function c(e){return this.each(function(){var h=d(this);var g=h.data("bs.button");var f=typeof e=="object"&&e;if(!g){h.data("bs.button",(g=new b(this,f)))}if(e=="toggle"){g.toggle()}else{if(e){g.setState(e)}}})}var a=d.fn.button;d.fn.button=c;d.fn.button.Constructor=b;d.fn.button.noConflict=function(){d.fn.button=a;return this};d(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(g){var f=d(g.target);if(!f.hasClass("btn")){f=f.closest(".btn")}c.call(f,"toggle");g.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(f){d(f.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(f.type))})}(jQuery);+function(c){var d=function(g,f){this.$element=c(g);this.$indicators=this.$element.find(".carousel-indicators");this.options=f;this.paused=this.sliding=this.interval=this.$active=this.$items=null;this.options.keyboard&&this.$element.on("keydown.bs.carousel",c.proxy(this.keydown,this));this.options.pause=="hover"&&!("ontouchstart" in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",c.proxy(this.pause,this)).on("mouseleave.bs.carousel",c.proxy(this.cycle,this))};d.VERSION="3.3.2";d.TRANSITION_DURATION=600;d.DEFAULTS={interval:5000,pause:"hover",wrap:true,keyboard:true};d.prototype.keydown=function(f){if(/input|textarea/i.test(f.target.tagName)){return}switch(f.which){case 37:this.prev();break;case 39:this.next();break;default:return}f.preventDefault()};d.prototype.cycle=function(f){f||(this.paused=false);this.interval&&clearInterval(this.interval);this.options.interval&&!this.paused&&(this.interval=setInterval(c.proxy(this.next,this),this.options.interval));return this};d.prototype.getItemIndex=function(f){this.$items=f.parent().children(".item");return this.$items.index(f||this.$active)};d.prototype.getItemForDirection=function(j,i){var f=this.getItemIndex(i);var g=(j=="prev"&&f===0)||(j=="next"&&f==(this.$items.length-1));if(g&&!this.options.wrap){return i}var k=j=="prev"?-1:1;var h=(f+k)%this.$items.length;return this.$items.eq(h)};d.prototype.to=function(h){var g=this;var f=this.getItemIndex(this.$active=this.$element.find(".item.active"));if(h>(this.$items.length-1)||h<0){return}if(this.sliding){return this.$element.one("slid.bs.carousel",function(){g.to(h)})}if(f==h){return this.pause().cycle()}return this.slide(h>f?"next":"prev",this.$items.eq(h))};d.prototype.pause=function(f){f||(this.paused=true);if(this.$element.find(".next, .prev").length&&c.support.transition){this.$element.trigger(c.support.transition.end);this.cycle(true)}this.interval=clearInterval(this.interval);return this};d.prototype.next=function(){if(this.sliding){return}return this.slide("next")};d.prototype.prev=function(){if(this.sliding){return}return this.slide("prev")};d.prototype.slide=function(m,i){var p=this.$element.find(".item.active");var g=i||this.getItemForDirection(m,p);var k=this.interval;var n=m=="next"?"left":"right";var j=this;if(g.hasClass("active")){return(this.sliding=false)}var l=g[0];var f=c.Event("slide.bs.carousel",{relatedTarget:l,direction:n});this.$element.trigger(f);if(f.isDefaultPrevented()){return}this.sliding=true;k&&this.pause();if(this.$indicators.length){this.$indicators.find(".active").removeClass("active");var h=c(this.$indicators.children()[this.getItemIndex(g)]);h&&h.addClass("active")}var o=c.Event("slid.bs.carousel",{relatedTarget:l,direction:n});if(c.support.transition&&this.$element.hasClass("slide")){g.addClass(m);g[0].offsetWidth;p.addClass(n);g.addClass(n);p.one("bsTransitionEnd",function(){g.removeClass([m,n].join(" ")).addClass("active");p.removeClass(["active",n].join(" "));j.sliding=false;setTimeout(function(){j.$element.trigger(o)},0)}).emulateTransitionEnd(d.TRANSITION_DURATION)}else{p.removeClass("active");g.addClass("active");this.sliding=false;this.$element.trigger(o)}k&&this.cycle();return this};function b(f){return this.each(function(){var j=c(this);var i=j.data("bs.carousel");var g=c.extend({},d.DEFAULTS,j.data(),typeof f=="object"&&f);var h=typeof f=="string"?f:g.slide;if(!i){j.data("bs.carousel",(i=new d(this,g)))}if(typeof f=="number"){i.to(f)}else{if(h){i[h]()}else{if(g.interval){i.pause().cycle()}}}})}var a=c.fn.carousel;c.fn.carousel=b;c.fn.carousel.Constructor=d;c.fn.carousel.noConflict=function(){c.fn.carousel=a;return this};var e=function(k){var g;var j=c(this);var f=c(j.attr("data-target")||(g=j.attr("href"))&&g.replace(/.*(?=#[^\s]+$)/,""));if(!f.hasClass("carousel")){return}var h=c.extend({},f.data(),j.data());var i=j.attr("data-slide-to");if(i){h.interval=false}b.call(f,h);if(i){f.data("bs.carousel").to(i)}k.preventDefault()};c(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e);c(window).on("load",function(){c('[data-ride="carousel"]').each(function(){var f=c(this);b.call(f,f.data())})})}(jQuery);+function(d){var e=function(g,f){this.$element=d(g);this.options=d.extend({},e.DEFAULTS,f);this.$trigger=d(this.options.trigger).filter('[href="#'+g.id+'"], [data-target="#'+g.id+'"]');this.transitioning=null;if(this.options.parent){this.$parent=this.getParent()}else{this.addAriaAndCollapsedClass(this.$element,this.$trigger)}if(this.options.toggle){this.toggle()}};e.VERSION="3.3.2";e.TRANSITION_DURATION=350;e.DEFAULTS={toggle:true,trigger:'[data-toggle="collapse"]'};e.prototype.dimension=function(){var f=this.$element.hasClass("width");return f?"width":"height"};e.prototype.show=function(){if(this.transitioning||this.$element.hasClass("in")){return}var h;var j=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(j&&j.length){h=j.data("bs.collapse");if(h&&h.transitioning){return}}var g=d.Event("show.bs.collapse");this.$element.trigger(g);if(g.isDefaultPrevented()){return}if(j&&j.length){b.call(j,"hide");h||j.data("bs.collapse",null)}var k=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[k](0).attr("aria-expanded",true);this.$trigger.removeClass("collapsed").attr("aria-expanded",true);this.transitioning=1;var f=function(){this.$element.removeClass("collapsing").addClass("collapse in")[k]("");this.transitioning=0;this.$element.trigger("shown.bs.collapse")};if(!d.support.transition){return f.call(this)}var i=d.camelCase(["scroll",k].join("-"));this.$element.one("bsTransitionEnd",d.proxy(f,this)).emulateTransitionEnd(e.TRANSITION_DURATION)[k](this.$element[0][i])};e.prototype.hide=function(){if(this.transitioning||!this.$element.hasClass("in")){return}var g=d.Event("hide.bs.collapse");this.$element.trigger(g);if(g.isDefaultPrevented()){return}var h=this.dimension();this.$element[h](this.$element[h]())[0].offsetHeight;this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",false);this.$trigger.addClass("collapsed").attr("aria-expanded",false);this.transitioning=1;var f=function(){this.transitioning=0;this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};if(!d.support.transition){return f.call(this)}this.$element[h](0).one("bsTransitionEnd",d.proxy(f,this)).emulateTransitionEnd(e.TRANSITION_DURATION)};e.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};e.prototype.getParent=function(){return d(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(d.proxy(function(h,g){var f=d(g);this.addAriaAndCollapsedClass(c(f),f)},this)).end()};e.prototype.addAriaAndCollapsedClass=function(g,f){var h=g.hasClass("in");g.attr("aria-expanded",h);f.toggleClass("collapsed",!h).attr("aria-expanded",h)};function c(f){var g;var h=f.attr("data-target")||(g=f.attr("href"))&&g.replace(/.*(?=#[^\s]+$)/,"");return d(h)}function b(f){return this.each(function(){var i=d(this);var h=i.data("bs.collapse");var g=d.extend({},e.DEFAULTS,i.data(),typeof f=="object"&&f);if(!h&&g.toggle&&f=="show"){g.toggle=false}if(!h){i.data("bs.collapse",(h=new e(this,g)))}if(typeof f=="string"){h[f]()}})}var a=d.fn.collapse;d.fn.collapse=b;d.fn.collapse.Constructor=e;d.fn.collapse.noConflict=function(){d.fn.collapse=a;return this};d(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(j){var i=d(this);if(!i.attr("data-target")){j.preventDefault()}var f=c(i);var h=f.data("bs.collapse");var g=h?"toggle":d.extend({},i.data(),{trigger:this});b.call(f,g)})}(jQuery);+function(h){var e=".dropdown-backdrop";var b='[data-toggle="dropdown"]';var a=function(i){h(i).on("click.bs.dropdown",this.toggle)};a.VERSION="3.3.2";a.prototype.toggle=function(m){var l=h(this);if(l.is(".disabled, :disabled")){return}var k=f(l);var j=k.hasClass("open");d();if(!j){if("ontouchstart" in document.documentElement&&!k.closest(".navbar-nav").length){h('<div class="dropdown-backdrop"/>').insertAfter(h(this)).on("click",d)}var i={relatedTarget:this};k.trigger(m=h.Event("show.bs.dropdown",i));if(m.isDefaultPrevented()){return}l.trigger("focus").attr("aria-expanded","true");k.toggleClass("open").trigger("shown.bs.dropdown",i)}return false};a.prototype.keydown=function(m){if(!/(38|40|27|32)/.test(m.which)||/input|textarea/i.test(m.target.tagName)){return}var l=h(this);m.preventDefault();m.stopPropagation();if(l.is(".disabled, :disabled")){return}var k=f(l);var j=k.hasClass("open");if((!j&&m.which!=27)||(j&&m.which==27)){if(m.which==27){k.find(b).trigger("focus")}return l.trigger("click")}var n=" li:not(.divider):visible a";var o=k.find('[role="menu"]'+n+', [role="listbox"]'+n);if(!o.length){return}var i=o.index(m.target);if(m.which==38&&i>0){i--}if(m.which==40&&i<o.length-1){i++}if(!~i){i=0}o.eq(i).trigger("focus")};function d(i){if(i&&i.which===3){return}h(e).remove();h(b).each(function(){var l=h(this);var k=f(l);var j={relatedTarget:this};if(!k.hasClass("open")){return}k.trigger(i=h.Event("hide.bs.dropdown",j));if(i.isDefaultPrevented()){return}l.attr("aria-expanded","false");k.removeClass("open").trigger("hidden.bs.dropdown",j)})}function f(k){var i=k.attr("data-target");if(!i){i=k.attr("href");i=i&&/#[A-Za-z]/.test(i)&&i.replace(/.*(?=#[^\s]*$)/,"")}var j=i&&h(i);return j&&j.length?j:k.parent()}function g(i){return this.each(function(){var k=h(this);var j=k.data("bs.dropdown");if(!j){k.data("bs.dropdown",(j=new a(this)))}if(typeof i=="string"){j[i].call(k)}})}var c=h.fn.dropdown;h.fn.dropdown=g;h.fn.dropdown.Constructor=a;h.fn.dropdown.noConflict=function(){h.fn.dropdown=c;return this};h(document).on("click.bs.dropdown.data-api",d).on("click.bs.dropdown.data-api",".dropdown form",function(i){i.stopPropagation()}).on("click.bs.dropdown.data-api",b,a.prototype.toggle).on("keydown.bs.dropdown.data-api",b,a.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="menu"]',a.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="listbox"]',a.prototype.keydown)}(jQuery);+function(d){var b=function(f,e){this.options=e;this.$body=d(document.body);this.$element=d(f);this.$backdrop=this.isShown=null;this.scrollbarWidth=0;if(this.options.remote){this.$element.find(".modal-content").load(this.options.remote,d.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))}};b.VERSION="3.3.2";b.TRANSITION_DURATION=300;b.BACKDROP_TRANSITION_DURATION=150;b.DEFAULTS={backdrop:true,keyboard:true,show:true};b.prototype.toggle=function(e){return this.isShown?this.hide():this.show(e)};b.prototype.show=function(h){var f=this;var g=d.Event("show.bs.modal",{relatedTarget:h});this.$element.trigger(g);if(this.isShown||g.isDefaultPrevented()){return}this.isShown=true;this.checkScrollbar();this.setScrollbar();this.$body.addClass("modal-open");this.escape();this.resize();this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',d.proxy(this.hide,this));this.backdrop(function(){var j=d.support.transition&&f.$element.hasClass("fade");if(!f.$element.parent().length){f.$element.appendTo(f.$body)}f.$element.show().scrollTop(0);if(f.options.backdrop){f.adjustBackdrop()}f.adjustDialog();if(j){f.$element[0].offsetWidth}f.$element.addClass("in").attr("aria-hidden",false);f.enforceFocus();var i=d.Event("shown.bs.modal",{relatedTarget:h});j?f.$element.find(".modal-dialog").one("bsTransitionEnd",function(){f.$element.trigger("focus").trigger(i)}).emulateTransitionEnd(b.TRANSITION_DURATION):f.$element.trigger("focus").trigger(i)})};b.prototype.hide=function(f){if(f){f.preventDefault()}f=d.Event("hide.bs.modal");this.$element.trigger(f);if(!this.isShown||f.isDefaultPrevented()){return}this.isShown=false;this.escape();this.resize();d(document).off("focusin.bs.modal");this.$element.removeClass("in").attr("aria-hidden",true).off("click.dismiss.bs.modal");d.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",d.proxy(this.hideModal,this)).emulateTransitionEnd(b.TRANSITION_DURATION):this.hideModal()};b.prototype.enforceFocus=function(){d(document).off("focusin.bs.modal").on("focusin.bs.modal",d.proxy(function(f){if(this.$element[0]!==f.target&&!this.$element.has(f.target).length){this.$element.trigger("focus")}},this))};b.prototype.escape=function(){if(this.isShown&&this.options.keyboard){this.$element.on("keydown.dismiss.bs.modal",d.proxy(function(f){f.which==27&&this.hide()},this))}else{if(!this.isShown){this.$element.off("keydown.dismiss.bs.modal")}}};b.prototype.resize=function(){if(this.isShown){d(window).on("resize.bs.modal",d.proxy(this.handleUpdate,this))}else{d(window).off("resize.bs.modal")}};b.prototype.hideModal=function(){var e=this;this.$element.hide();this.backdrop(function(){e.$body.removeClass("modal-open");e.resetAdjustments();e.resetScrollbar();e.$element.trigger("hidden.bs.modal")})};b.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove();this.$backdrop=null};b.prototype.backdrop=function(i){var h=this;var f=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var e=d.support.transition&&f;this.$backdrop=d('<div class="modal-backdrop '+f+'" />').prependTo(this.$element).on("click.dismiss.bs.modal",d.proxy(function(j){if(j.target!==j.currentTarget){return}this.options.backdrop=="static"?this.$element[0].focus.call(this.$element[0]):this.hide.call(this)},this));if(e){this.$backdrop[0].offsetWidth}this.$backdrop.addClass("in");if(!i){return}e?this.$backdrop.one("bsTransitionEnd",i).emulateTransitionEnd(b.BACKDROP_TRANSITION_DURATION):i()}else{if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){h.removeBackdrop();i&&i()};d.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(b.BACKDROP_TRANSITION_DURATION):g()}else{if(i){i()}}}};b.prototype.handleUpdate=function(){if(this.options.backdrop){this.adjustBackdrop()}this.adjustDialog()};b.prototype.adjustBackdrop=function(){this.$backdrop.css("height",0).css("height",this.$element[0].scrollHeight)};b.prototype.adjustDialog=function(){var e=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&e?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!e?this.scrollbarWidth:""})};b.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})};b.prototype.checkScrollbar=function(){this.bodyIsOverflowing=document.body.scrollHeight>document.documentElement.clientHeight;this.scrollbarWidth=this.measureScrollbar()};b.prototype.setScrollbar=function(){var e=parseInt((this.$body.css("padding-right")||0),10);if(this.bodyIsOverflowing){this.$body.css("padding-right",e+this.scrollbarWidth)}};b.prototype.resetScrollbar=function(){this.$body.css("padding-right","")};b.prototype.measureScrollbar=function(){var f=document.createElement("div");f.className="modal-scrollbar-measure";this.$body.append(f);var e=f.offsetWidth-f.clientWidth;this.$body[0].removeChild(f);return e};function c(e,f){return this.each(function(){var i=d(this);var h=i.data("bs.modal");var g=d.extend({},b.DEFAULTS,i.data(),typeof e=="object"&&e);if(!h){i.data("bs.modal",(h=new b(this,g)))}if(typeof e=="string"){h[e](f)}else{if(g.show){h.show(f)}}})}var a=d.fn.modal;d.fn.modal=c;d.fn.modal.Constructor=b;d.fn.modal.noConflict=function(){d.fn.modal=a;return this};d(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(j){var i=d(this);var g=i.attr("href");var f=d(i.attr("data-target")||(g&&g.replace(/.*(?=#[^\s]+$)/,"")));var h=f.data("bs.modal")?"toggle":d.extend({remote:!/#/.test(g)&&g},f.data(),i.data());if(i.is("a")){j.preventDefault()}f.one("show.bs.modal",function(e){if(e.isDefaultPrevented()){return}f.one("hidden.bs.modal",function(){i.is(":visible")&&i.trigger("focus")})});c.call(f,h,this)})}(jQuery);+function(d){var c=function(f,e){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null;this.init("tooltip",f,e)};c.VERSION="3.3.2";c.TRANSITION_DURATION=150;c.DEFAULTS={animation:true,placement:"top",selector:false,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:false,container:false,viewport:{selector:"body",padding:0}};c.prototype.init=function(l,j,g){this.enabled=true;this.type=l;this.$element=d(j);this.options=this.getOptions(g);this.$viewport=this.options.viewport&&d(this.options.viewport.selector||this.options.viewport);var k=this.options.trigger.split(" ");for(var h=k.length;h--;){var f=k[h];if(f=="click"){this.$element.on("click."+this.type,this.options.selector,d.proxy(this.toggle,this))}else{if(f!="manual"){var m=f=="hover"?"mouseenter":"focusin";var e=f=="hover"?"mouseleave":"focusout";this.$element.on(m+"."+this.type,this.options.selector,d.proxy(this.enter,this));this.$element.on(e+"."+this.type,this.options.selector,d.proxy(this.leave,this))}}}this.options.selector?(this._options=d.extend({},this.options,{trigger:"manual",selector:""})):this.fixTitle()};c.prototype.getDefaults=function(){return c.DEFAULTS};c.prototype.getOptions=function(e){e=d.extend({},this.getDefaults(),this.$element.data(),e);if(e.delay&&typeof e.delay=="number"){e.delay={show:e.delay,hide:e.delay}}return e};c.prototype.getDelegateOptions=function(){var e={};var f=this.getDefaults();this._options&&d.each(this._options,function(g,h){if(f[g]!=h){e[g]=h}});return e};c.prototype.enter=function(f){var e=f instanceof this.constructor?f:d(f.currentTarget).data("bs."+this.type);if(e&&e.$tip&&e.$tip.is(":visible")){e.hoverState="in";return}if(!e){e=new this.constructor(f.currentTarget,this.getDelegateOptions());d(f.currentTarget).data("bs."+this.type,e)}clearTimeout(e.timeout);e.hoverState="in";if(!e.options.delay||!e.options.delay.show){return e.show()}e.timeout=setTimeout(function(){if(e.hoverState=="in"){e.show()}},e.options.delay.show)};c.prototype.leave=function(f){var e=f instanceof this.constructor?f:d(f.currentTarget).data("bs."+this.type);if(!e){e=new this.constructor(f.currentTarget,this.getDelegateOptions());d(f.currentTarget).data("bs."+this.type,e)}clearTimeout(e.timeout);e.hoverState="out";if(!e.options.delay||!e.options.delay.hide){return e.hide()}e.timeout=setTimeout(function(){if(e.hoverState=="out"){e.hide()}},e.options.delay.hide)};c.prototype.show=function(){var p=d.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(p);var q=d.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(p.isDefaultPrevented()||!q){return}var o=this;var m=this.tip();var i=this.getUID(this.type);this.setContent();m.attr("id",i);this.$element.attr("aria-describedby",i);if(this.options.animation){m.addClass("fade")}var l=typeof this.options.placement=="function"?this.options.placement.call(this,m[0],this.$element[0]):this.options.placement;var t=/\s?auto?\s?/i;var u=t.test(l);if(u){l=l.replace(t,"")||"top"}m.detach().css({top:0,left:0,display:"block"}).addClass(l).data("bs."+this.type,this);this.options.container?m.appendTo(this.options.container):m.insertAfter(this.$element);var r=this.getPosition();var f=m[0].offsetWidth;var n=m[0].offsetHeight;if(u){var k=l;var s=this.options.container?d(this.options.container):this.$element.parent();var h=this.getPosition(s);l=l=="bottom"&&r.bottom+n>h.bottom?"top":l=="top"&&r.top-n<h.top?"bottom":l=="right"&&r.right+f>h.width?"left":l=="left"&&r.left-f<h.left?"right":l;m.removeClass(k).addClass(l)}var j=this.getCalculatedOffset(l,r,f,n);this.applyPlacement(j,l);var g=function(){var e=o.hoverState;o.$element.trigger("shown.bs."+o.type);o.hoverState=null;if(e=="out"){o.leave(o)}};d.support.transition&&this.$tip.hasClass("fade")?m.one("bsTransitionEnd",g).emulateTransitionEnd(c.TRANSITION_DURATION):g()}};c.prototype.applyPlacement=function(j,k){var l=this.tip();var g=l[0].offsetWidth;var q=l[0].offsetHeight;var f=parseInt(l.css("margin-top"),10);var i=parseInt(l.css("margin-left"),10);if(isNaN(f)){f=0}if(isNaN(i)){i=0}j.top=j.top+f;j.left=j.left+i;d.offset.setOffset(l[0],d.extend({using:function(r){l.css({top:Math.round(r.top),left:Math.round(r.left)})}},j),0);l.addClass("in");var e=l[0].offsetWidth;var m=l[0].offsetHeight;if(k=="top"&&m!=q){j.top=j.top+q-m}var p=this.getViewportAdjustedDelta(k,j,e,m);if(p.left){j.left+=p.left}else{j.top+=p.top}var n=/top|bottom/.test(k);var h=n?p.left*2-g+e:p.top*2-q+m;var o=n?"offsetWidth":"offsetHeight";l.offset(j);this.replaceArrow(h,l[0][o],n)};c.prototype.replaceArrow=function(g,e,f){this.arrow().css(f?"left":"top",50*(1-g/e)+"%").css(f?"top":"left","")};c.prototype.setContent=function(){var f=this.tip();var e=this.getTitle();f.find(".tooltip-inner")[this.options.html?"html":"text"](e);f.removeClass("fade in top bottom left right")};c.prototype.hide=function(j){var g=this;var i=this.tip();var h=d.Event("hide.bs."+this.type);function f(){if(g.hoverState!="in"){i.detach()}g.$element.removeAttr("aria-describedby").trigger("hidden.bs."+g.type);j&&j()}this.$element.trigger(h);if(h.isDefaultPrevented()){return}i.removeClass("in");d.support.transition&&this.$tip.hasClass("fade")?i.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f();this.hoverState=null;return this};c.prototype.fixTitle=function(){var e=this.$element;if(e.attr("title")||typeof(e.attr("data-original-title"))!="string"){e.attr("data-original-title",e.attr("title")||"").attr("title","")}};c.prototype.hasContent=function(){return this.getTitle()};c.prototype.getPosition=function(g){g=g||this.$element;var i=g[0];var f=i.tagName=="BODY";var h=i.getBoundingClientRect();if(h.width==null){h=d.extend({},h,{width:h.right-h.left,height:h.bottom-h.top})}var k=f?{top:0,left:0}:g.offset();var e={scroll:f?document.documentElement.scrollTop||document.body.scrollTop:g.scrollTop()};var j=f?{width:d(window).width(),height:d(window).height()}:null;return d.extend({},h,e,j,k)};c.prototype.getCalculatedOffset=function(e,h,f,g){return e=="bottom"?{top:h.top+h.height,left:h.left+h.width/2-f/2}:e=="top"?{top:h.top-g,left:h.left+h.width/2-f/2}:e=="left"?{top:h.top+h.height/2-g/2,left:h.left-f}:{top:h.top+h.height/2-g/2,left:h.left+h.width}};c.prototype.getViewportAdjustedDelta=function(h,k,e,j){var m={top:0,left:0};if(!this.$viewport){return m}var g=this.options.viewport&&this.options.viewport.padding||0;var l=this.getPosition(this.$viewport);if(/right|left/.test(h)){var n=k.top-g-l.scroll;var i=k.top+g-l.scroll+j;if(n<l.top){m.top=l.top-n}else{if(i>l.top+l.height){m.top=l.top+l.height-i}}}else{var o=k.left-g;var f=k.left+g+e;if(o<l.left){m.left=l.left-o}else{if(f>l.width){m.left=l.left+l.width-f}}}return m};c.prototype.getTitle=function(){var g;var e=this.$element;var f=this.options;g=e.attr("data-original-title")||(typeof f.title=="function"?f.title.call(e[0]):f.title);return g};c.prototype.getUID=function(e){do{e+=~~(Math.random()*1000000)}while(document.getElementById(e));return e};c.prototype.tip=function(){return(this.$tip=this.$tip||d(this.options.template))};c.prototype.arrow=function(){return(this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow"))};c.prototype.enable=function(){this.enabled=true};c.prototype.disable=function(){this.enabled=false};c.prototype.toggleEnabled=function(){this.enabled=!this.enabled};c.prototype.toggle=function(g){var f=this;if(g){f=d(g.currentTarget).data("bs."+this.type);if(!f){f=new this.constructor(g.currentTarget,this.getDelegateOptions());d(g.currentTarget).data("bs."+this.type,f)}}f.tip().hasClass("in")?f.leave(f):f.enter(f)};c.prototype.destroy=function(){var e=this;clearTimeout(this.timeout);this.hide(function(){e.$element.off("."+e.type).removeData("bs."+e.type)})};function b(e){return this.each(function(){var h=d(this);var g=h.data("bs.tooltip");var f=typeof e=="object"&&e;if(!g&&e=="destroy"){return}if(!g){h.data("bs.tooltip",(g=new c(this,f)))}if(typeof e=="string"){g[e]()}})}var a=d.fn.tooltip;d.fn.tooltip=b;d.fn.tooltip.Constructor=c;d.fn.tooltip.noConflict=function(){d.fn.tooltip=a;return this}}(jQuery);+function(d){var c=function(f,e){this.init("popover",f,e)};if(!d.fn.tooltip){throw new Error("Popover requires tooltip.js")}c.VERSION="3.3.2";c.DEFAULTS=d.extend({},d.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'});c.prototype=d.extend({},d.fn.tooltip.Constructor.prototype);c.prototype.constructor=c;c.prototype.getDefaults=function(){return c.DEFAULTS};c.prototype.setContent=function(){var g=this.tip();var f=this.getTitle();var e=this.getContent();g.find(".popover-title")[this.options.html?"html":"text"](f);g.find(".popover-content").children().detach().end()[this.options.html?(typeof e=="string"?"html":"append"):"text"](e);g.removeClass("fade top bottom left right in");if(!g.find(".popover-title").html()){g.find(".popover-title").hide()}};c.prototype.hasContent=function(){return this.getTitle()||this.getContent()};c.prototype.getContent=function(){var e=this.$element;var f=this.options;return e.attr("data-content")||(typeof f.content=="function"?f.content.call(e[0]):f.content)};c.prototype.arrow=function(){return(this.$arrow=this.$arrow||this.tip().find(".arrow"))};c.prototype.tip=function(){if(!this.$tip){this.$tip=d(this.options.template)}return this.$tip};function b(e){return this.each(function(){var h=d(this);var g=h.data("bs.popover");var f=typeof e=="object"&&e;if(!g&&e=="destroy"){return}if(!g){h.data("bs.popover",(g=new c(this,f)))}if(typeof e=="string"){g[e]()}})}var a=d.fn.popover;d.fn.popover=b;d.fn.popover.Constructor=c;d.fn.popover.noConflict=function(){d.fn.popover=a;return this}}(jQuery);+function(d){function c(f,e){var g=d.proxy(this.process,this);this.$body=d("body");this.$scrollElement=d(f).is("body")?d(window):d(f);this.options=d.extend({},c.DEFAULTS,e);this.selector=(this.options.target||"")+" .nav li > a";this.offsets=[];this.targets=[];this.activeTarget=null;this.scrollHeight=0;this.$scrollElement.on("scroll.bs.scrollspy",g);this.refresh();this.process()}c.VERSION="3.3.2";c.DEFAULTS={offset:10};c.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)};c.prototype.refresh=function(){var e="offset";var g=0;if(!d.isWindow(this.$scrollElement[0])){e="position";g=this.$scrollElement.scrollTop()}this.offsets=[];this.targets=[];this.scrollHeight=this.getScrollHeight();var f=this;this.$body.find(this.selector).map(function(){var i=d(this);var h=i.data("target")||i.attr("href");var j=/^#./.test(h)&&d(h);return(j&&j.length&&j.is(":visible")&&[[j[e]().top+g,h]])||null}).sort(function(i,h){return i[0]-h[0]}).each(function(){f.offsets.push(this[0]);f.targets.push(this[1])})};c.prototype.process=function(){var k=this.$scrollElement.scrollTop()+this.options.offset;var g=this.getScrollHeight();var j=this.options.offset+g-this.$scrollElement.height();var h=this.offsets;var e=this.targets;var l=this.activeTarget;var f;if(this.scrollHeight!=g){this.refresh()}if(k>=j){return l!=(f=e[e.length-1])&&this.activate(f)}if(l&&k<h[0]){this.activeTarget=null;return this.clear()}for(f=h.length;f--;){l!=e[f]&&k>=h[f]&&(!h[f+1]||k<=h[f+1])&&this.activate(e[f])}};c.prototype.activate=function(g){this.activeTarget=g;this.clear();var e=this.selector+'[data-target="'+g+'"],'+this.selector+'[href="'+g+'"]';var f=d(e).parents("li").addClass("active");if(f.parent(".dropdown-menu").length){f=f.closest("li.dropdown").addClass("active")}f.trigger("activate.bs.scrollspy")};c.prototype.clear=function(){d(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};function b(e){return this.each(function(){var h=d(this);var g=h.data("bs.scrollspy");var f=typeof e=="object"&&e;if(!g){h.data("bs.scrollspy",(g=new c(this,f)))}if(typeof e=="string"){g[e]()}})}var a=d.fn.scrollspy;d.fn.scrollspy=b;d.fn.scrollspy.Constructor=c;d.fn.scrollspy.noConflict=function(){d.fn.scrollspy=a;return this};d(window).on("load.bs.scrollspy.data-api",function(){d('[data-spy="scroll"]').each(function(){var e=d(this);b.call(e,e.data())})})}(jQuery);+function(d){var b=function(f){this.element=d(f)};b.VERSION="3.3.2";b.TRANSITION_DURATION=150;b.prototype.show=function(){var l=this.element;var h=l.closest("ul:not(.dropdown-menu)");var g=l.data("target");if(!g){g=l.attr("href");g=g&&g.replace(/.*(?=#[^\s]*$)/,"")}if(l.parent("li").hasClass("active")){return}var j=h.find(".active:last a");var k=d.Event("hide.bs.tab",{relatedTarget:l[0]});var i=d.Event("show.bs.tab",{relatedTarget:j[0]});j.trigger(k);l.trigger(i);if(i.isDefaultPrevented()||k.isDefaultPrevented()){return}var f=d(g);this.activate(l.closest("li"),h);this.activate(f,f.parent(),function(){j.trigger({type:"hidden.bs.tab",relatedTarget:l[0]});l.trigger({type:"shown.bs.tab",relatedTarget:j[0]})})};b.prototype.activate=function(h,g,k){var f=g.find("> .active");var j=k&&d.support.transition&&((f.length&&f.hasClass("fade"))||!!g.find("> .fade").length);function i(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",false);h.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",true);if(j){h[0].offsetWidth;h.addClass("in")}else{h.removeClass("fade")}if(h.parent(".dropdown-menu")){h.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",true)}k&&k()}f.length&&j?f.one("bsTransitionEnd",i).emulateTransitionEnd(b.TRANSITION_DURATION):i();f.removeClass("in")};function c(f){return this.each(function(){var h=d(this);var g=h.data("bs.tab");if(!g){h.data("bs.tab",(g=new b(this)))}if(typeof f=="string"){g[f]()}})}var a=d.fn.tab;d.fn.tab=c;d.fn.tab.Constructor=b;d.fn.tab.noConflict=function(){d.fn.tab=a;return this};var e=function(f){f.preventDefault();c.call(d(this),"show")};d(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery);+function(d){var c=function(f,e){this.options=d.extend({},c.DEFAULTS,e);this.$target=d(this.options.target).on("scroll.bs.affix.data-api",d.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",d.proxy(this.checkPositionWithEventLoop,this));this.$element=d(f);this.affixed=this.unpin=this.pinnedOffset=null;this.checkPosition()};c.VERSION="3.3.2";c.RESET="affix affix-top affix-bottom";c.DEFAULTS={offset:0,target:window};c.prototype.getState=function(n,m,f,g){var e=this.$target.scrollTop();var i=this.$element.offset();var j=this.$target.height();if(f!=null&&this.affixed=="top"){return e<f?"top":false}if(this.affixed=="bottom"){if(f!=null){return(e+this.unpin<=i.top)?false:"bottom"}return(e+j<=n-g)?false:"bottom"}var h=this.affixed==null;var l=h?e:i.top;var k=h?j:m;if(f!=null&&e<=f){return"top"}if(g!=null&&(l+k>=n-g)){return"bottom"}return false};c.prototype.getPinnedOffset=function(){if(this.pinnedOffset){return this.pinnedOffset}this.$element.removeClass(c.RESET).addClass("affix");var f=this.$target.scrollTop();var e=this.$element.offset();return(this.pinnedOffset=e.top-f)};c.prototype.checkPositionWithEventLoop=function(){setTimeout(d.proxy(this.checkPosition,this),1)};c.prototype.checkPosition=function(){if(!this.$element.is(":visible")){return}var f=this.$element.height();var l=this.options.offset;var j=l.top;var h=l.bottom;var i=d("body").height();if(typeof l!="object"){h=j=l}if(typeof j=="function"){j=l.top(this.$element)}if(typeof h=="function"){h=l.bottom(this.$element)}var g=this.getState(i,f,j,h);if(this.affixed!=g){if(this.unpin!=null){this.$element.css("top","")}var m="affix"+(g?"-"+g:"");var k=d.Event(m+".bs.affix");this.$element.trigger(k);if(k.isDefaultPrevented()){return}this.affixed=g;this.unpin=g=="bottom"?this.getPinnedOffset():null;this.$element.removeClass(c.RESET).addClass(m).trigger(m.replace("affix","affixed")+".bs.affix")}if(g=="bottom"){this.$element.offset({top:i-f-h})}};function b(e){return this.each(function(){var h=d(this);var g=h.data("bs.affix");var f=typeof e=="object"&&e;if(!g){h.data("bs.affix",(g=new c(this,f)))}if(typeof e=="string"){g[e]()}})}var a=d.fn.affix;d.fn.affix=b;d.fn.affix.Constructor=c;d.fn.affix.noConflict=function(){d.fn.affix=a;return this};d(window).on("load",function(){d('[data-spy="affix"]').each(function(){var f=d(this);var e=f.data();e.offset=e.offset||{};if(e.offsetBottom!=null){e.offset.bottom=e.offsetBottom}if(e.offsetTop!=null){e.offset.top=e.offsetTop}b.call(f,e)})})}(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/bootstrap-3.3.2.min.js
bootstrap-3.3.2.min.js
* @summary TableTools * @description Tools and buttons for DataTables * @version 2.2.0 * @file dataTables.tableTools.js * @author SpryMedia Ltd (www.sprymedia.co.uk) * @contact www.sprymedia.co.uk/contact * @copyright Copyright 2009-2014 SpryMedia Ltd. * * This source file is free software, available under the following license: * MIT license - http://datatables.net/license/mit * * 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 */ /* Global scope for TableTools for backwards compatibility. * Will be removed in 2.3 */ var TableTools; (function (window, document, undefined) { var factory = function ($, DataTable) { "use strict"; //include ZeroClipboard.js /* ZeroClipboard 1.0.4 * Author: Joseph Huckaby */ var ZeroClipboard_TableTools = { version: "1.0.4-TableTools2", clients: {}, // registered upload clients on page, indexed by id moviePath: '', // URL to movie nextId: 1, // ID of next movie $: function (thingy) { // simple DOM lookup utility function if (typeof(thingy) == 'string') { thingy = document.getElementById(thingy); } if (!thingy.addClass) { // extend element with a few useful methods thingy.hide = function () { this.style.display = 'none'; }; thingy.show = function () { this.style.display = ''; }; thingy.addClass = function (name) { this.removeClass(name); this.className += ' ' + name; }; thingy.removeClass = function (name) { this.className = this.className.replace(new RegExp("\\s*" + name + "\\s*"), " ").replace(/^\s+/, '').replace(/\s+$/, ''); }; thingy.hasClass = function (name) { return !!this.className.match(new RegExp("\\s*" + name + "\\s*")); }; } return thingy; }, setMoviePath: function (path) { // set path to ZeroClipboard.swf this.moviePath = path; }, dispatch: function (id, eventName, args) { // receive event from flash movie, send to client var client = this.clients[id]; if (client) { client.receiveEvent(eventName, args); } }, register: function (id, client) { // register new client to receive events this.clients[id] = client; }, getDOMObjectPosition: function (obj) { // get absolute coordinates for dom element var info = { left: 0, top: 0, width: obj.width ? obj.width : obj.offsetWidth, height: obj.height ? obj.height : obj.offsetHeight }; if (obj.style.width !== "") { info.width = obj.style.width.replace("px", ""); } if (obj.style.height !== "") { info.height = obj.style.height.replace("px", ""); } while (obj) { info.left += obj.offsetLeft; info.top += obj.offsetTop; obj = obj.offsetParent; } return info; }, Client: function (elem) { // constructor for new simple upload client this.handlers = {}; // unique ID this.id = ZeroClipboard_TableTools.nextId++; this.movieId = 'ZeroClipboard_TableToolsMovie_' + this.id; // register client with singleton to receive flash events ZeroClipboard_TableTools.register(this.id, this); // create movie if (elem) { this.glue(elem); } } }; ZeroClipboard_TableTools.Client.prototype = { id: 0, // unique ID for us ready: false, // whether movie is ready to receive events or not movie: null, // reference to movie object clipText: '', // text to copy to clipboard fileName: '', // default file save name action: 'copy', // action to perform handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor cssEffects: true, // enable CSS mouse effects on dom container handlers: null, // user event handlers sized: false, glue: function (elem, title) { // glue to DOM element // elem can be ID or actual DOM element object this.domElement = ZeroClipboard_TableTools.$(elem); // float just above object, or zIndex 99 if dom element isn't set var zIndex = 99; if (this.domElement.style.zIndex) { zIndex = parseInt(this.domElement.style.zIndex, 10) + 1; } // find X/Y position of domElement var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); // create floating DIV above element this.div = document.createElement('div'); var style = this.div.style; style.position = 'absolute'; style.left = '0px'; style.top = '0px'; style.width = (box.width) + 'px'; style.height = box.height + 'px'; style.zIndex = zIndex; if (typeof title != "undefined" && title !== "") { this.div.title = title; } if (box.width !== 0 && box.height !== 0) { this.sized = true; } // style.backgroundColor = '#f00'; // debug if (this.domElement) { this.domElement.appendChild(this.div); this.div.innerHTML = this.getHTML(box.width, box.height).replace(/&/g, '&amp;'); } }, positionElement: function () { var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); var style = this.div.style; style.position = 'absolute'; //style.left = (this.domElement.offsetLeft)+'px'; //style.top = this.domElement.offsetTop+'px'; style.width = box.width + 'px'; style.height = box.height + 'px'; if (box.width !== 0 && box.height !== 0) { this.sized = true; } else { return; } var flash = this.div.childNodes[0]; flash.width = box.width; flash.height = box.height; }, getHTML: function (width, height) { // return HTML for movie var html = ''; var flashvars = 'id=' + this.id + '&width=' + width + '&height=' + height; if (navigator.userAgent.match(/MSIE/)) { // IE gets an OBJECT tag var protocol = location.href.match(/^https/i) ? 'https://' : 'http://'; html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="' + protocol + 'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="' + width + '" height="' + height + '" id="' + this.movieId + '" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="' + ZeroClipboard_TableTools.moviePath + '" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="' + flashvars + '"/><param name="wmode" value="transparent"/></object>'; } else { // all other browsers get an EMBED tag html += '<embed id="' + this.movieId + '" src="' + ZeroClipboard_TableTools.moviePath + '" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="' + width + '" height="' + height + '" name="' + this.movieId + '" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="' + flashvars + '" wmode="transparent" />'; } return html; }, hide: function () { // temporarily hide floater offscreen if (this.div) { this.div.style.left = '-2000px'; } }, show: function () { // show ourselves after a call to hide() this.reposition(); }, destroy: function () { // destroy control and floater if (this.domElement && this.div) { this.hide(); this.div.innerHTML = ''; var body = document.getElementsByTagName('body')[0]; try { body.removeChild(this.div); } catch (e) { } this.domElement = null; this.div = null; } }, reposition: function (elem) { // reposition our floating div, optionally to new container // warning: container CANNOT change size, only position if (elem) { this.domElement = ZeroClipboard_TableTools.$(elem); if (!this.domElement) { this.hide(); } } if (this.domElement && this.div) { var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); var style = this.div.style; style.left = '' + box.left + 'px'; style.top = '' + box.top + 'px'; } }, clearText: function () { // clear the text to be copy / saved this.clipText = ''; if (this.ready) { this.movie.clearText(); } }, appendText: function (newText) { // append text to that which is to be copied / saved this.clipText += newText; if (this.ready) { this.movie.appendText(newText); } }, setText: function (newText) { // set text to be copied to be copied / saved this.clipText = newText; if (this.ready) { this.movie.setText(newText); } }, setCharSet: function (charSet) { // set the character set (UTF16LE or UTF8) this.charSet = charSet; if (this.ready) { this.movie.setCharSet(charSet); } }, setBomInc: function (bomInc) { // set if the BOM should be included or not this.incBom = bomInc; if (this.ready) { this.movie.setBomInc(bomInc); } }, setFileName: function (newText) { // set the file name this.fileName = newText; if (this.ready) { this.movie.setFileName(newText); } }, setAction: function (newText) { // set action (save or copy) this.action = newText; if (this.ready) { this.movie.setAction(newText); } }, addEventListener: function (eventName, func) { // add user event listener for event // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel eventName = eventName.toString().toLowerCase().replace(/^on/, ''); if (!this.handlers[eventName]) { this.handlers[eventName] = []; } this.handlers[eventName].push(func); }, setHandCursor: function (enabled) { // enable hand cursor (true), or default arrow cursor (false) this.handCursorEnabled = enabled; if (this.ready) { this.movie.setHandCursor(enabled); } }, setCSSEffects: function (enabled) { // enable or disable CSS effects on DOM container this.cssEffects = !!enabled; }, receiveEvent: function (eventName, args) { var self; // receive event from flash eventName = eventName.toString().toLowerCase().replace(/^on/, ''); // special behavior for certain events switch (eventName) { case 'load': // movie claims it is ready, but in IE this isn't always the case... // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function this.movie = document.getElementById(this.movieId); if (!this.movie) { self = this; setTimeout(function () { self.receiveEvent('load', null); }, 1); return; } // firefox on pc needs a "kick" in order to set these in certain cases if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) { self = this; setTimeout(function () { self.receiveEvent('load', null); }, 100); this.ready = true; return; } this.ready = true; this.movie.clearText(); this.movie.appendText(this.clipText); this.movie.setFileName(this.fileName); this.movie.setAction(this.action); this.movie.setCharSet(this.charSet); this.movie.setBomInc(this.incBom); this.movie.setHandCursor(this.handCursorEnabled); break; case 'mouseover': if (this.domElement && this.cssEffects) { //this.domElement.addClass('hover'); if (this.recoverActive) { this.domElement.addClass('active'); } } break; case 'mouseout': if (this.domElement && this.cssEffects) { this.recoverActive = false; if (this.domElement.hasClass('active')) { this.domElement.removeClass('active'); this.recoverActive = true; } //this.domElement.removeClass('hover'); } break; case 'mousedown': if (this.domElement && this.cssEffects) { this.domElement.addClass('active'); } break; case 'mouseup': if (this.domElement && this.cssEffects) { this.domElement.removeClass('active'); this.recoverActive = false; } break; } // switch eventName if (this.handlers[eventName]) { for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) { var func = this.handlers[eventName][idx]; if (typeof(func) == 'function') { // actual function reference func(this, args); } else if ((typeof(func) == 'object') && (func.length == 2)) { // PHP style object + method, i.e. [myObject, 'myMethod'] func[0][ func[1] ](this, args); } else if (typeof(func) == 'string') { // name of function window[func](this, args); } } // foreach event handler defined } // user defined handler for event } }; // For the Flash binding to work, ZeroClipboard_TableTools must be on the global // object list window.ZeroClipboard_TableTools = ZeroClipboard_TableTools; //include TableTools.js /* TableTools * 2009-2014 SpryMedia Ltd - datatables.net/license */ /*globals ZeroClipboard_TableTools*/ /* Global scope for TableTools */ var TableTools; (function ($, window, document) { /** * TableTools provides flexible buttons and other tools for a DataTables enhanced table * @class TableTools * @constructor * @param {Object} oDT DataTables instance. When using DataTables 1.10 this can * also be a jQuery collection, jQuery selector, table node, DataTables API * instance or DataTables settings object. * @param {Object} oOpts TableTools options * @param {String} oOpts.sSwfPath ZeroClipboard SWF path * @param {String} oOpts.sRowSelect Row selection options - 'none', 'single', 'multi' or 'os' * @param {Function} oOpts.fnPreRowSelect Callback function just prior to row selection * @param {Function} oOpts.fnRowSelected Callback function just after row selection * @param {Function} oOpts.fnRowDeselected Callback function when row is deselected * @param {Array} oOpts.aButtons List of buttons to be used */ TableTools = function (oDT, oOpts) { /* Santiy check that we are a new instance */ if (!this instanceof TableTools) { alert("Warning: TableTools must be initialised with the keyword 'new'"); } // In 1.10 we can use the API to get the settings object from a number of // sources var dtSettings = $.fn.dataTable.Api ? new $.fn.dataTable.Api(oDT).settings()[0] : oDT.fnSettings(); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for TableTools instance */ this.s = { /** * Store 'this' so the instance can be retrieved from the settings object * @property that * @type object * @default this */ "that": this, /** * DataTables settings objects * @property dt * @type object * @default <i>From the oDT init option</i> */ "dt": dtSettings, /** * @namespace Print specific information */ "print": { /** * DataTables draw 'start' point before the printing display was shown * @property saveStart * @type int * @default -1 */ "saveStart": -1, /** * DataTables draw 'length' point before the printing display was shown * @property saveLength * @type int * @default -1 */ "saveLength": -1, /** * Page scrolling point before the printing display was shown so it can be restored * @property saveScroll * @type int * @default -1 */ "saveScroll": -1, /** * Wrapped function to end the print display (to maintain scope) * @property funcEnd * @type Function * @default function () {} */ "funcEnd": function () { } }, /** * A unique ID is assigned to each button in each instance * @property buttonCounter * @type int * @default 0 */ "buttonCounter": 0, /** * @namespace Select rows specific information */ "select": { /** * Select type - can be 'none', 'single' or 'multi' * @property type * @type string * @default "" */ "type": "", /** * Array of nodes which are currently selected * @property selected * @type array * @default [] */ "selected": [], /** * Function to run before the selection can take place. Will cancel the select if the * function returns false * @property preRowSelect * @type Function * @default null */ "preRowSelect": null, /** * Function to run when a row is selected * @property postSelected * @type Function * @default null */ "postSelected": null, /** * Function to run when a row is deselected * @property postDeselected * @type Function * @default null */ "postDeselected": null, /** * Indicate if all rows are selected (needed for server-side processing) * @property all * @type boolean * @default false */ "all": false, /** * Class name to add to selected TR nodes * @property selectedClass * @type String * @default "" */ "selectedClass": "" }, /** * Store of the user input customisation object * @property custom * @type object * @default {} */ "custom": {}, /** * SWF movie path * @property swfPath * @type string * @default "" */ "swfPath": "", /** * Default button set * @property buttonSet * @type array * @default [] */ "buttonSet": [], /** * When there is more than one TableTools instance for a DataTable, there must be a * master which controls events (row selection etc) * @property master * @type boolean * @default false */ "master": false, /** * Tag names that are used for creating collections and buttons * @namesapce */ "tags": {} }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * DIV element that is create and all TableTools buttons (and their children) put into * @property container * @type node * @default null */ "container": null, /** * The table node to which TableTools will be applied * @property table * @type node * @default null */ "table": null, /** * @namespace Nodes used for the print display */ "print": { /** * Nodes which have been removed from the display by setting them to display none * @property hidden * @type array * @default [] */ "hidden": [], /** * The information display saying telling the user about the print display * @property message * @type node * @default null */ "message": null }, /** * @namespace Nodes used for a collection display. This contains the currently used collection */ "collection": { /** * The div wrapper containing the buttons in the collection (i.e. the menu) * @property collection * @type node * @default null */ "collection": null, /** * Background display to provide focus and capture events * @property background * @type node * @default null */ "background": null } }; /** * @namespace Name space for the classes that this TableTools instance will use * @extends TableTools.classes */ this.classes = $.extend(true, {}, TableTools.classes); if (this.s.dt.bJUI) { $.extend(true, this.classes, TableTools.classes_themeroller); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @method fnSettings * @returns {object} TableTools settings object */ this.fnSettings = function () { return this.s; }; /* Constructor logic */ if (typeof oOpts == 'undefined') { oOpts = {}; } this._fnConstruct(oOpts); return this; }; TableTools.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @returns {array} List of TR nodes which are currently selected * @param {boolean} [filtered=false] Get only selected rows which are * available given the filtering applied to the table. By default * this is false - i.e. all rows, regardless of filtering are selected. */ "fnGetSelected": function (filtered) { var out = [], data = this.s.dt.aoData, displayed = this.s.dt.aiDisplay, i, iLen; if (filtered) { // Only consider filtered rows for (i = 0, iLen = displayed.length; i < iLen; i++) { if (data[ displayed[i] ]._DTTT_selected) { out.push(data[ displayed[i] ].nTr); } } } else { // Use all rows for (i = 0, iLen = data.length; i < iLen; i++) { if (data[i]._DTTT_selected) { out.push(data[i].nTr); } } } return out; }, /** * Get the data source objects/arrays from DataTables for the selected rows (same as * fnGetSelected followed by fnGetData on each row from the table) * @returns {array} Data from the TR nodes which are currently selected */ "fnGetSelectedData": function () { var out = []; var data = this.s.dt.aoData; var i, iLen; for (i = 0, iLen = data.length; i < iLen; i++) { if (data[i]._DTTT_selected) { out.push(this.s.dt.oInstance.fnGetData(i)); } } return out; }, /** * Check to see if a current row is selected or not * @param {Node} n TR node to check if it is currently selected or not * @returns {Boolean} true if select, false otherwise */ "fnIsSelected": function (n) { var pos = this.s.dt.oInstance.fnGetPosition(n); return (this.s.dt.aoData[pos]._DTTT_selected === true) ? true : false; }, /** * Select all rows in the table * @param {boolean} [filtered=false] Select only rows which are available * given the filtering applied to the table. By default this is false - * i.e. all rows, regardless of filtering are selected. */ "fnSelectAll": function (filtered) { var s = this._fnGetMasterSettings(); this._fnRowSelect((filtered === true) ? s.dt.aiDisplay : s.dt.aoData ); }, /** * Deselect all rows in the table * @param {boolean} [filtered=false] Deselect only rows which are available * given the filtering applied to the table. By default this is false - * i.e. all rows, regardless of filtering are deselected. */ "fnSelectNone": function (filtered) { var s = this._fnGetMasterSettings(); this._fnRowDeselect(this.fnGetSelected(filtered)); }, /** * Select row(s) * @param {node|object|array} n The row(s) to select. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnSelect": function (n) { if (this.s.select.type == "single") { this.fnSelectNone(); this._fnRowSelect(n); } else if (this.s.select.type == "multi") { this._fnRowSelect(n); } }, /** * Deselect row(s) * @param {node|object|array} n The row(s) to deselect. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnDeselect": function (n) { this._fnRowDeselect(n); }, /** * Get the title of the document - useful for file names. The title is retrieved from either * the configuration object's 'title' parameter, or the HTML document title * @param {Object} oConfig Button configuration object * @returns {String} Button title */ "fnGetTitle": function (oConfig) { var sTitle = ""; if (typeof oConfig.sTitle != 'undefined' && oConfig.sTitle !== "") { sTitle = oConfig.sTitle; } else { var anTitle = document.getElementsByTagName('title'); if (anTitle.length > 0) { sTitle = anTitle[0].innerHTML; } } /* Strip characters which the OS will object to - checking for UTF8 support in the scripting * engine */ if ("\u00A1".toString().length < 4) { return sTitle.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, ""); } else { return sTitle.replace(/[^a-zA-Z0-9_\.,\-_ !\(\)]/g, ""); } }, /** * Calculate a unity array with the column width by proportion for a set of columns to be * included for a button. This is particularly useful for PDF creation, where we can use the * column widths calculated by the browser to size the columns in the PDF. * @param {Object} oConfig Button configuration object * @returns {Array} Unity array of column ratios */ "fnCalcColRatios": function (oConfig) { var aoCols = this.s.dt.aoColumns, aColumnsInc = this._fnColumnTargets(oConfig.mColumns), aColWidths = [], iWidth = 0, iTotal = 0, i, iLen; for (i = 0, iLen = aColumnsInc.length; i < iLen; i++) { if (aColumnsInc[i]) { iWidth = aoCols[i].nTh.offsetWidth; iTotal += iWidth; aColWidths.push(iWidth); } } for (i = 0, iLen = aColWidths.length; i < iLen; i++) { aColWidths[i] = aColWidths[i] / iTotal; } return aColWidths.join('\t'); }, /** * Get the information contained in a table as a string * @param {Object} oConfig Button configuration object * @returns {String} Table data as a string */ "fnGetTableData": function (oConfig) { /* In future this could be used to get data from a plain HTML source as well as DataTables */ if (this.s.dt) { return this._fnGetDataTablesData(oConfig); } }, /** * Pass text to a flash button instance, which will be used on the button's click handler * @param {Object} clip Flash button object * @param {String} text Text to set */ "fnSetText": function (clip, text) { this._fnFlashSetText(clip, text); }, /** * Resize the flash elements of the buttons attached to this TableTools instance - this is * useful for when initialising TableTools when it is hidden (display:none) since sizes can't * be calculated at that time. */ "fnResizeButtons": function () { for (var cli in ZeroClipboard_TableTools.clients) { if (cli) { var client = ZeroClipboard_TableTools.clients[cli]; if (typeof client.domElement != 'undefined' && client.domElement.parentNode) { client.positionElement(); } } } }, /** * Check to see if any of the ZeroClipboard client's attached need to be resized */ "fnResizeRequired": function () { for (var cli in ZeroClipboard_TableTools.clients) { if (cli) { var client = ZeroClipboard_TableTools.clients[cli]; if (typeof client.domElement != 'undefined' && client.domElement.parentNode == this.dom.container && client.sized === false) { return true; } } } return false; }, /** * Programmatically enable or disable the print view * @param {boolean} [bView=true] Show the print view if true or not given. If false, then * terminate the print view and return to normal. * @param {object} [oConfig={}] Configuration for the print view * @param {boolean} [oConfig.bShowAll=false] Show all rows in the table if true * @param {string} [oConfig.sInfo] Information message, displayed as an overlay to the * user to let them know what the print view is. * @param {string} [oConfig.sMessage] HTML string to show at the top of the document - will * be included in the printed document. */ "fnPrint": function (bView, oConfig) { if (oConfig === undefined) { oConfig = {}; } if (bView === undefined || bView) { this._fnPrintStart(oConfig); } else { this._fnPrintEnd(); } }, /** * Show a message to the end user which is nicely styled * @param {string} message The HTML string to show to the user * @param {int} time The duration the message is to be shown on screen for (mS) */ "fnInfo": function (message, time) { var info = $('<div/>') .addClass(this.classes.print.info) .html(message) .appendTo('body'); setTimeout(function () { info.fadeOut("normal", function () { info.remove(); }); }, time); }, /** * Get the container element of the instance for attaching to the DOM * @returns {node} DOM node */ "fnContainer": function () { return this.dom.container; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Constructor logic * @method _fnConstruct * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnConstruct": function (oOpts) { var that = this; this._fnCustomiseSettings(oOpts); /* Container element */ this.dom.container = document.createElement(this.s.tags.container); this.dom.container.className = this.classes.container; /* Row selection config */ if (this.s.select.type != 'none') { this._fnRowSelectConfig(); } /* Buttons */ this._fnButtonDefinations(this.s.buttonSet, this.dom.container); /* Destructor */ this.s.dt.aoDestroyCallback.push({ "sName": "TableTools", "fn": function () { $(that.s.dt.nTBody).off('click.DTTT_Select', 'tr'); $(that.dom.container).empty(); } }); }, /** * Take the user defined settings and the default settings and combine them. * @method _fnCustomiseSettings * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnCustomiseSettings": function (oOpts) { /* Is this the master control instance or not? */ if (typeof this.s.dt._TableToolsInit == 'undefined') { this.s.master = true; this.s.dt._TableToolsInit = true; } /* We can use the table node from comparisons to group controls */ this.dom.table = this.s.dt.nTable; /* Clone the defaults and then the user options */ this.s.custom = $.extend({}, TableTools.DEFAULTS, oOpts); /* Flash file location */ this.s.swfPath = this.s.custom.sSwfPath; if (typeof ZeroClipboard_TableTools != 'undefined') { ZeroClipboard_TableTools.moviePath = this.s.swfPath; } /* Table row selecting */ this.s.select.type = this.s.custom.sRowSelect; this.s.select.preRowSelect = this.s.custom.fnPreRowSelect; this.s.select.postSelected = this.s.custom.fnRowSelected; this.s.select.postDeselected = this.s.custom.fnRowDeselected; // Backwards compatibility - allow the user to specify a custom class in the initialiser if (this.s.custom.sSelectedClass) { this.classes.select.row = this.s.custom.sSelectedClass; } this.s.tags = this.s.custom.oTags; /* Button set */ this.s.buttonSet = this.s.custom.aButtons; }, /** * Take the user input arrays and expand them to be fully defined, and then add them to a given * DOM element * @method _fnButtonDefinations * @param {array} buttonSet Set of user defined buttons * @param {node} wrapper Node to add the created buttons to * @returns void * @private */ "_fnButtonDefinations": function (buttonSet, wrapper) { var buttonDef; for (var i = 0, iLen = buttonSet.length; i < iLen; i++) { if (typeof buttonSet[i] == "string") { if (typeof TableTools.BUTTONS[ buttonSet[i] ] == 'undefined') { alert("TableTools: Warning - unknown button type: " + buttonSet[i]); continue; } buttonDef = $.extend({}, TableTools.BUTTONS[ buttonSet[i] ], true); } else { if (typeof TableTools.BUTTONS[ buttonSet[i].sExtends ] == 'undefined') { alert("TableTools: Warning - unknown button type: " + buttonSet[i].sExtends); continue; } var o = $.extend({}, TableTools.BUTTONS[ buttonSet[i].sExtends ], true); buttonDef = $.extend(o, buttonSet[i], true); } wrapper.appendChild(this._fnCreateButton( buttonDef, $(wrapper).hasClass(this.classes.collection.container) )); } }, /** * Create and configure a TableTools button * @method _fnCreateButton * @param {Object} oConfig Button configuration object * @returns {Node} Button element * @private */ "_fnCreateButton": function (oConfig, bCollectionButton) { var nButton = this._fnButtonBase(oConfig, bCollectionButton); if (oConfig.sAction.match(/flash/)) { this._fnFlashConfig(nButton, oConfig); } else if (oConfig.sAction == "text") { this._fnTextConfig(nButton, oConfig); } else if (oConfig.sAction == "div") { this._fnTextConfig(nButton, oConfig); } else if (oConfig.sAction == "collection") { this._fnTextConfig(nButton, oConfig); this._fnCollectionConfig(nButton, oConfig); } return nButton; }, /** * Create the DOM needed for the button and apply some base properties. All buttons start here * @method _fnButtonBase * @param {o} oConfig Button configuration object * @returns {Node} DIV element for the button * @private */ "_fnButtonBase": function (o, bCollectionButton) { var sTag, sLiner, sClass; if (bCollectionButton) { sTag = o.sTag && o.sTag !== "default" ? o.sTag : this.s.tags.collection.button; sLiner = o.sLinerTag && o.sLinerTag !== "default" ? o.sLiner : this.s.tags.collection.liner; sClass = this.classes.collection.buttons.normal; } else { sTag = o.sTag && o.sTag !== "default" ? o.sTag : this.s.tags.button; sLiner = o.sLinerTag && o.sLinerTag !== "default" ? o.sLiner : this.s.tags.liner; sClass = this.classes.buttons.normal; } var nButton = document.createElement(sTag), nSpan = document.createElement(sLiner), masterS = this._fnGetMasterSettings(); nButton.className = sClass + " " + o.sButtonClass; nButton.setAttribute('id', "ToolTables_" + this.s.dt.sInstance + "_" + masterS.buttonCounter); nButton.appendChild(nSpan); nSpan.innerHTML = o.sButtonText; masterS.buttonCounter++; return nButton; }, /** * Get the settings object for the master instance. When more than one TableTools instance is * assigned to a DataTable, only one of them can be the 'master' (for the select rows). As such, * we will typically want to interact with that master for global properties. * @method _fnGetMasterSettings * @returns {Object} TableTools settings object * @private */ "_fnGetMasterSettings": function () { if (this.s.master) { return this.s; } else { /* Look for the master which has the same DT as this one */ var instances = TableTools._aInstances; for (var i = 0, iLen = instances.length; i < iLen; i++) { if (this.dom.table == instances[i].s.dt.nTable) { return instances[i].s; } } } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Button collection functions */ /** * Create a collection button, when activated will present a drop down list of other buttons * @param {Node} nButton Button to use for the collection activation * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionConfig": function (nButton, oConfig) { var nHidden = document.createElement(this.s.tags.collection.container); nHidden.style.display = "none"; nHidden.className = this.classes.collection.container; oConfig._collection = nHidden; document.body.appendChild(nHidden); this._fnButtonDefinations(oConfig.aButtons, nHidden); }, /** * Show a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionShow": function (nButton, oConfig) { var that = this, oPos = $(nButton).offset(), nHidden = oConfig._collection, iDivX = oPos.left, iDivY = oPos.top + $(nButton).outerHeight(), iWinHeight = $(window).height(), iDocHeight = $(document).height(), iWinWidth = $(window).width(), iDocWidth = $(document).width(); nHidden.style.position = "absolute"; nHidden.style.left = iDivX + "px"; nHidden.style.top = iDivY + "px"; nHidden.style.display = "block"; $(nHidden).css('opacity', 0); var nBackground = document.createElement('div'); nBackground.style.position = "absolute"; nBackground.style.left = "0px"; nBackground.style.top = "0px"; nBackground.style.height = ((iWinHeight > iDocHeight) ? iWinHeight : iDocHeight) + "px"; nBackground.style.width = ((iWinWidth > iDocWidth) ? iWinWidth : iDocWidth) + "px"; nBackground.className = this.classes.collection.background; $(nBackground).css('opacity', 0); document.body.appendChild(nBackground); document.body.appendChild(nHidden); /* Visual corrections to try and keep the collection visible */ var iDivWidth = $(nHidden).outerWidth(); var iDivHeight = $(nHidden).outerHeight(); if (iDivX + iDivWidth > iDocWidth) { nHidden.style.left = (iDocWidth - iDivWidth) + "px"; } if (iDivY + iDivHeight > iDocHeight) { nHidden.style.top = (iDivY - iDivHeight - $(nButton).outerHeight()) + "px"; } this.dom.collection.collection = nHidden; this.dom.collection.background = nBackground; /* This results in a very small delay for the end user but it allows the animation to be * much smoother. If you don't want the animation, then the setTimeout can be removed */ setTimeout(function () { $(nHidden).animate({"opacity": 1}, 500); $(nBackground).animate({"opacity": 0.25}, 500); }, 10); /* Resize the buttons to the Flash contents fit */ this.fnResizeButtons(); /* Event handler to remove the collection display */ $(nBackground).click(function () { that._fnCollectionHide.call(that, null, null); }); }, /** * Hide a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionHide": function (nButton, oConfig) { if (oConfig !== null && oConfig.sExtends == 'collection') { return; } if (this.dom.collection.collection !== null) { $(this.dom.collection.collection).animate({"opacity": 0}, 500, function (e) { this.style.display = "none"; }); $(this.dom.collection.background).animate({"opacity": 0}, 500, function (e) { this.parentNode.removeChild(this); }); this.dom.collection.collection = null; this.dom.collection.background = null; } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Row selection functions */ /** * Add event handlers to a table to allow for row selection * @method _fnRowSelectConfig * @returns void * @private */ "_fnRowSelectConfig": function () { if (this.s.master) { var that = this, i, iLen, dt = this.s.dt, aoOpenRows = this.s.dt.aoOpenRows; $(dt.nTable).addClass(this.classes.select.table); // When using OS style selection, we want to cancel the shift text // selection, but only when the shift key is used (so you can // actually still select text in the table) if (this.s.select.type === 'os') { $(dt.nTBody).on('mousedown.DTTT_Select', 'tr', function (e) { if (e.shiftKey) { $(dt.nTBody) .css('-moz-user-select', 'none') .one('selectstart.DTTT_Select', 'tr', function () { return false; }); } }); $(dt.nTBody).on('mouseup.DTTT_Select', 'tr', function (e) { $(dt.nTBody).css('-moz-user-select', ''); }); } // Row selection $(dt.nTBody).on('click.DTTT_Select', 'tr', function (e) { var select = that.s.select; var pos = that.s.dt.oInstance.fnGetPosition(this); /* Sub-table must be ignored (odd that the selector won't do this with >) */ if (this.parentNode != dt.nTBody) { return; } /* Check that we are actually working with a DataTables controlled row */ if (dt.oInstance.fnGetData(this) === null) { return; } // Shift click, ctrl click and simple click handling to make // row selection a lot like a file system in desktop OSs if (select.type == 'os') { if (e.ctrlKey || e.metaKey) { // Add or remove from the selection if (that.fnIsSelected(this)) { that._fnRowDeselect(this, e); } else { that._fnRowSelect(this, e); } } else if (e.shiftKey) { // Add a range of rows, from the last selected row to // this one var rowIdxs = that.s.dt.aiDisplay.slice(); // visible rows var idx1 = $.inArray(select.lastRow, rowIdxs); var idx2 = $.inArray(pos, rowIdxs); if (that.fnGetSelected().length === 0 || idx1 === -1) { // select from top to here - slightly odd, but both // Windows and Mac OS do this rowIdxs.splice($.inArray(pos, rowIdxs) + 1, rowIdxs.length); } else { // reverse so we can shift click 'up' as well as down if (idx1 > idx2) { var tmp = idx2; idx2 = idx1; idx1 = tmp; } rowIdxs.splice(idx2 + 1, rowIdxs.length); rowIdxs.splice(0, idx1); } if (!that.fnIsSelected(this)) { // Select range that._fnRowSelect(rowIdxs, e); } else { // Deselect range - need to keep the clicked on row selected rowIdxs.splice($.inArray(pos, rowIdxs), 1); that._fnRowDeselect(rowIdxs, e); } } else { // No cmd or shift click. Deselect current if selected, // or select this row only if (that.fnIsSelected(this) && that.fnGetSelected().length === 1) { that._fnRowDeselect(this, e); } else { that.fnSelectNone(); that._fnRowSelect(this, e); } } } else if (that.fnIsSelected(this)) { that._fnRowDeselect(this, e); } else if (select.type == "single") { that.fnSelectNone(); that._fnRowSelect(this, e); } else if (select.type == "multi") { that._fnRowSelect(this, e); } select.lastRow = pos; });//.on('selectstart', function () { return false; } ); // Bind a listener to the DataTable for when new rows are created. // This allows rows to be visually selected when they should be and // deferred rendering is used. dt.oApi._fnCallbackReg(dt, 'aoRowCreatedCallback', function (tr, data, index) { if (dt.aoData[index]._DTTT_selected) { $(tr).addClass(that.classes.select.row); } }, 'TableTools-SelectAll'); } }, /** * Select rows * @param {*} src Rows to select - see _fnSelectData for a description of valid inputs * @private */ "_fnRowSelect": function (src, e) { var that = this, data = this._fnSelectData(src), firstTr = data.length === 0 ? null : data[0].nTr, anSelected = [], i, len; // Get all the rows that will be selected for (i = 0, len = data.length; i < len; i++) { if (data[i].nTr) { anSelected.push(data[i].nTr); } } // User defined pre-selection function if (this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anSelected, true)) { return; } // Mark them as selected for (i = 0, len = data.length; i < len; i++) { data[i]._DTTT_selected = true; if (data[i].nTr) { $(data[i].nTr).addClass(that.classes.select.row); } } // Post-selection function if (this.s.select.postSelected !== null) { this.s.select.postSelected.call(this, anSelected); } TableTools._fnEventDispatch(this, 'select', anSelected, true); }, /** * Deselect rows * @param {*} src Rows to deselect - see _fnSelectData for a description of valid inputs * @private */ "_fnRowDeselect": function (src, e) { var that = this, data = this._fnSelectData(src), firstTr = data.length === 0 ? null : data[0].nTr, anDeselectedTrs = [], i, len; // Get all the rows that will be deselected for (i = 0, len = data.length; i < len; i++) { if (data[i].nTr) { anDeselectedTrs.push(data[i].nTr); } } // User defined pre-selection function if (this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anDeselectedTrs, false)) { return; } // Mark them as deselected for (i = 0, len = data.length; i < len; i++) { data[i]._DTTT_selected = false; if (data[i].nTr) { $(data[i].nTr).removeClass(that.classes.select.row); } } // Post-deselection function if (this.s.select.postDeselected !== null) { this.s.select.postDeselected.call(this, anDeselectedTrs); } TableTools._fnEventDispatch(this, 'select', anDeselectedTrs, false); }, /** * Take a data source for row selection and convert it into aoData points for the DT * @param {*} src Can be a single DOM TR node, an array of TR nodes (including a * a jQuery object), a single aoData point from DataTables, an array of aoData * points or an array of aoData indexes * @returns {array} An array of aoData points */ "_fnSelectData": function (src) { var out = [], pos, i, iLen; if (src.nodeName) { // Single node pos = this.s.dt.oInstance.fnGetPosition(src); out.push(this.s.dt.aoData[pos]); } else if (typeof src.length !== 'undefined') { // jQuery object or an array of nodes, or aoData points for (i = 0, iLen = src.length; i < iLen; i++) { if (src[i].nodeName) { pos = this.s.dt.oInstance.fnGetPosition(src[i]); out.push(this.s.dt.aoData[pos]); } else if (typeof src[i] === 'number') { out.push(this.s.dt.aoData[ src[i] ]); } else { out.push(src[i]); } } return out; } else { // A single aoData point out.push(src); } return out; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Text button functions */ /** * Configure a text based button for interaction events * @method _fnTextConfig * @param {Node} nButton Button element which is being considered * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnTextConfig": function (nButton, oConfig) { var that = this; if (oConfig.fnInit !== null) { oConfig.fnInit.call(this, nButton, oConfig); } if (oConfig.sToolTip !== "") { nButton.title = oConfig.sToolTip; } $(nButton).hover(function () { if (oConfig.fnMouseover !== null) { oConfig.fnMouseover.call(this, nButton, oConfig, null); } }, function () { if (oConfig.fnMouseout !== null) { oConfig.fnMouseout.call(this, nButton, oConfig, null); } }); if (oConfig.fnSelect !== null) { TableTools._fnEventListen(this, 'select', function (n) { oConfig.fnSelect.call(that, nButton, oConfig, n); }); } $(nButton).click(function (e) { //e.preventDefault(); if (oConfig.fnClick !== null) { oConfig.fnClick.call(that, nButton, oConfig, null, e); } /* Provide a complete function to match the behaviour of the flash elements */ if (oConfig.fnComplete !== null) { oConfig.fnComplete.call(that, nButton, oConfig, null, null); } that._fnCollectionHide(nButton, oConfig); }); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Flash button functions */ /** * Configure a flash based button for interaction events * @method _fnFlashConfig * @param {Node} nButton Button element which is being considered * @param {o} oConfig Button configuration object * @returns void * @private */ "_fnFlashConfig": function (nButton, oConfig) { var that = this; var flash = new ZeroClipboard_TableTools.Client(); if (oConfig.fnInit !== null) { oConfig.fnInit.call(this, nButton, oConfig); } flash.setHandCursor(true); if (oConfig.sAction == "flash_save") { flash.setAction('save'); flash.setCharSet((oConfig.sCharSet == "utf16le") ? 'UTF16LE' : 'UTF8'); flash.setBomInc(oConfig.bBomInc); flash.setFileName(oConfig.sFileName.replace('*', this.fnGetTitle(oConfig))); } else if (oConfig.sAction == "flash_pdf") { flash.setAction('pdf'); flash.setFileName(oConfig.sFileName.replace('*', this.fnGetTitle(oConfig))); } else { flash.setAction('copy'); } flash.addEventListener('mouseOver', function (client) { if (oConfig.fnMouseover !== null) { oConfig.fnMouseover.call(that, nButton, oConfig, flash); } }); flash.addEventListener('mouseOut', function (client) { if (oConfig.fnMouseout !== null) { oConfig.fnMouseout.call(that, nButton, oConfig, flash); } }); flash.addEventListener('mouseDown', function (client) { if (oConfig.fnClick !== null) { oConfig.fnClick.call(that, nButton, oConfig, flash); } }); flash.addEventListener('complete', function (client, text) { if (oConfig.fnComplete !== null) { oConfig.fnComplete.call(that, nButton, oConfig, flash, text); } that._fnCollectionHide(nButton, oConfig); }); this._fnFlashGlue(flash, nButton, oConfig.sToolTip); }, /** * Wait until the id is in the DOM before we "glue" the swf. Note that this function will call * itself (using setTimeout) until it completes successfully * @method _fnFlashGlue * @param {Object} clip Zero clipboard object * @param {Node} node node to glue swf to * @param {String} text title of the flash movie * @returns void * @private */ "_fnFlashGlue": function (flash, node, text) { var that = this; var id = node.getAttribute('id'); if (document.getElementById(id)) { flash.glue(node, text); } else { setTimeout(function () { that._fnFlashGlue(flash, node, text); }, 100); } }, /** * Set the text for the flash clip to deal with * * This function is required for large information sets. There is a limit on the * amount of data that can be transferred between Javascript and Flash in a single call, so * we use this method to build up the text in Flash by sending over chunks. It is estimated * that the data limit is around 64k, although it is undocumented, and appears to be different * between different flash versions. We chunk at 8KiB. * @method _fnFlashSetText * @param {Object} clip the ZeroClipboard object * @param {String} sData the data to be set * @returns void * @private */ "_fnFlashSetText": function (clip, sData) { var asData = this._fnChunkData(sData, 8192); clip.clearText(); for (var i = 0, iLen = asData.length; i < iLen; i++) { clip.appendText(asData[i]); } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Data retrieval functions */ /** * Convert the mixed columns variable into a boolean array the same size as the columns, which * indicates which columns we want to include * @method _fnColumnTargets * @param {String|Array} mColumns The columns to be included in data retrieval. If a string * then it can take the value of "visible" or "hidden" (to include all visible or * hidden columns respectively). Or an array of column indexes * @returns {Array} A boolean array the length of the columns of the table, which each value * indicating if the column is to be included or not * @private */ "_fnColumnTargets": function (mColumns) { var aColumns = []; var dt = this.s.dt; var i, iLen; if (typeof mColumns == "object") { for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) { aColumns.push(false); } for (i = 0, iLen = mColumns.length; i < iLen; i++) { aColumns[ mColumns[i] ] = true; } } else if (mColumns == "visible") { for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) { aColumns.push(dt.aoColumns[i].bVisible ? true : false); } } else if (mColumns == "hidden") { for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) { aColumns.push(dt.aoColumns[i].bVisible ? false : true); } } else if (mColumns == "sortable") { for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) { aColumns.push(dt.aoColumns[i].bSortable ? true : false); } } else /* all */ { for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) { aColumns.push(true); } } return aColumns; }, /** * New line character(s) depend on the platforms * @method method * @param {Object} oConfig Button configuration object - only interested in oConfig.sNewLine * @returns {String} Newline character */ "_fnNewline": function (oConfig) { if (oConfig.sNewLine == "auto") { return navigator.userAgent.match(/Windows/) ? "\r\n" : "\n"; } else { return oConfig.sNewLine; } }, /** * Get data from DataTables' internals and format it for output * @method _fnGetDataTablesData * @param {Object} oConfig Button configuration object * @param {String} oConfig.sFieldBoundary Field boundary for the data cells in the string * @param {String} oConfig.sFieldSeperator Field separator for the data cells * @param {String} oConfig.sNewline New line options * @param {Mixed} oConfig.mColumns Which columns should be included in the output * @param {Boolean} oConfig.bHeader Include the header * @param {Boolean} oConfig.bFooter Include the footer * @param {Boolean} oConfig.bSelectedOnly Include only the selected rows in the output * @returns {String} Concatenated string of data * @private */ "_fnGetDataTablesData": function (oConfig) { var i, iLen, j, jLen; var aRow, aData = [], sLoopData = '', arr; var dt = this.s.dt, tr, child; var regex = new RegExp(oConfig.sFieldBoundary, "g"); /* Do it here for speed */ var aColumnsInc = this._fnColumnTargets(oConfig.mColumns); var bSelectedOnly = (typeof oConfig.bSelectedOnly != 'undefined') ? oConfig.bSelectedOnly : false; /* * Header */ if (oConfig.bHeader) { aRow = []; for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) { if (aColumnsInc[i]) { sLoopData = dt.aoColumns[i].sTitle.replace(/\n/g, " ").replace(/<.*?>/g, "").replace(/^\s+|\s+$/g, ""); sLoopData = this._fnHtmlDecode(sLoopData); aRow.push(this._fnBoundData(sLoopData, oConfig.sFieldBoundary, regex)); } } aData.push(aRow.join(oConfig.sFieldSeperator)); } /* * Body */ var aSelected = this.fnGetSelected(); bSelectedOnly = this.s.select.type !== "none" && bSelectedOnly && aSelected.length !== 0; var aDataIndex = dt.oInstance .$('tr', oConfig.oSelectorOpts) .map(function (id, row) { // If "selected only", then ensure that the row is in the selected list return bSelectedOnly && $.inArray(row, aSelected) === -1 ? null : dt.oInstance.fnGetPosition(row); }) .get(); for (j = 0, jLen = aDataIndex.length; j < jLen; j++) { tr = dt.aoData[ aDataIndex[j] ].nTr; aRow = []; /* Columns */ for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) { if (aColumnsInc[i]) { /* Convert to strings (with small optimisation) */ var mTypeData = dt.oApi._fnGetCellData(dt, aDataIndex[j], i, 'display'); if (oConfig.fnCellRender) { sLoopData = oConfig.fnCellRender(mTypeData, i, tr, aDataIndex[j]) + ""; } else if (typeof mTypeData == "string") { /* Strip newlines, replace img tags with alt attr. and finally strip html... */ sLoopData = mTypeData.replace(/\n/g, " "); sLoopData = sLoopData.replace(/<img.*?\s+alt\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+)).*?>/gi, '$1$2$3'); sLoopData = sLoopData.replace(/<.*?>/g, ""); } else { sLoopData = mTypeData + ""; } /* Trim and clean the data */ sLoopData = sLoopData.replace(/^\s+/, '').replace(/\s+$/, ''); sLoopData = this._fnHtmlDecode(sLoopData); /* Bound it and add it to the total data */ aRow.push(this._fnBoundData(sLoopData, oConfig.sFieldBoundary, regex)); } } aData.push(aRow.join(oConfig.sFieldSeperator)); /* Details rows from fnOpen */ if (oConfig.bOpenRows) { arr = $.grep(dt.aoOpenRows, function (o) { return o.nParent === tr; }); if (arr.length === 1) { sLoopData = this._fnBoundData($('td', arr[0].nTr).html(), oConfig.sFieldBoundary, regex); aData.push(sLoopData); } } } /* * Footer */ if (oConfig.bFooter && dt.nTFoot !== null) { aRow = []; for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) { if (aColumnsInc[i] && dt.aoColumns[i].nTf !== null) { sLoopData = dt.aoColumns[i].nTf.innerHTML.replace(/\n/g, " ").replace(/<.*?>/g, ""); sLoopData = this._fnHtmlDecode(sLoopData); aRow.push(this._fnBoundData(sLoopData, oConfig.sFieldBoundary, regex)); } } aData.push(aRow.join(oConfig.sFieldSeperator)); } var _sLastData = aData.join(this._fnNewline(oConfig)); return _sLastData; }, /** * Wrap data up with a boundary string * @method _fnBoundData * @param {String} sData data to bound * @param {String} sBoundary bounding char(s) * @param {RegExp} regex search for the bounding chars - constructed outside for efficiency * in the loop * @returns {String} bound data * @private */ "_fnBoundData": function (sData, sBoundary, regex) { if (sBoundary === "") { return sData; } else { return sBoundary + sData.replace(regex, sBoundary + sBoundary) + sBoundary; } }, /** * Break a string up into an array of smaller strings * @method _fnChunkData * @param {String} sData data to be broken up * @param {Int} iSize chunk size * @returns {Array} String array of broken up text * @private */ "_fnChunkData": function (sData, iSize) { var asReturn = []; var iStrlen = sData.length; for (var i = 0; i < iStrlen; i += iSize) { if (i + iSize < iStrlen) { asReturn.push(sData.substring(i, i + iSize)); } else { asReturn.push(sData.substring(i, iStrlen)); } } return asReturn; }, /** * Decode HTML entities * @method _fnHtmlDecode * @param {String} sData encoded string * @returns {String} decoded string * @private */ "_fnHtmlDecode": function (sData) { if (sData.indexOf('&') === -1) { return sData; } var n = document.createElement('div'); return sData.replace(/&([^\s]*);/g, function (match, match2) { if (match.substr(1, 1) === '#') { return String.fromCharCode(Number(match2.substr(1))); } else { n.innerHTML = match; return n.childNodes[0].nodeValue; } }); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Printing functions */ /** * Show print display * @method _fnPrintStart * @param {Event} e Event object * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnPrintStart": function (oConfig) { var that = this; var oSetDT = this.s.dt; /* Parse through the DOM hiding everything that isn't needed for the table */ this._fnPrintHideNodes(oSetDT.nTable); /* Show the whole table */ this.s.print.saveStart = oSetDT._iDisplayStart; this.s.print.saveLength = oSetDT._iDisplayLength; if (oConfig.bShowAll) { oSetDT._iDisplayStart = 0; oSetDT._iDisplayLength = -1; if (oSetDT.oApi._fnCalculateEnd) { oSetDT.oApi._fnCalculateEnd(oSetDT); } oSetDT.oApi._fnDraw(oSetDT); } /* Adjust the display for scrolling which might be done by DataTables */ if (oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "") { this._fnPrintScrollStart(oSetDT); // If the table redraws while in print view, the DataTables scrolling // setup would hide the header, so we need to readd it on draw $(this.s.dt.nTable).bind('draw.DTTT_Print', function () { that._fnPrintScrollStart(oSetDT); }); } /* Remove the other DataTables feature nodes - but leave the table! and info div */ var anFeature = oSetDT.aanFeatures; for (var cFeature in anFeature) { if (cFeature != 'i' && cFeature != 't' && cFeature.length == 1) { for (var i = 0, iLen = anFeature[cFeature].length; i < iLen; i++) { this.dom.print.hidden.push({ "node": anFeature[cFeature][i], "display": "block" }); anFeature[cFeature][i].style.display = "none"; } } } /* Print class can be used for styling */ $(document.body).addClass(this.classes.print.body); /* Show information message to let the user know what is happening */ if (oConfig.sInfo !== "") { this.fnInfo(oConfig.sInfo, 3000); } /* Add a message at the top of the page */ if (oConfig.sMessage) { $('<div/>') .addClass(this.classes.print.message) .html(oConfig.sMessage) .prepend('body'); } /* Cache the scrolling and the jump to the top of the page */ this.s.print.saveScroll = $(window).scrollTop(); window.scrollTo(0, 0); /* Bind a key event listener to the document for the escape key - * it is removed in the callback */ $(document).bind("keydown.DTTT", function (e) { /* Only interested in the escape key */ if (e.keyCode == 27) { e.preventDefault(); that._fnPrintEnd.call(that, e); } }); }, /** * Printing is finished, resume normal display * @method _fnPrintEnd * @param {Event} e Event object * @returns void * @private */ "_fnPrintEnd": function (e) { var that = this; var oSetDT = this.s.dt; var oSetPrint = this.s.print; var oDomPrint = this.dom.print; /* Show all hidden nodes */ this._fnPrintShowNodes(); /* Restore DataTables' scrolling */ if (oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "") { $(this.s.dt.nTable).unbind('draw.DTTT_Print'); this._fnPrintScrollEnd(); } /* Restore the scroll */ window.scrollTo(0, oSetPrint.saveScroll); /* Drop the print message */ if (oDomPrint.message !== null) { document.body.removeChild(oDomPrint.message); oDomPrint.message = null; } /* Styling class */ $(document.body).removeClass('DTTT_Print'); /* Restore the table length */ oSetDT._iDisplayStart = oSetPrint.saveStart; oSetDT._iDisplayLength = oSetPrint.saveLength; if (oSetDT.oApi._fnCalculateEnd) { oSetDT.oApi._fnCalculateEnd(oSetDT); } oSetDT.oApi._fnDraw(oSetDT); $(document).unbind("keydown.DTTT"); }, /** * Take account of scrolling in DataTables by showing the full table * @returns void * @private */ "_fnPrintScrollStart": function () { var oSetDT = this.s.dt, nScrollHeadInner = oSetDT.nScrollHead.getElementsByTagName('div')[0], nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0], nScrollBody = oSetDT.nTable.parentNode, nTheadSize, nTfootSize; /* Copy the header in the thead in the body table, this way we show one single table when * in print view. Note that this section of code is more or less verbatim from DT 1.7.0 */ nTheadSize = oSetDT.nTable.getElementsByTagName('thead'); if (nTheadSize.length > 0) { oSetDT.nTable.removeChild(nTheadSize[0]); } if (oSetDT.nTFoot !== null) { nTfootSize = oSetDT.nTable.getElementsByTagName('tfoot'); if (nTfootSize.length > 0) { oSetDT.nTable.removeChild(nTfootSize[0]); } } nTheadSize = oSetDT.nTHead.cloneNode(true); oSetDT.nTable.insertBefore(nTheadSize, oSetDT.nTable.childNodes[0]); if (oSetDT.nTFoot !== null) { nTfootSize = oSetDT.nTFoot.cloneNode(true); oSetDT.nTable.insertBefore(nTfootSize, oSetDT.nTable.childNodes[1]); } /* Now adjust the table's viewport so we can actually see it */ if (oSetDT.oScroll.sX !== "") { oSetDT.nTable.style.width = $(oSetDT.nTable).outerWidth() + "px"; nScrollBody.style.width = $(oSetDT.nTable).outerWidth() + "px"; nScrollBody.style.overflow = "visible"; } if (oSetDT.oScroll.sY !== "") { nScrollBody.style.height = $(oSetDT.nTable).outerHeight() + "px"; nScrollBody.style.overflow = "visible"; } }, /** * Take account of scrolling in DataTables by showing the full table. Note that the redraw of * the DataTable that we do will actually deal with the majority of the hard work here * @returns void * @private */ "_fnPrintScrollEnd": function () { var oSetDT = this.s.dt, nScrollBody = oSetDT.nTable.parentNode; if (oSetDT.oScroll.sX !== "") { nScrollBody.style.width = oSetDT.oApi._fnStringToCss(oSetDT.oScroll.sX); nScrollBody.style.overflow = "auto"; } if (oSetDT.oScroll.sY !== "") { nScrollBody.style.height = oSetDT.oApi._fnStringToCss(oSetDT.oScroll.sY); nScrollBody.style.overflow = "auto"; } }, /** * Resume the display of all TableTools hidden nodes * @method _fnPrintShowNodes * @returns void * @private */ "_fnPrintShowNodes": function () { var anHidden = this.dom.print.hidden; for (var i = 0, iLen = anHidden.length; i < iLen; i++) { anHidden[i].node.style.display = anHidden[i].display; } anHidden.splice(0, anHidden.length); }, /** * Hide nodes which are not needed in order to display the table. Note that this function is * recursive * @method _fnPrintHideNodes * @param {Node} nNode Element which should be showing in a 'print' display * @returns void * @private */ "_fnPrintHideNodes": function (nNode) { var anHidden = this.dom.print.hidden; var nParent = nNode.parentNode; var nChildren = nParent.childNodes; for (var i = 0, iLen = nChildren.length; i < iLen; i++) { if (nChildren[i] != nNode && nChildren[i].nodeType == 1) { /* If our node is shown (don't want to show nodes which were previously hidden) */ var sDisplay = $(nChildren[i]).css("display"); if (sDisplay != "none") { /* Cache the node and it's previous state so we can restore it */ anHidden.push({ "node": nChildren[i], "display": sDisplay }); nChildren[i].style.display = "none"; } } } if (nParent.nodeName.toUpperCase() != "BODY") { this._fnPrintHideNodes(nParent); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Store of all instances that have been created of TableTools, so one can look up other (when * there is need of a master) * @property _aInstances * @type Array * @default [] * @private */ TableTools._aInstances = []; /** * Store of all listeners and their callback functions * @property _aListeners * @type Array * @default [] */ TableTools._aListeners = []; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Get an array of all the master instances * @method fnGetMasters * @returns {Array} List of master TableTools instances * @static */ TableTools.fnGetMasters = function () { var a = []; for (var i = 0, iLen = TableTools._aInstances.length; i < iLen; i++) { if (TableTools._aInstances[i].s.master) { a.push(TableTools._aInstances[i]); } } return a; }; /** * Get the master instance for a table node (or id if a string is given) * @method fnGetInstance * @returns {Object} ID of table OR table node, for which we want the TableTools instance * @static */ TableTools.fnGetInstance = function (node) { if (typeof node != 'object') { node = document.getElementById(node); } for (var i = 0, iLen = TableTools._aInstances.length; i < iLen; i++) { if (TableTools._aInstances[i].s.master && TableTools._aInstances[i].dom.table == node) { return TableTools._aInstances[i]; } } return null; }; /** * Add a listener for a specific event * @method _fnEventListen * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Function} fn Function * @returns void * @private * @static */ TableTools._fnEventListen = function (that, type, fn) { TableTools._aListeners.push({ "that": that, "type": type, "fn": fn }); }; /** * An event has occurred - look up every listener and fire it off. We check that the event we are * going to fire is attached to the same table (using the table node as reference) before firing * @method _fnEventDispatch * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Node} node Element that the event occurred on (may be null) * @param {boolean} [selected] Indicate if the node was selected (true) or deselected (false) * @returns void * @private * @static */ TableTools._fnEventDispatch = function (that, type, node, selected) { var listeners = TableTools._aListeners; for (var i = 0, iLen = listeners.length; i < iLen; i++) { if (that.dom.table == listeners[i].that.dom.table && listeners[i].type == type) { listeners[i].fn(node, selected); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ TableTools.buttonBase = { // Button base "sAction": "text", "sTag": "default", "sLinerTag": "default", "sButtonClass": "DTTT_button_text", "sButtonText": "Button text", "sTitle": "", "sToolTip": "", // Common button specific options "sCharSet": "utf8", "bBomInc": false, "sFileName": "*.csv", "sFieldBoundary": "", "sFieldSeperator": "\t", "sNewLine": "auto", "mColumns": "all", /* "all", "visible", "hidden" or array of column integers */ "bHeader": true, "bFooter": true, "bOpenRows": false, "bSelectedOnly": false, "oSelectorOpts": undefined, // See http://datatables.net/docs/DataTables/1.9.4/#$ for full options // Callbacks "fnMouseover": null, "fnMouseout": null, "fnClick": null, "fnSelect": null, "fnComplete": null, "fnInit": null, "fnCellRender": null }; /** * @namespace Default button configurations */ TableTools.BUTTONS = { "csv": $.extend({}, TableTools.buttonBase, { "sAction": "flash_save", "sButtonClass": "DTTT_button_csv", "sButtonText": "CSV", "sFieldBoundary": '"', "sFieldSeperator": ",", "fnClick": function (nButton, oConfig, flash) { this.fnSetText(flash, this.fnGetTableData(oConfig)); } }), "xls": $.extend({}, TableTools.buttonBase, { "sAction": "flash_save", "sCharSet": "utf16le", "bBomInc": true, "sButtonClass": "DTTT_button_xls", "sButtonText": "Excel", "fnClick": function (nButton, oConfig, flash) { this.fnSetText(flash, this.fnGetTableData(oConfig)); } }), "copy": $.extend({}, TableTools.buttonBase, { "sAction": "flash_copy", "sButtonClass": "DTTT_button_copy", "sButtonText": "Copy", "fnClick": function (nButton, oConfig, flash) { this.fnSetText(flash, this.fnGetTableData(oConfig)); }, "fnComplete": function (nButton, oConfig, flash, text) { var lines = text.split('\n').length, len = this.s.dt.nTFoot === null ? lines - 1 : lines - 2, plural = (len == 1) ? "" : "s"; this.fnInfo('<h6>Table copied</h6>' + '<p>Copied ' + len + ' row' + plural + ' to the clipboard.</p>', 1500 ); } }), "pdf": $.extend({}, TableTools.buttonBase, { "sAction": "flash_pdf", "sNewLine": "\n", "sFileName": "*.pdf", "sButtonClass": "DTTT_button_pdf", "sButtonText": "PDF", "sPdfOrientation": "portrait", "sPdfSize": "A4", "sPdfMessage": "", "fnClick": function (nButton, oConfig, flash) { this.fnSetText(flash, "title:" + this.fnGetTitle(oConfig) + "\n" + "message:" + oConfig.sPdfMessage + "\n" + "colWidth:" + this.fnCalcColRatios(oConfig) + "\n" + "orientation:" + oConfig.sPdfOrientation + "\n" + "size:" + oConfig.sPdfSize + "\n" + "--/TableToolsOpts--\n" + this.fnGetTableData(oConfig) ); } }), "print": $.extend({}, TableTools.buttonBase, { "sInfo": "<h6>Print view</h6><p>Please use your browser's print function to " + "print this table. Press escape when finished.</p>", "sMessage": null, "bShowAll": true, "sToolTip": "View print view", "sButtonClass": "DTTT_button_print", "sButtonText": "Print", "fnClick": function (nButton, oConfig) { this.fnPrint(true, oConfig); } }), "text": $.extend({}, TableTools.buttonBase), "select": $.extend({}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function (nButton, oConfig) { if (this.fnGetSelected().length !== 0) { $(nButton).removeClass(this.classes.buttons.disabled); } else { $(nButton).addClass(this.classes.buttons.disabled); } }, "fnInit": function (nButton, oConfig) { $(nButton).addClass(this.classes.buttons.disabled); } }), "select_single": $.extend({}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function (nButton, oConfig) { var iSelected = this.fnGetSelected().length; if (iSelected == 1) { $(nButton).removeClass(this.classes.buttons.disabled); } else { $(nButton).addClass(this.classes.buttons.disabled); } }, "fnInit": function (nButton, oConfig) { $(nButton).addClass(this.classes.buttons.disabled); } }), "select_all": $.extend({}, TableTools.buttonBase, { "sButtonText": "Select all", "fnClick": function (nButton, oConfig) { this.fnSelectAll(); }, "fnSelect": function (nButton, oConfig) { if (this.fnGetSelected().length == this.s.dt.fnRecordsDisplay()) { $(nButton).addClass(this.classes.buttons.disabled); } else { $(nButton).removeClass(this.classes.buttons.disabled); } } }), "select_none": $.extend({}, TableTools.buttonBase, { "sButtonText": "Deselect all", "fnClick": function (nButton, oConfig) { this.fnSelectNone(); }, "fnSelect": function (nButton, oConfig) { if (this.fnGetSelected().length !== 0) { $(nButton).removeClass(this.classes.buttons.disabled); } else { $(nButton).addClass(this.classes.buttons.disabled); } }, "fnInit": function (nButton, oConfig) { $(nButton).addClass(this.classes.buttons.disabled); } }), "ajax": $.extend({}, TableTools.buttonBase, { "sAjaxUrl": "/xhr.php", "sButtonText": "Ajax button", "fnClick": function (nButton, oConfig) { var sData = this.fnGetTableData(oConfig); $.ajax({ "url": oConfig.sAjaxUrl, "data": [ { "name": "tableData", "value": sData } ], "success": oConfig.fnAjaxComplete, "dataType": "json", "type": "POST", "cache": false, "error": function () { alert("Error detected when sending table data to server"); } }); }, "fnAjaxComplete": function (json) { alert('Ajax complete'); } }), "div": $.extend({}, TableTools.buttonBase, { "sAction": "div", "sTag": "div", "sButtonClass": "DTTT_nonbutton", "sButtonText": "Text button" }), "collection": $.extend({}, TableTools.buttonBase, { "sAction": "collection", "sButtonClass": "DTTT_button_collection", "sButtonText": "Collection", "fnClick": function (nButton, oConfig) { this._fnCollectionShow(nButton, oConfig); } }) }; /* * on* callback parameters: * 1. node - button element * 2. object - configuration object for this button * 3. object - ZeroClipboard reference (flash button only) * 4. string - Returned string from Flash (flash button only - and only on 'complete') */ // Alias to match the other plug-ins styling TableTools.buttons = TableTools.BUTTONS; /** * @namespace Classes used by TableTools - allows the styles to be override easily. * Note that when TableTools initialises it will take a copy of the classes object * and will use its internal copy for the remainder of its run time. */ TableTools.classes = { "container": "DTTT_container", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" }, "collection": { "container": "DTTT_collection", "background": "DTTT_collection_background", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" } }, "select": { "table": "DTTT_selectable", "row": "DTTT_selected selected" }, "print": { "body": "DTTT_Print", "info": "DTTT_print_info", "message": "DTTT_PrintMessage" } }; /** * @namespace ThemeRoller classes - built in for compatibility with DataTables' * bJQueryUI option. */ TableTools.classes_themeroller = { "container": "DTTT_container ui-buttonset ui-buttonset-multi", "buttons": { "normal": "DTTT_button ui-button ui-state-default" }, "collection": { "container": "DTTT_collection ui-buttonset ui-buttonset-multi" } }; /** * @namespace TableTools default settings for initialisation */ TableTools.DEFAULTS = { "sSwfPath": "../swf/copy_csv_xls_pdf.swf", "sRowSelect": "none", "sSelectedClass": null, "fnPreRowSelect": null, "fnRowSelected": null, "fnRowDeselected": null, "aButtons": [ "copy", "csv", "xls", "pdf", "print" ], "oTags": { "container": "div", "button": "a", // We really want to use buttons here, but Firefox and IE ignore the // click on the Flash element in the button (but not mouse[in|out]). "liner": "span", "collection": { "container": "div", "button": "a", "liner": "span" } } }; // Alias to match the other plug-ins TableTools.defaults = TableTools.DEFAULTS; /** * Name of this class * @constant CLASS * @type String * @default TableTools */ TableTools.prototype.CLASS = "TableTools"; /** * TableTools version * @constant VERSION * @type String * @default See code */ TableTools.version = "2.2.0-dev"; // DataTables 1.10 API // // This will be extended in a big way in in TableTools 3 to provide API methods // such as rows().select() and rows.selected() etc, but for the moment the // tabletools() method simply returns the instance. if ($.fn.dataTable.Api) { $.fn.dataTable.Api.register('tabletools()', function () { var tt = null; if (this.context.length > 0) { tt = TableTools.fnGetInstance(this.context[0].nTable); } return tt; }); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Register a new feature with DataTables */ if (typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.9.0')) { $.fn.dataTableExt.aoFeatures.push({ "fnInit": function (oDTSettings) { var init = oDTSettings.oInit; var opts = init.tableTools || init.oTableTools || {}; var oTT = new TableTools(oDTSettings.oInstance, opts); TableTools._aInstances.push(oTT); return oTT.dom.container; }, "cFeature": "T", "sFeature": "TableTools" }); } else { alert("Warning: TableTools requires DataTables 1.9.0 or newer - www.datatables.net/download"); } $.fn.DataTable.TableTools = TableTools; })(jQuery, window, document); /* * Register a new feature with DataTables */ if (typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.9.0')) { $.fn.dataTableExt.aoFeatures.push({ "fnInit": function (oDTSettings) { var oOpts = typeof oDTSettings.oInit.oTableTools != 'undefined' ? oDTSettings.oInit.oTableTools : {}; var oTT = new TableTools(oDTSettings.oInstance, oOpts); TableTools._aInstances.push(oTT); return oTT.dom.container; }, "cFeature": "T", "sFeature": "TableTools" }); } else { alert("Warning: TableTools 2 requires DataTables 1.9.0 or newer - www.datatables.net/download"); } $.fn.dataTable.TableTools = TableTools; $.fn.DataTable.TableTools = TableTools; return TableTools; }; // /factory factory(jQuery, jQuery.fn.dataTable); })(window, document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-tableTools.js
jquery-dataTables-tableTools.js
(function($) { /* * Math functions will be used extensively, so it's convenient to make a few * shortcuts */ var abs = Math.abs, max = Math.max, min = Math.min, round = Math.round; /** * Create a new HTML div element * * @return A jQuery object representing the new element */ function div() { return $('<div/>'); } /** * imgAreaSelect initialization * * @param img * A HTML image element to attach the plugin to * @param options * An options object */ $.imgAreaSelect = function (img, options) { var /* jQuery object representing the image */ $img = $(img), /* Has the image finished loading? */ imgLoaded, /* Plugin elements */ /* Container box */ $box = div(), /* Selection area */ $area = div(), /* Border (four divs) */ $border = div().add(div()).add(div()).add(div()), /* Outer area (four divs) */ $outer = div().add(div()).add(div()).add(div()), /* Handles (empty by default, initialized in setOptions()) */ $handles = $([]), /* * Additional element to work around a cursor problem in Opera * (explained later) */ $areaOpera, /* Image position (relative to viewport) */ left, top, /* Image offset (as returned by .offset()) */ imgOfs = { left: 0, top: 0 }, /* Image dimensions (as returned by .width() and .height()) */ imgWidth, imgHeight, /* * jQuery object representing the parent element that the plugin * elements are appended to */ $parent, /* Parent element offset (as returned by .offset()) */ parOfs = { left: 0, top: 0 }, /* Base z-index for plugin elements */ zIndex = 0, /* Plugin elements position */ position = 'absolute', /* X/Y coordinates of the starting point for move/resize operations */ startX, startY, /* Horizontal and vertical scaling factors */ scaleX, scaleY, /* Current resize mode ("nw", "se", etc.) */ resize, /* Selection area constraints */ minWidth, minHeight, maxWidth, maxHeight, /* Aspect ratio to maintain (floating point number) */ aspectRatio, /* Are the plugin elements currently displayed? */ shown, /* Current selection (relative to parent element) */ x1, y1, x2, y2, /* Current selection (relative to scaled image) */ selection = { x1: 0, y1: 0, x2: 0, y2: 0, width: 0, height: 0 }, /* Document element */ docElem = document.documentElement, /* User agent */ ua = navigator.userAgent, /* Various helper variables used throughout the code */ $p, d, i, o, w, h, adjusted; /* * Translate selection coordinates (relative to scaled image) to viewport * coordinates (relative to parent element) */ /** * Translate selection X to viewport X * * @param x * Selection X * @return Viewport X */ function viewX(x) { return x + imgOfs.left - parOfs.left; } /** * Translate selection Y to viewport Y * * @param y * Selection Y * @return Viewport Y */ function viewY(y) { return y + imgOfs.top - parOfs.top; } /* * Translate viewport coordinates to selection coordinates */ /** * Translate viewport X to selection X * * @param x * Viewport X * @return Selection X */ function selX(x) { return x - imgOfs.left + parOfs.left; } /** * Translate viewport Y to selection Y * * @param y * Viewport Y * @return Selection Y */ function selY(y) { return y - imgOfs.top + parOfs.top; } /* * Translate event coordinates (relative to document) to viewport * coordinates */ /** * Get event X and translate it to viewport X * * @param event * The event object * @return Viewport X */ function evX(event) { return event.pageX - parOfs.left; } /** * Get event Y and translate it to viewport Y * * @param event * The event object * @return Viewport Y */ function evY(event) { return event.pageY - parOfs.top; } /** * Get the current selection * * @param noScale * If set to <code>true</code>, scaling is not applied to the * returned selection * @return Selection object */ function getSelection(noScale) { var sx = noScale || scaleX, sy = noScale || scaleY; return { x1: round(selection.x1 * sx), y1: round(selection.y1 * sy), x2: round(selection.x2 * sx), y2: round(selection.y2 * sy), width: round(selection.x2 * sx) - round(selection.x1 * sx), height: round(selection.y2 * sy) - round(selection.y1 * sy) }; } /** * Set the current selection * * @param x1 * X coordinate of the upper left corner of the selection area * @param y1 * Y coordinate of the upper left corner of the selection area * @param x2 * X coordinate of the lower right corner of the selection area * @param y2 * Y coordinate of the lower right corner of the selection area * @param noScale * If set to <code>true</code>, scaling is not applied to the * new selection */ function setSelection(x1, y1, x2, y2, noScale) { var sx = noScale || scaleX, sy = noScale || scaleY; selection = { x1: round(x1 / sx || 0), y1: round(y1 / sy || 0), x2: round(x2 / sx || 0), y2: round(y2 / sy || 0) }; selection.width = selection.x2 - selection.x1; selection.height = selection.y2 - selection.y1; } /** * Recalculate image and parent offsets */ function adjust() { /* * Do not adjust if image has not yet loaded or if width is not a * positive number. The latter might happen when imgAreaSelect is put * on a parent element which is then hidden. */ if (!imgLoaded || !$img.width()) return; /* * Get image offset. The .offset() method returns float values, so they * need to be rounded. */ imgOfs = { left: round($img.offset().left), top: round($img.offset().top) }; /* Get image dimensions */ imgWidth = $img.innerWidth(); imgHeight = $img.innerHeight(); imgOfs.top += ($img.outerHeight() - imgHeight) >> 1; imgOfs.left += ($img.outerWidth() - imgWidth) >> 1; /* Set minimum and maximum selection area dimensions */ minWidth = round(options.minWidth / scaleX) || 0; minHeight = round(options.minHeight / scaleY) || 0; maxWidth = round(min(options.maxWidth / scaleX || 1<<24, imgWidth)); maxHeight = round(min(options.maxHeight / scaleY || 1<<24, imgHeight)); /* * Workaround for jQuery 1.3.2 incorrect offset calculation, originally * observed in Safari 3. Firefox 2 is also affected. */ if ($().jquery == '1.3.2' && position == 'fixed' && !docElem['getBoundingClientRect']) { imgOfs.top += max(document.body.scrollTop, docElem.scrollTop); imgOfs.left += max(document.body.scrollLeft, docElem.scrollLeft); } /* Determine parent element offset */ parOfs = /absolute|relative/.test($parent.css('position')) ? { left: round($parent.offset().left) - $parent.scrollLeft(), top: round($parent.offset().top) - $parent.scrollTop() } : position == 'fixed' ? { left: $(document).scrollLeft(), top: $(document).scrollTop() } : { left: 0, top: 0 }; left = viewX(0); top = viewY(0); /* * Check if selection area is within image boundaries, adjust if * necessary */ if (selection.x2 > imgWidth || selection.y2 > imgHeight) doResize(); } /** * Update plugin elements * * @param resetKeyPress * If set to <code>false</code>, this instance's keypress * event handler is not activated */ function update(resetKeyPress) { /* If plugin elements are hidden, do nothing */ if (!shown) return; /* * Set the position and size of the container box and the selection area * inside it */ $box.css({ left: viewX(selection.x1), top: viewY(selection.y1) }) .add($area).width(w = selection.width).height(h = selection.height); /* * Reset the position of selection area, borders, and handles (IE6/IE7 * position them incorrectly if we don't do this) */ $area.add($border).add($handles).css({ left: 0, top: 0 }); /* Set border dimensions */ $border .width(max(w - $border.outerWidth() + $border.innerWidth(), 0)) .height(max(h - $border.outerHeight() + $border.innerHeight(), 0)); /* Arrange the outer area elements */ $($outer[0]).css({ left: left, top: top, width: selection.x1, height: imgHeight }); $($outer[1]).css({ left: left + selection.x1, top: top, width: w, height: selection.y1 }); $($outer[2]).css({ left: left + selection.x2, top: top, width: imgWidth - selection.x2, height: imgHeight }); $($outer[3]).css({ left: left + selection.x1, top: top + selection.y2, width: w, height: imgHeight - selection.y2 }); w -= $handles.outerWidth(); h -= $handles.outerHeight(); /* Arrange handles */ switch ($handles.length) { case 8: $($handles[4]).css({ left: w >> 1 }); $($handles[5]).css({ left: w, top: h >> 1 }); $($handles[6]).css({ left: w >> 1, top: h }); $($handles[7]).css({ top: h >> 1 }); case 4: $handles.slice(1,3).css({ left: w }); $handles.slice(2,4).css({ top: h }); } if (resetKeyPress !== false) { /* * Need to reset the document keypress event handler -- unbind the * current handler */ if ($.imgAreaSelect.onKeyPress != docKeyPress) $(document).unbind($.imgAreaSelect.keyPress, $.imgAreaSelect.onKeyPress); if (options.keys) /* * Set the document keypress event handler to this instance's * docKeyPress() function */ $(document)[$.imgAreaSelect.keyPress]( $.imgAreaSelect.onKeyPress = docKeyPress); } /* * Internet Explorer displays 1px-wide dashed borders incorrectly by * filling the spaces between dashes with white. Toggling the margin * property between 0 and "auto" fixes this in IE6 and IE7 (IE8 is still * broken). This workaround is not perfect, as it requires setTimeout() * and thus causes the border to flicker a bit, but I haven't found a * better solution. * * Note: This only happens with CSS borders, set with the borderWidth, * borderOpacity, borderColor1, and borderColor2 options (which are now * deprecated). Borders created with GIF background images are fine. */ if (msie && $border.outerWidth() - $border.innerWidth() == 2) { $border.css('margin', 0); setTimeout(function () { $border.css('margin', 'auto'); }, 0); } } /** * Do the complete update sequence: recalculate offsets, update the * elements, and set the correct values of x1, y1, x2, and y2. * * @param resetKeyPress * If set to <code>false</code>, this instance's keypress * event handler is not activated */ function doUpdate(resetKeyPress) { adjust(); update(resetKeyPress); x1 = viewX(selection.x1); y1 = viewY(selection.y1); x2 = viewX(selection.x2); y2 = viewY(selection.y2); } /** * Hide or fade out an element (or multiple elements) * * @param $elem * A jQuery object containing the element(s) to hide/fade out * @param fn * Callback function to be called when fadeOut() completes */ function hide($elem, fn) { options.fadeSpeed ? $elem.fadeOut(options.fadeSpeed, fn) : $elem.hide(); } /** * Selection area mousemove event handler * * @param event * The event object */ function areaMouseMove(event) { var x = selX(evX(event)) - selection.x1, y = selY(evY(event)) - selection.y1; if (!adjusted) { adjust(); adjusted = true; $box.one('mouseout', function () { adjusted = false; }); } /* Clear the resize mode */ resize = ''; if (options.resizable) { /* * Check if the mouse pointer is over the resize margin area and set * the resize mode accordingly */ if (y <= options.resizeMargin) resize = 'n'; else if (y >= selection.height - options.resizeMargin) resize = 's'; if (x <= options.resizeMargin) resize += 'w'; else if (x >= selection.width - options.resizeMargin) resize += 'e'; } $box.css('cursor', resize ? resize + '-resize' : options.movable ? 'move' : ''); if ($areaOpera) $areaOpera.toggle(); } /** * Document mouseup event handler * * @param event * The event object */ function docMouseUp(event) { /* Set back the default cursor */ $('body').css('cursor', ''); /* * If autoHide is enabled, or if the selection has zero width/height, * hide the selection and the outer area */ if (options.autoHide || selection.width * selection.height == 0) hide($box.add($outer), function () { $(this).hide(); }); $(document).unbind('mousemove', selectingMouseMove); $box.mousemove(areaMouseMove); options.onSelectEnd(img, getSelection()); } /** * Selection area mousedown event handler * * @param event * The event object * @return false */ function areaMouseDown(event) { if (event.which != 1) return false; adjust(); if (resize) { /* Resize mode is in effect */ $('body').css('cursor', resize + '-resize'); x1 = viewX(selection[/w/.test(resize) ? 'x2' : 'x1']); y1 = viewY(selection[/n/.test(resize) ? 'y2' : 'y1']); $(document).mousemove(selectingMouseMove) .one('mouseup', docMouseUp); $box.unbind('mousemove', areaMouseMove); } else if (options.movable) { startX = left + selection.x1 - evX(event); startY = top + selection.y1 - evY(event); $box.unbind('mousemove', areaMouseMove); $(document).mousemove(movingMouseMove) .one('mouseup', function () { options.onSelectEnd(img, getSelection()); $(document).unbind('mousemove', movingMouseMove); $box.mousemove(areaMouseMove); }); } else $img.mousedown(event); return false; } /** * Adjust the x2/y2 coordinates to maintain aspect ratio (if defined) * * @param xFirst * If set to <code>true</code>, calculate x2 first. Otherwise, * calculate y2 first. */ function fixAspectRatio(xFirst) { if (aspectRatio) if (xFirst) { x2 = max(left, min(left + imgWidth, x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1))); y2 = round(max(top, min(top + imgHeight, y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1)))); x2 = round(x2); } else { y2 = max(top, min(top + imgHeight, y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1))); x2 = round(max(left, min(left + imgWidth, x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1)))); y2 = round(y2); } } /** * Resize the selection area respecting the minimum/maximum dimensions and * aspect ratio */ function doResize() { /* * Make sure the top left corner of the selection area stays within * image boundaries (it might not if the image source was dynamically * changed). */ x1 = min(x1, left + imgWidth); y1 = min(y1, top + imgHeight); if (abs(x2 - x1) < minWidth) { /* Selection width is smaller than minWidth */ x2 = x1 - minWidth * (x2 < x1 || -1); if (x2 < left) x1 = left + minWidth; else if (x2 > left + imgWidth) x1 = left + imgWidth - minWidth; } if (abs(y2 - y1) < minHeight) { /* Selection height is smaller than minHeight */ y2 = y1 - minHeight * (y2 < y1 || -1); if (y2 < top) y1 = top + minHeight; else if (y2 > top + imgHeight) y1 = top + imgHeight - minHeight; } x2 = max(left, min(x2, left + imgWidth)); y2 = max(top, min(y2, top + imgHeight)); fixAspectRatio(abs(x2 - x1) < abs(y2 - y1) * aspectRatio); if (abs(x2 - x1) > maxWidth) { /* Selection width is greater than maxWidth */ x2 = x1 - maxWidth * (x2 < x1 || -1); fixAspectRatio(); } if (abs(y2 - y1) > maxHeight) { /* Selection height is greater than maxHeight */ y2 = y1 - maxHeight * (y2 < y1 || -1); fixAspectRatio(true); } selection = { x1: selX(min(x1, x2)), x2: selX(max(x1, x2)), y1: selY(min(y1, y2)), y2: selY(max(y1, y2)), width: abs(x2 - x1), height: abs(y2 - y1) }; update(); options.onSelectChange(img, getSelection()); } /** * Mousemove event handler triggered when the user is selecting an area * * @param event * The event object * @return false */ function selectingMouseMove(event) { x2 = /w|e|^$/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2); y2 = /n|s|^$/.test(resize) || aspectRatio ? evY(event) : viewY(selection.y2); doResize(); return false; } /** * Move the selection area * * @param newX1 * New viewport X1 * @param newY1 * New viewport Y1 */ function doMove(newX1, newY1) { x2 = (x1 = newX1) + selection.width; y2 = (y1 = newY1) + selection.height; $.extend(selection, { x1: selX(x1), y1: selY(y1), x2: selX(x2), y2: selY(y2) }); update(); options.onSelectChange(img, getSelection()); } /** * Mousemove event handler triggered when the selection area is being moved * * @param event * The event object * @return false */ function movingMouseMove(event) { x1 = max(left, min(startX + evX(event), left + imgWidth - selection.width)); y1 = max(top, min(startY + evY(event), top + imgHeight - selection.height)); doMove(x1, y1); event.preventDefault(); return false; } /** * Start selection */ function startSelection() { $(document).unbind('mousemove', startSelection); adjust(); x2 = x1; y2 = y1; doResize(); resize = ''; if (!$outer.is(':visible')) /* Show the plugin elements */ $box.add($outer).hide().fadeIn(options.fadeSpeed||0); shown = true; $(document).unbind('mouseup', cancelSelection) .mousemove(selectingMouseMove).one('mouseup', docMouseUp); $box.unbind('mousemove', areaMouseMove); options.onSelectStart(img, getSelection()); } /** * Cancel selection */ function cancelSelection() { $(document).unbind('mousemove', startSelection) .unbind('mouseup', cancelSelection); hide($box.add($outer)); setSelection(selX(x1), selY(y1), selX(x1), selY(y1)); /* If this is an API call, callback functions should not be triggered */ if (!(this instanceof $.imgAreaSelect)) { options.onSelectChange(img, getSelection()); options.onSelectEnd(img, getSelection()); } } /** * Image mousedown event handler * * @param event * The event object * @return false */ function imgMouseDown(event) { /* Ignore the event if animation is in progress */ if (event.which != 1 || $outer.is(':animated')) return false; adjust(); startX = x1 = evX(event); startY = y1 = evY(event); /* Selection will start when the mouse is moved */ $(document).mousemove(startSelection).mouseup(cancelSelection); return false; } /** * Window resize event handler */ function windowResize() { doUpdate(false); } /** * Image load event handler. This is the final part of the initialization * process. */ function imgLoad() { imgLoaded = true; /* Set options */ setOptions(options = $.extend({ classPrefix: 'imgareaselect', movable: true, parent: 'body', resizable: true, resizeMargin: 10, onInit: function () {}, onSelectStart: function () {}, onSelectChange: function () {}, onSelectEnd: function () {} }, options)); $box.add($outer).css({ visibility: '' }); if (options.show) { shown = true; adjust(); update(); $box.add($outer).hide().fadeIn(options.fadeSpeed||0); } /* * Call the onInit callback. The setTimeout() call is used to ensure * that the plugin has been fully initialized and the object instance is * available (so that it can be obtained in the callback). */ setTimeout(function () { options.onInit(img, getSelection()); }, 0); } /** * Document keypress event handler * * @param event * The event object * @return false */ var docKeyPress = function(event) { var k = options.keys, d, t, key = event.keyCode; d = !isNaN(k.alt) && (event.altKey || event.originalEvent.altKey) ? k.alt : !isNaN(k.ctrl) && event.ctrlKey ? k.ctrl : !isNaN(k.shift) && event.shiftKey ? k.shift : !isNaN(k.arrows) ? k.arrows : 10; if (k.arrows == 'resize' || (k.shift == 'resize' && event.shiftKey) || (k.ctrl == 'resize' && event.ctrlKey) || (k.alt == 'resize' && (event.altKey || event.originalEvent.altKey))) { /* Resize selection */ switch (key) { case 37: /* Left */ d = -d; case 39: /* Right */ t = max(x1, x2); x1 = min(x1, x2); x2 = max(t + d, x1); fixAspectRatio(); break; case 38: /* Up */ d = -d; case 40: /* Down */ t = max(y1, y2); y1 = min(y1, y2); y2 = max(t + d, y1); fixAspectRatio(true); break; default: return; } doResize(); } else { /* Move selection */ x1 = min(x1, x2); y1 = min(y1, y2); switch (key) { case 37: /* Left */ doMove(max(x1 - d, left), y1); break; case 38: /* Up */ doMove(x1, max(y1 - d, top)); break; case 39: /* Right */ doMove(x1 + min(d, imgWidth - selX(x2)), y1); break; case 40: /* Down */ doMove(x1, y1 + min(d, imgHeight - selY(y2))); break; default: return; } } return false; }; /** * Apply style options to plugin element (or multiple elements) * * @param $elem * A jQuery object representing the element(s) to style * @param props * An object that maps option names to corresponding CSS * properties */ function styleOptions($elem, props) { for (var option in props) if (options[option] !== undefined) $elem.css(props[option], options[option]); } /** * Set plugin options * * @param newOptions * The new options object */ function setOptions(newOptions) { if (newOptions.parent) ($parent = $(newOptions.parent)).append($box).append($outer); /* Merge the new options with the existing ones */ $.extend(options, newOptions); adjust(); if (newOptions.handles != null) { /* Recreate selection area handles */ $handles.remove(); $handles = $([]); i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0; while (i--) $handles = $handles.add(div()); /* Add a class to handles and set the CSS properties */ $handles.addClass(options.classPrefix + '-handle').css({ position: 'absolute', /* * The font-size property needs to be set to zero, otherwise * Internet Explorer makes the handles too large */ fontSize: 0, zIndex: zIndex + 1 || 1 }); /* * If handle width/height has not been set with CSS rules, set the * default 5px */ if (!parseInt($handles.css('width')) >= 0) $handles.width(5).height(5); /* * If the borderWidth option is in use, add a solid border to * handles */ if (o = options.borderWidth) $handles.css({ borderWidth: o, borderStyle: 'solid' }); /* Apply other style options */ styleOptions($handles, { borderColor1: 'border-color', borderColor2: 'background-color', borderOpacity: 'opacity' }); } /* Calculate scale factors */ scaleX = options.imageWidth / imgWidth || 1; scaleY = options.imageHeight / imgHeight || 1; /* Set selection */ if (newOptions.x1 != null) { setSelection(newOptions.x1, newOptions.y1, newOptions.x2, newOptions.y2); newOptions.show = !newOptions.hide; } if (newOptions.keys) /* Enable keyboard support */ options.keys = $.extend({ shift: 1, ctrl: 'resize' }, newOptions.keys); /* Add classes to plugin elements */ $outer.addClass(options.classPrefix + '-outer'); $area.addClass(options.classPrefix + '-selection'); for (i = 0; i++ < 4;) $($border[i-1]).addClass(options.classPrefix + '-border' + i); /* Apply style options */ styleOptions($area, { selectionColor: 'background-color', selectionOpacity: 'opacity' }); styleOptions($border, { borderOpacity: 'opacity', borderWidth: 'border-width' }); styleOptions($outer, { outerColor: 'background-color', outerOpacity: 'opacity' }); if (o = options.borderColor1) $($border[0]).css({ borderStyle: 'solid', borderColor: o }); if (o = options.borderColor2) $($border[1]).css({ borderStyle: 'dashed', borderColor: o }); /* Append all the selection area elements to the container box */ $box.append($area.add($border).add($areaOpera)).append($handles); if (msie) { if (o = ($outer.css('filter')||'').match(/opacity=(\d+)/)) $outer.css('opacity', o[1]/100); if (o = ($border.css('filter')||'').match(/opacity=(\d+)/)) $border.css('opacity', o[1]/100); } if (newOptions.hide) hide($box.add($outer)); else if (newOptions.show && imgLoaded) { shown = true; $box.add($outer).fadeIn(options.fadeSpeed||0); doUpdate(); } /* Calculate the aspect ratio factor */ aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1]; $img.add($outer).unbind('mousedown', imgMouseDown); if (options.disable || options.enable === false) { /* Disable the plugin */ $box.unbind('mousemove', areaMouseMove).unbind('mousedown', areaMouseDown); $(window).unbind('resize', windowResize); } else { if (options.enable || options.disable === false) { /* Enable the plugin */ if (options.resizable || options.movable) $box.mousemove(areaMouseMove).mousedown(areaMouseDown); $(window).resize(windowResize); } if (!options.persistent) $img.add($outer).mousedown(imgMouseDown); } options.enable = options.disable = undefined; } /** * Remove plugin completely */ this.remove = function () { /* * Call setOptions with { disable: true } to unbind the event handlers */ setOptions({ disable: true }); $box.add($outer).remove(); }; /* * Public API */ /** * Get current options * * @return An object containing the set of options currently in use */ this.getOptions = function () { return options; }; /** * Set plugin options * * @param newOptions * The new options object */ this.setOptions = setOptions; /** * Get the current selection * * @param noScale * If set to <code>true</code>, scaling is not applied to the * returned selection * @return Selection object */ this.getSelection = getSelection; /** * Set the current selection * * @param x1 * X coordinate of the upper left corner of the selection area * @param y1 * Y coordinate of the upper left corner of the selection area * @param x2 * X coordinate of the lower right corner of the selection area * @param y2 * Y coordinate of the lower right corner of the selection area * @param noScale * If set to <code>true</code>, scaling is not applied to the * new selection */ this.setSelection = setSelection; /** * Cancel selection */ this.cancelSelection = cancelSelection; /** * Update plugin elements * * @param resetKeyPress * If set to <code>false</code>, this instance's keypress * event handler is not activated */ this.update = doUpdate; /* Do the dreaded browser detection */ var msie = (/msie ([\w.]+)/i.exec(ua)||[])[1], opera = /opera/i.test(ua), safari = /webkit/i.test(ua) && !/chrome/i.test(ua); /* * Traverse the image's parent elements (up to <body>) and find the * highest z-index */ $p = $img; while ($p.length) { zIndex = max(zIndex, !isNaN($p.css('z-index')) ? $p.css('z-index') : zIndex); /* Also check if any of the ancestor elements has fixed position */ //if ($p.css('position') == 'fixed') // position = 'fixed'; $p = $p.parent(':not(body)'); } /* * If z-index is given as an option, it overrides the one found by the * above loop */ zIndex = options.zIndex || zIndex; if (msie) $img.attr('unselectable', 'on'); /* * In MSIE and WebKit, we need to use the keydown event instead of keypress */ $.imgAreaSelect.keyPress = msie || safari ? 'keydown' : 'keypress'; /* * There is a bug affecting the CSS cursor property in Opera (observed in * versions up to 10.00) that prevents the cursor from being updated unless * the mouse leaves and enters the element again. To trigger the mouseover * event, we're adding an additional div to $box and we're going to toggle * it when mouse moves inside the selection area. */ if (opera) $areaOpera = div().css({ width: '100%', height: '100%', position: 'absolute', zIndex: zIndex + 2 || 2 }); /* * We initially set visibility to "hidden" as a workaround for a weird * behaviour observed in Google Chrome 1.0.154.53 (on Windows XP). Normally * we would just set display to "none", but, for some reason, if we do so * then Chrome refuses to later display the element with .show() or * .fadeIn(). */ $box.add($outer).css({ visibility: 'hidden', position: position, overflow: 'hidden', zIndex: zIndex || '0' }); $box.css({ zIndex: zIndex + 2 || 2 }); $area.add($border).css({ position: 'absolute', fontSize: 0 }); /* * If the image has been fully loaded, or if it is not really an image (eg. * a div), call imgLoad() immediately; otherwise, bind it to be called once * on image load event. */ img.complete || img.readyState == 'complete' || !$img.is('img') ? imgLoad() : $img.one('load', imgLoad); /* * MSIE 9.0 doesn't always fire the image load event -- resetting the src * attribute seems to trigger it. The check is for version 7 and above to * accommodate for MSIE 9 running in compatibility mode. */ if (!imgLoaded && msie && msie >= 7) img.src = img.src; }; /** * Invoke imgAreaSelect on a jQuery object containing the image(s) * * @param options * Options object * @return The jQuery object or a reference to imgAreaSelect instance (if the * <code>instance</code> option was specified) */ $.fn.imgAreaSelect = function (options) { options = options || {}; this.each(function () { /* Is there already an imgAreaSelect instance bound to this element? */ if ($(this).data('imgAreaSelect')) { /* Yes there is -- is it supposed to be removed? */ if (options.remove) { /* Remove the plugin */ $(this).data('imgAreaSelect').remove(); $(this).removeData('imgAreaSelect'); } else /* Reset options */ $(this).data('imgAreaSelect').setOptions(options); } else if (!options.remove) { /* No exising instance -- create a new one */ /* * If neither the "enable" nor the "disable" option is present, add * "enable" as the default */ if (options.enable === undefined && options.disable === undefined) options.enable = true; $(this).data('imgAreaSelect', new $.imgAreaSelect(this, options)); } }); if (options.instance) /* * Return the imgAreaSelect instance bound to the first element in the * set */ return $(this).data('imgAreaSelect'); return this; }; })(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-imgareaselect-0.9.11-rc1.js
jquery-imgareaselect-0.9.11-rc1.js
(function(o,d){var k="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",h=/^([\-+])=\s*(\d+\.?\d*)/,g=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(p){return[p[1],p[2],p[3],p[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(p){return[p[1]*2.55,p[2]*2.55,p[3]*2.55,p[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(p){return[parseInt(p[1],16),parseInt(p[2],16),parseInt(p[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(p){return[parseInt(p[1]+p[1],16),parseInt(p[2]+p[2],16),parseInt(p[3]+p[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(p){return[p[1],p[2]/100,p[3]/100,p[4]]}}],e=o.Color=function(q,r,p,s){return new o.Color.fn.parse(q,r,p,s)},j={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},n={"byte":{floor:true,max:255},percent:{max:1},degrees:{mod:360,floor:true}},m=e.support={},b=o("<p>")[0],a,l=o.each;b.style.cssText="background-color:rgba(1,1,1,.5)";m.rgba=b.style.backgroundColor.indexOf("rgba")>-1;l(j,function(p,q){q.cache="_"+p;q.props.alpha={idx:3,type:"percent",def:1}});function i(q,s,r){var p=n[s.type]||{};if(q==null){return(r||!s.def)?null:s.def}q=p.floor?~~q:parseFloat(q);if(isNaN(q)){return s.def}if(p.mod){return(q+p.mod)%p.mod}return 0>q?0:p.max<q?p.max:q}function f(p){var r=e(),q=r._rgba=[];p=p.toLowerCase();l(g,function(w,x){var u,v=x.re.exec(p),t=v&&x.parse(v),s=x.space||"rgba";if(t){u=r[s](t);r[j[s].cache]=u[j[s].cache];q=r._rgba=u._rgba;return false}});if(q.length){if(q.join()==="0,0,0,0"){o.extend(q,a.transparent)}return r}return a[p]}e.fn=o.extend(e.prototype,{parse:function(v,t,p,u){if(v===d){this._rgba=[null,null,null,null];return this}if(v.jquery||v.nodeType){v=o(v).css(t);t=d}var s=this,r=o.type(v),q=this._rgba=[];if(t!==d){v=[v,t,p,u];r="array"}if(r==="string"){return this.parse(f(v)||a._default)}if(r==="array"){l(j.rgba.props,function(w,x){q[x.idx]=i(v[x.idx],x)});return this}if(r==="object"){if(v instanceof e){l(j,function(w,x){if(v[x.cache]){s[x.cache]=v[x.cache].slice()}})}else{l(j,function(x,y){var w=y.cache;l(y.props,function(z,A){if(!s[w]&&y.to){if(z==="alpha"||v[z]==null){return}s[w]=y.to(s._rgba)}s[w][A.idx]=i(v[z],A,true)});if(s[w]&&o.inArray(null,s[w].slice(0,3))<0){s[w][3]=1;if(y.from){s._rgba=y.from(s[w])}}})}return this}},is:function(r){var p=e(r),s=true,q=this;l(j,function(t,v){var w,u=p[v.cache];if(u){w=q[v.cache]||v.to&&v.to(q._rgba)||[];l(v.props,function(x,y){if(u[y.idx]!=null){s=(u[y.idx]===w[y.idx]);return s}})}return s});return s},_space:function(){var p=[],q=this;l(j,function(r,s){if(q[s.cache]){p.push(r)}});return p.pop()},transition:function(q,w){var r=e(q),s=r._space(),t=j[s],u=this.alpha()===0?e("transparent"):this,v=u[t.cache]||t.to(u._rgba),p=v.slice();r=r[t.cache];l(t.props,function(A,C){var z=C.idx,y=v[z],x=r[z],B=n[C.type]||{};if(x===null){return}if(y===null){p[z]=x}else{if(B.mod){if(x-y>B.mod/2){y+=B.mod}else{if(y-x>B.mod/2){y-=B.mod}}}p[z]=i((x-y)*w+y,C)}});return this[s](p)},blend:function(s){if(this._rgba[3]===1){return this}var r=this._rgba.slice(),q=r.pop(),p=e(s)._rgba;return e(o.map(r,function(t,u){return(1-q)*p[u]+q*t}))},toRgbaString:function(){var q="rgba(",p=o.map(this._rgba,function(r,s){return r==null?(s>2?1:0):r});if(p[3]===1){p.pop();q="rgb("}return q+p.join()+")"},toHslaString:function(){var q="hsla(",p=o.map(this.hsla(),function(r,s){if(r==null){r=s>2?1:0}if(s&&s<3){r=Math.round(r*100)+"%"}return r});if(p[3]===1){p.pop();q="hsl("}return q+p.join()+")"},toHexString:function(p){var q=this._rgba.slice(),r=q.pop();if(p){q.push(~~(r*255))}return"#"+o.map(q,function(s){s=(s||0).toString(16);return s.length===1?"0"+s:s}).join("")},toString:function(){return this._rgba[3]===0?"transparent":this.toRgbaString()}});e.fn.parse.prototype=e.fn;function c(t,s,r){r=(r+1)%1;if(r*6<1){return t+(s-t)*r*6}if(r*2<1){return s}if(r*3<2){return t+(s-t)*((2/3)-r)*6}return t}j.hsla.to=function(t){if(t[0]==null||t[1]==null||t[2]==null){return[null,null,null,t[3]]}var p=t[0]/255,w=t[1]/255,x=t[2]/255,z=t[3],y=Math.max(p,w,x),u=Math.min(p,w,x),A=y-u,B=y+u,q=B*0.5,v,C;if(u===y){v=0}else{if(p===y){v=(60*(w-x)/A)+360}else{if(w===y){v=(60*(x-p)/A)+120}else{v=(60*(p-w)/A)+240}}}if(A===0){C=0}else{if(q<=0.5){C=A/B}else{C=A/(2-B)}}return[Math.round(v)%360,C,q,z==null?1:z]};j.hsla.from=function(w){if(w[0]==null||w[1]==null||w[2]==null){return[null,null,null,w[3]]}var v=w[0]/360,u=w[1],t=w[2],r=w[3],x=t<=0.5?t*(1+u):t+u-t*u,y=2*t-x;return[Math.round(c(y,x,v+(1/3))*255),Math.round(c(y,x,v)*255),Math.round(c(y,x,v-(1/3))*255),r]};l(j,function(q,s){var r=s.props,p=s.cache,u=s.to,t=s.from;e.fn[q]=function(z){if(u&&!this[p]){this[p]=u(this._rgba)}if(z===d){return this[p].slice()}var w,y=o.type(z),v=(y==="array"||y==="object")?z:arguments,x=this[p].slice();l(r,function(A,C){var B=v[y==="object"?A:C.idx];if(B==null){B=x[C.idx]}x[C.idx]=i(B,C)});if(t){w=e(t(x));w[p]=x;return w}else{return e(x)}};l(r,function(v,w){if(e.fn[v]){return}e.fn[v]=function(A){var C=o.type(A),z=(v==="alpha"?(this._hsla?"hsla":"rgba"):q),y=this[z](),B=y[w.idx],x;if(C==="undefined"){return B}if(C==="function"){A=A.call(this,B);C=o.type(A)}if(A==null&&w.empty){return this}if(C==="string"){x=h.exec(A);if(x){A=B+parseFloat(x[2])*(x[1]==="+"?1:-1)}}y[w.idx]=A;return this[z](y)}})});e.hook=function(q){var p=q.split(" ");l(p,function(r,s){o.cssHooks[s]={set:function(w,x){var u,v,t="";if(x!=="transparent"&&(o.type(x)!=="string"||(u=f(x)))){x=e(u||x);if(!m.rgba&&x._rgba[3]!==1){v=s==="backgroundColor"?w.parentNode:w;while((t===""||t==="transparent")&&v&&v.style){try{t=o.css(v,"backgroundColor");v=v.parentNode}catch(y){}}x=x.blend(t&&t!=="transparent"?t:"_default")}x=x.toRgbaString()}try{w.style[s]=x}catch(y){}}};o.fx.step[s]=function(t){if(!t.colorInit){t.start=e(t.elem,s);t.end=e(t.end);t.colorInit=true}o.cssHooks[s].set(t.elem,t.start.transition(t.end,t.pos))}})};e.hook(k);o.cssHooks.borderColor={expand:function(q){var p={};l(["Top","Right","Bottom","Left"],function(s,r){p["border"+r+"Color"]=q});return p}};a=o.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-color-2.1.2.min.js
jquery-color-2.1.2.min.js
(function(a){a.fn.rowGrouping=function(e){function b(){}function c(j,h,i){}function d(j,h,i){}function g(i){var h=["January","February","March","April","May","June","July","August","September","October","November","December"];return h[i-1]}var f={iGroupingColumnIndex:0,sGroupingColumnSortDirection:"",iGroupingOrderByColumnIndex:-1,sGroupingClass:"group",sGroupItemClass:"group-item",bHideGroupingColumn:true,bHideGroupingOrderByColumn:true,sGroupBy:"name",sGroupLabelPrefix:"",fnGroupLabelFormat:function(h){return h},bExpandableGrouping:false,bExpandSingleGroup:false,iExpandGroupOffset:100,asExpandedGroups:null,sDateFormat:"dd/MM/yyyy",sEmptyGroupLabel:"-",bSetGroupingClassOnTR:false,iGroupingColumnIndex2:-1,sGroupingColumnSortDirection2:"",iGroupingOrderByColumnIndex2:-1,sGroupingClass2:"subgroup",sGroupItemClass2:"subgroup-item",bHideGroupingColumn2:true,bHideGroupingOrderByColumn2:true,sGroupBy2:"name",sGroupLabelPrefix2:"",fnGroupLabelFormat2:function(h){return h},bExpandableGrouping2:false,fnOnGrouped:b,fnOnGroupCreated:c,fnOnGroupCompleted:d,oHideEffect:null,oShowEffect:null,bUseFilteringForGrouping:false};return this.each(function(s,J){var E=a(J).dataTable();var B=new Array();a(this).dataTableExt.aoGroups=B;function q(T,i,P){var R=document.createElement("tr");var S=document.createElement("td");R.id="group-id-"+E.attr("id")+"_"+T;var Q={id:R.id,key:T,text:i,level:0,groupItemClass:".group-item-"+T,dataGroup:T,aoSubgroups:new Array()};if(t.bSetGroupingClassOnTR){R.className=t.sGroupingClass+" "+T}else{S.className=t.sGroupingClass+" "+T}S.colSpan=P;S.innerHTML=t.sGroupLabelPrefix+t.fnGroupLabelFormat(i==""?t.sEmptyGroupLabel:i,Q);if(t.bExpandableGrouping){if(!I(T)){S.className+=" expanded-group";Q.state="expanded"}else{S.className+=" collapsed-group";Q.state="collapsed"}S.className+=" group-item-expander";a(S).attr("data-group",Q.dataGroup);a(S).attr("data-group-level",Q.level);a(S).click(h)}R.appendChild(S);B[T]=Q;Q.nGroup=R;t.fnOnGroupCreated(Q,T,1);return Q}function w(R,Q,P,T){var i=document.createElement("tr");i.id=T.id+"_"+R;var V=document.createElement("td");var U=T.dataGroup+"_"+R;var S={id:i.id,key:R,text:Q,level:T.level+1,groupItemClass:".group-item-"+U,dataGroup:U,aoSubgroups:new Array()};if(t.bSetGroupingClassOnTR){i.className=t.sGroupingClass2+" "+R}else{V.className=t.sGroupingClass2+" "+R}V.colSpan=P;V.innerHTML=t.sGroupLabelPrefix2+t.fnGroupLabelFormat2(Q==""?t.sEmptyGroupLabel:Q,S);if(t.bExpandableGrouping){i.className+=" group-item-"+T.dataGroup}if(t.bExpandableGrouping&&t.bExpandableGrouping2){if(!I(S.dataGroup)){V.className+=" expanded-group";S.state="expanded"}else{V.className+=" collapsed-group";S.state="collapsed"}V.className+=" group-item-expander";a(V).attr("data-group",S.dataGroup);a(V).attr("data-group-level",S.level);a(V).click(h)}i.appendChild(V);T.aoSubgroups[S.dataGroup]=S;B[S.dataGroup]=S;S.nGroup=i;t.fnOnGroupCreated(S,R,2);return S}function I(i){if(B[i]!=null){return(B[i].state=="collapsed")}else{if(i.indexOf("_")>-1){true}else{if(l&&(j==null||j.length==0)){return false}else{return(a.inArray(i,j)==-1)}}}}function L(i){if(i.length<(x+K)){return i}else{return i.substr(x,K)}}function y(i){return i}function M(i){return i.substr(0,1)}function O(i){return L(i)}function C(i){return i.substr(x,K)+" "+g(i.substr(r,H))}function u(i){if(i===""){return"-"}return i.toLowerCase().replace(/[^a-zA-Z0-9\u0080-\uFFFF]+/g,"-")}function D(R,P,i){if(R.nTable.id!==E[0].id){return true}var Q=P[t.iGroupingColumnIndex];if(typeof Q==="undefined"){Q=P[R.aoColumns[t.iGroupingColumnIndex].mDataProp]}if(I(u(Q))){if(E.fnIsOpen(E.fnGetNodes(i))){if(t.fnOnRowClosed!=null){t.fnOnRowClosed(this)}E.fnClose(E.fnGetNodes(i))}return false}return true}function p(i){B[i].state="expanded";a("td[data-group^='"+i+"']").removeClass("collapsed-group");a("td[data-group^='"+i+"']").addClass("expanded-group");if(t.bUseFilteringForGrouping){E.fnDraw();return}if(jQuery.inArray(i,j)==-1){j.push(i)}if(t.oHideEffect!=null){a(".group-item-"+i,E)[t.oShowEffect.method](t.oShowEffect.duration,t.oShowEffect.easing,function(){})}else{a(".group-item-"+i,E).show()}}function m(i){B[i].state="collapsed";a("td[data-group^='"+i+"']").removeClass("expanded-group");a("td[data-group^='"+i+"']").addClass("collapsed-group");if(t.bUseFilteringForGrouping){E.fnDraw();return}a(".group-item-"+i).each(function(){if(E.fnIsOpen(this)){if(t.fnOnRowClosed!=null){t.fnOnRowClosed(this)}E.fnClose(this)}});if(t.oHideEffect!=null){a(".group-item-"+i,E)[t.oHideEffect.method](t.oHideEffect.duration,t.oHideEffect.easing,function(){})}else{a(".group-item-"+i,E).hide()}}function h(T){var Q=a(this).attr("data-group");var S=a(this).attr("data-group-level");var R=!I(Q);if(t.bExpandSingleGroup){if(!R){var P=a("td.expanded-group").attr("data-group");m(P);p(Q);if(t.iExpandGroupOffset!=-1){var i=a("#group-id-"+E.attr("id")+"_"+Q).offset().top-t.iExpandGroupOffset;window.scroll(0,i)}else{var i=E.offset().top;window.scroll(0,i)}}}else{if(R){m(Q)}else{p(Q)}}T.preventDefault()}function A(V){if(E.fnSettings().oFeatures.bServerSide){l=true}var Z=false;if(t.iGroupingColumnIndex2!=-1){Z=true}if(V.aiDisplayMaster.length==0){return}var T=a("tbody tr",E);var Q=0;for(var ae=0;ae<V.aoColumns.length;ae++){if(V.aoColumns[ae].bVisible){Q+=1}}var ah=null;var aa=null;if(V.aiDisplay.length>0){for(var ag=0;ag<T.length;ag++){var U=V._iDisplayStart+ag;if(E.fnSettings().oFeatures.bServerSide){U=ag}var S="";var af=null;var P="";var Y=null;S=this.fnGetData(T[ag],t.iGroupingColumnIndex);var af=S;if(t.sGroupBy!="year"){af=N(S)}if(Z){P=V.aoData[V.aiDisplay[U]]._aData[t.iGroupingColumnIndex2];if(P==undefined){P=V.aoData[V.aiDisplay[U]]._aData[V.aoColumns[t.iGroupingColumnIndex2].mDataProp]}if(t.sGroupBy2!="year"){Y=N(P)}}if(ah==null||u(af)!=u(ah)){var ab=u(af);if(ah!=null){t.fnOnGroupCompleted(B[u(ah)])}if(t.bAddAllGroupsAsExpanded&&jQuery.inArray(ab,j)==-1){j.push(ab)}var W=q(ab,af,Q);var R=W.nGroup;if(T[ag].parentNode!=null){T[ag].parentNode.insertBefore(R,T[ag])}else{a(T[ag]).before(R)}ah=af;aa=null}a(T[ag]).attr("data-group",B[ab].dataGroup);a(T[ag]).addClass(t.sGroupItemClass);a(T[ag]).addClass("group-item-"+ab);if(t.bExpandableGrouping){if(I(ab)&&!t.bUseFilteringForGrouping){a(T[ag]).hide()}}if(Z){if(aa==null||u(Y)!=u(aa)){var X=u(af)+"-"+u(Y);var ac=w(X,Y,Q,B[ab]);var ad=ac.nGroup;T[ag].parentNode.insertBefore(ad,T[ag]);aa=Y}a(T[ag]).attr("data-group",ac.dataGroup).addClass(t.sGroupItemClass2).addClass("group-item-"+ac.dataGroup)}}}if(ah!=null){t.fnOnGroupCompleted(B[u(ah)])}t.fnOnGrouped(B);l=false}var x=6;var K=4;var j=new Array();var l=true;var t=a.extend(f,e);if(t.iGroupingOrderByColumnIndex==-1){t.bCustomColumnOrdering=false;t.iGroupingOrderByColumnIndex=t.iGroupingColumnIndex}else{t.bCustomColumnOrdering=true}if(t.sGroupingColumnSortDirection==""){if(t.sGroupBy=="year"){t.sGroupingColumnSortDirection="desc"}else{t.sGroupingColumnSortDirection="asc"}}if(t.iGroupingOrderByColumnIndex2==-1){t.bCustomColumnOrdering2=false;t.iGroupingOrderByColumnIndex2=t.iGroupingColumnIndex2}else{t.bCustomColumnOrdering2=true}if(t.sGroupingColumnSortDirection2==""){if(t.sGroupBy2=="year"){t.sGroupingColumnSortDirection2="desc"}else{t.sGroupingColumnSortDirection2="asc"}}x=t.sDateFormat.toLowerCase().indexOf("yy");K=t.sDateFormat.toLowerCase().lastIndexOf("y")-t.sDateFormat.toLowerCase().indexOf("y")+1;var r=t.sDateFormat.toLowerCase().indexOf("mm");var H=t.sDateFormat.toLowerCase().lastIndexOf("m")-t.sDateFormat.toLowerCase().indexOf("m")+1;var N=y;switch(t.sGroupBy){case"letter":N=M;break;case"year":N=O;break;case"month":N=C;break;default:N=y;break}if(t.asExpandedGroups!=null){if(t.asExpandedGroups=="NONE"){t.asExpandedGroups=[];j=t.asExpandedGroups;l=false}else{if(t.asExpandedGroups=="ALL"){t.bAddAllGroupsAsExpanded=true}else{if(t.asExpandedGroups.constructor==String){var k=t.asExpandedGroups;t.asExpandedGroups=new Array();t.asExpandedGroups.push(u(k));j=t.asExpandedGroups;l=false}else{if(t.asExpandedGroups.constructor==Array){for(var G=0;G<t.asExpandedGroups.length;G++){j.push(u(t.asExpandedGroups[G]));if(t.bExpandSingleGroup){break}}l=false}}}}}else{t.asExpandedGroups=new Array();t.bAddAllGroupsAsExpanded=true}if(t.bExpandSingleGroup){var o=a("tbody tr",E);var n=E.fnGetData(o[0],t.iGroupingColumnIndex);var F=n;if(t.sGroupBy!="year"){F=N(n)}var z=u(F);t.asExpandedGroups=new Array();t.asExpandedGroups.push(z)}E.fnSetColumnVis(t.iGroupingColumnIndex,!t.bHideGroupingColumn);if(t.bCustomColumnOrdering){E.fnSetColumnVis(t.iGroupingOrderByColumnIndex,!t.bHideGroupingOrderByColumn)}if(t.iGroupingColumnIndex2!=-1){E.fnSetColumnVis(t.iGroupingColumnIndex2,!t.bHideGroupingColumn2)}if(t.bCustomColumnOrdering2){E.fnSetColumnVis(t.iGroupingOrderByColumnIndex2,!t.bHideGroupingOrderByColumn2)}E.fnSettings().aoDrawCallback.push({fn:A,sName:"fnRowGrouping"});var v=new Array();v.push([t.iGroupingOrderByColumnIndex,t.sGroupingColumnSortDirection]);if(t.iGroupingColumnIndex2!=-1){v.push([t.iGroupingOrderByColumnIndex2,t.sGroupingColumnSortDirection2])}E.fnSettings().aaSortingFixed=v;switch(t.sGroupBy){case"name":break;case"letter":E.fnSettings().aoColumns[t.iGroupingOrderByColumnIndex].sSortDataType="rg-letter";a.fn.dataTableExt.afnSortData["rg-letter"]=function(Q,P){var i=[];a("td:eq("+P+")",Q.oApi._fnGetTrNodes(Q)).each(function(){i.push(M(this.innerHTML))});return i};break;case"year":E.fnSettings().aoColumns[t.iGroupingOrderByColumnIndex].sSortDataType="rg-date";a.fn.dataTableExt.afnSortData["rg-date"]=function(R,P){var i=[];var Q=R.oApi._fnGetTrNodes(R);for(G=0;G<Q.length;G++){i.push(L(E.fnGetData(Q[G],P)))}return i};break;default:break}if(t.bUseFilteringForGrouping){a.fn.dataTableExt.afnFiltering.push(D)}E.fnDraw()})}})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-rowGrouping.min.js
jquery-dataTables-rowGrouping.min.js
(function(c){var b={init:function(e){var f={set_width:false,set_height:false,horizontalScroll:false,scrollInertia:950,mouseWheel:true,mouseWheelPixels:"auto",autoDraggerLength:true,autoHideScrollbar:false,alwaysShowScrollbar:false,snapAmount:null,snapOffset:0,scrollButtons:{enable:false,scrollType:"continuous",scrollSpeed:"auto",scrollAmount:40},advanced:{updateOnBrowserResize:true,updateOnContentResize:false,autoExpandHorizontalScroll:false,autoScrollOnFocus:true,normalizeMouseWheelDelta:false},contentTouchScroll:true,callbacks:{onScrollStart:function(){},onScroll:function(){},onTotalScroll:function(){},onTotalScrollBack:function(){},onTotalScrollOffset:0,onTotalScrollBackOffset:0,whileScrolling:function(){}},theme:"light"},e=c.extend(true,f,e);return this.each(function(){var m=c(this);if(e.set_width){m.css("width",e.set_width)}if(e.set_height){m.css("height",e.set_height)}if(!c(document).data("mCustomScrollbar-index")){c(document).data("mCustomScrollbar-index","1")}else{var t=parseInt(c(document).data("mCustomScrollbar-index"));c(document).data("mCustomScrollbar-index",t+1)}m.wrapInner("<div class='mCustomScrollBox mCS-"+e.theme+"' id='mCSB_"+c(document).data("mCustomScrollbar-index")+"' style='position:relative; height:100%; overflow:hidden; max-width:100%;' />").addClass("mCustomScrollbar _mCS_"+c(document).data("mCustomScrollbar-index"));var g=m.children(".mCustomScrollBox");if(e.horizontalScroll){g.addClass("mCSB_horizontal").wrapInner("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />");var k=g.children(".mCSB_h_wrapper");k.wrapInner("<div class='mCSB_container' style='position:absolute; left:0;' />").children(".mCSB_container").css({width:k.children().outerWidth(),position:"relative"}).unwrap()}else{g.wrapInner("<div class='mCSB_container' style='position:relative; top:0;' />")}var o=g.children(".mCSB_container");if(c.support.touch){o.addClass("mCS_touch")}o.after("<div class='mCSB_scrollTools' style='position:absolute;'><div class='mCSB_draggerContainer'><div class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'><div class='mCSB_dragger_bar' style='position:relative;'></div></div><div class='mCSB_draggerRail'></div></div></div>");var l=g.children(".mCSB_scrollTools"),h=l.children(".mCSB_draggerContainer"),q=h.children(".mCSB_dragger");if(e.horizontalScroll){q.data("minDraggerWidth",q.width())}else{q.data("minDraggerHeight",q.height())}if(e.scrollButtons.enable){if(e.horizontalScroll){l.prepend("<a class='mCSB_buttonLeft' oncontextmenu='return false;'></a>").append("<a class='mCSB_buttonRight' oncontextmenu='return false;'></a>")}else{l.prepend("<a class='mCSB_buttonUp' oncontextmenu='return false;'></a>").append("<a class='mCSB_buttonDown' oncontextmenu='return false;'></a>")}}g.bind("scroll",function(){if(!m.is(".mCS_disabled")){g.scrollTop(0).scrollLeft(0)}});m.data({mCS_Init:true,mCustomScrollbarIndex:c(document).data("mCustomScrollbar-index"),horizontalScroll:e.horizontalScroll,scrollInertia:e.scrollInertia,scrollEasing:"mcsEaseOut",mouseWheel:e.mouseWheel,mouseWheelPixels:e.mouseWheelPixels,autoDraggerLength:e.autoDraggerLength,autoHideScrollbar:e.autoHideScrollbar,alwaysShowScrollbar:e.alwaysShowScrollbar,snapAmount:e.snapAmount,snapOffset:e.snapOffset,scrollButtons_enable:e.scrollButtons.enable,scrollButtons_scrollType:e.scrollButtons.scrollType,scrollButtons_scrollSpeed:e.scrollButtons.scrollSpeed,scrollButtons_scrollAmount:e.scrollButtons.scrollAmount,autoExpandHorizontalScroll:e.advanced.autoExpandHorizontalScroll,autoScrollOnFocus:e.advanced.autoScrollOnFocus,normalizeMouseWheelDelta:e.advanced.normalizeMouseWheelDelta,contentTouchScroll:e.contentTouchScroll,onScrollStart_Callback:e.callbacks.onScrollStart,onScroll_Callback:e.callbacks.onScroll,onTotalScroll_Callback:e.callbacks.onTotalScroll,onTotalScrollBack_Callback:e.callbacks.onTotalScrollBack,onTotalScroll_Offset:e.callbacks.onTotalScrollOffset,onTotalScrollBack_Offset:e.callbacks.onTotalScrollBackOffset,whileScrolling_Callback:e.callbacks.whileScrolling,bindEvent_scrollbar_drag:false,bindEvent_content_touch:false,bindEvent_scrollbar_click:false,bindEvent_mousewheel:false,bindEvent_buttonsContinuous_y:false,bindEvent_buttonsContinuous_x:false,bindEvent_buttonsPixels_y:false,bindEvent_buttonsPixels_x:false,bindEvent_focusin:false,bindEvent_autoHideScrollbar:false,mCSB_buttonScrollRight:false,mCSB_buttonScrollLeft:false,mCSB_buttonScrollDown:false,mCSB_buttonScrollUp:false});if(e.horizontalScroll){if(m.css("max-width")!=="none"){if(!e.advanced.updateOnContentResize){e.advanced.updateOnContentResize=true}}}else{if(m.css("max-height")!=="none"){var s=false,r=parseInt(m.css("max-height"));if(m.css("max-height").indexOf("%")>=0){s=r,r=m.parent().height()*s/100}m.css("overflow","hidden");g.css("max-height",r)}}m.mCustomScrollbar("update");if(e.advanced.updateOnBrowserResize){var i,j=c(window).width(),u=c(window).height();c(window).bind("resize."+m.data("mCustomScrollbarIndex"),function(){if(i){clearTimeout(i)}i=setTimeout(function(){if(!m.is(".mCS_disabled")&&!m.is(".mCS_destroyed")){var w=c(window).width(),v=c(window).height();if(j!==w||u!==v){if(m.css("max-height")!=="none"&&s){g.css("max-height",m.parent().height()*s/100)}m.mCustomScrollbar("update");j=w;u=v}}},150)})}if(e.advanced.updateOnContentResize){var p;if(e.horizontalScroll){var n=o.outerWidth()}else{var n=o.outerHeight()}p=setInterval(function(){if(e.horizontalScroll){if(e.advanced.autoExpandHorizontalScroll){o.css({position:"absolute",width:"auto"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({width:o.outerWidth(),position:"relative"}).unwrap()}var v=o.outerWidth()}else{var v=o.outerHeight()}if(v!=n){m.mCustomScrollbar("update");n=v}},300)}})},update:function(){var n=c(this),k=n.children(".mCustomScrollBox"),q=k.children(".mCSB_container");q.removeClass("mCS_no_scrollbar");n.removeClass("mCS_disabled mCS_destroyed");k.scrollTop(0).scrollLeft(0);var y=k.children(".mCSB_scrollTools"),o=y.children(".mCSB_draggerContainer"),m=o.children(".mCSB_dragger");if(n.data("horizontalScroll")){var A=y.children(".mCSB_buttonLeft"),t=y.children(".mCSB_buttonRight"),f=k.width();if(n.data("autoExpandHorizontalScroll")){q.css({position:"absolute",width:"auto"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({width:q.outerWidth(),position:"relative"}).unwrap()}var z=q.outerWidth()}else{var w=y.children(".mCSB_buttonUp"),g=y.children(".mCSB_buttonDown"),r=k.height(),i=q.outerHeight()}if(i>r&&!n.data("horizontalScroll")){y.css("display","block");var s=o.height();if(n.data("autoDraggerLength")){var u=Math.round(r/i*s),l=m.data("minDraggerHeight");if(u<=l){m.css({height:l})}else{if(u>=s-10){var p=s-10;m.css({height:p})}else{m.css({height:u})}}m.children(".mCSB_dragger_bar").css({"line-height":m.height()+"px"})}var B=m.height(),x=(i-r)/(s-B);n.data("scrollAmount",x).mCustomScrollbar("scrolling",k,q,o,m,w,g,A,t);var D=Math.abs(q.position().top);n.mCustomScrollbar("scrollTo",D,{scrollInertia:0,trigger:"internal"})}else{if(z>f&&n.data("horizontalScroll")){y.css("display","block");var h=o.width();if(n.data("autoDraggerLength")){var j=Math.round(f/z*h),C=m.data("minDraggerWidth");if(j<=C){m.css({width:C})}else{if(j>=h-10){var e=h-10;m.css({width:e})}else{m.css({width:j})}}}var v=m.width(),x=(z-f)/(h-v);n.data("scrollAmount",x).mCustomScrollbar("scrolling",k,q,o,m,w,g,A,t);var D=Math.abs(q.position().left);n.mCustomScrollbar("scrollTo",D,{scrollInertia:0,trigger:"internal"})}else{k.unbind("mousewheel focusin");if(n.data("horizontalScroll")){m.add(q).css("left",0)}else{m.add(q).css("top",0)}if(n.data("alwaysShowScrollbar")){if(!n.data("horizontalScroll")){m.css({height:o.height()})}else{if(n.data("horizontalScroll")){m.css({width:o.width()})}}}else{y.css("display","none");q.addClass("mCS_no_scrollbar")}n.data({bindEvent_mousewheel:false,bindEvent_focusin:false})}}},scrolling:function(i,q,n,k,A,f,D,w){var l=c(this);if(!l.data("bindEvent_scrollbar_drag")){var o,p,C,z,e;if(c.support.pointer){C="pointerdown";z="pointermove";e="pointerup"}else{if(c.support.msPointer){C="MSPointerDown";z="MSPointerMove";e="MSPointerUp"}}if(c.support.pointer||c.support.msPointer){k.bind(C,function(K){K.preventDefault();l.data({on_drag:true});k.addClass("mCSB_dragger_onDrag");var J=c(this),M=J.offset(),I=K.originalEvent.pageX-M.left,L=K.originalEvent.pageY-M.top;if(I<J.width()&&I>0&&L<J.height()&&L>0){o=L;p=I}});c(document).bind(z+"."+l.data("mCustomScrollbarIndex"),function(K){K.preventDefault();if(l.data("on_drag")){var J=k,M=J.offset(),I=K.originalEvent.pageX-M.left,L=K.originalEvent.pageY-M.top;G(o,p,L,I)}}).bind(e+"."+l.data("mCustomScrollbarIndex"),function(x){l.data({on_drag:false});k.removeClass("mCSB_dragger_onDrag")})}else{k.bind("mousedown touchstart",function(K){K.preventDefault();K.stopImmediatePropagation();var J=c(this),N=J.offset(),I,M;if(K.type==="touchstart"){var L=K.originalEvent.touches[0]||K.originalEvent.changedTouches[0];I=L.pageX-N.left;M=L.pageY-N.top}else{l.data({on_drag:true});k.addClass("mCSB_dragger_onDrag");I=K.pageX-N.left;M=K.pageY-N.top}if(I<J.width()&&I>0&&M<J.height()&&M>0){o=M;p=I}}).bind("touchmove",function(K){K.preventDefault();K.stopImmediatePropagation();var N=K.originalEvent.touches[0]||K.originalEvent.changedTouches[0],J=c(this),M=J.offset(),I=N.pageX-M.left,L=N.pageY-M.top;G(o,p,L,I)});c(document).bind("mousemove."+l.data("mCustomScrollbarIndex"),function(K){if(l.data("on_drag")){var J=k,M=J.offset(),I=K.pageX-M.left,L=K.pageY-M.top;G(o,p,L,I)}}).bind("mouseup."+l.data("mCustomScrollbarIndex"),function(x){l.data({on_drag:false});k.removeClass("mCSB_dragger_onDrag")})}l.data({bindEvent_scrollbar_drag:true})}function G(J,K,L,I){if(l.data("horizontalScroll")){l.mCustomScrollbar("scrollTo",(k.position().left-(K))+I,{moveDragger:true,trigger:"internal"})}else{l.mCustomScrollbar("scrollTo",(k.position().top-(J))+L,{moveDragger:true,trigger:"internal"})}}if(c.support.touch&&l.data("contentTouchScroll")){if(!l.data("bindEvent_content_touch")){var m,E,s,t,v,F,H;q.bind("touchstart",function(x){x.stopImmediatePropagation();m=x.originalEvent.touches[0]||x.originalEvent.changedTouches[0];E=c(this);s=E.offset();v=m.pageX-s.left;t=m.pageY-s.top;F=t;H=v});q.bind("touchmove",function(x){x.preventDefault();x.stopImmediatePropagation();m=x.originalEvent.touches[0]||x.originalEvent.changedTouches[0];E=c(this).parent();s=E.offset();v=m.pageX-s.left;t=m.pageY-s.top;if(l.data("horizontalScroll")){l.mCustomScrollbar("scrollTo",H-v,{trigger:"internal"})}else{l.mCustomScrollbar("scrollTo",F-t,{trigger:"internal"})}})}}if(!l.data("bindEvent_scrollbar_click")){n.bind("click",function(I){var x=(I.pageY-n.offset().top)*l.data("scrollAmount"),y=c(I.target);if(l.data("horizontalScroll")){x=(I.pageX-n.offset().left)*l.data("scrollAmount")}if(y.hasClass("mCSB_draggerContainer")||y.hasClass("mCSB_draggerRail")){l.mCustomScrollbar("scrollTo",x,{trigger:"internal",scrollEasing:"draggerRailEase"})}});l.data({bindEvent_scrollbar_click:true})}if(l.data("mouseWheel")){if(!l.data("bindEvent_mousewheel")){i.bind("mousewheel",function(K,M){var J,I=l.data("mouseWheelPixels"),x=Math.abs(q.position().top),L=k.position().top,y=n.height()-k.height();if(l.data("normalizeMouseWheelDelta")){if(M<0){M=-1}else{M=1}}if(I==="auto"){I=100+Math.round(l.data("scrollAmount")/2)}if(l.data("horizontalScroll")){L=k.position().left;y=n.width()-k.width();x=Math.abs(q.position().left)}if((M>0&&L!==0)||(M<0&&L!==y)){K.preventDefault();K.stopImmediatePropagation()}J=x-(M*I);l.mCustomScrollbar("scrollTo",J,{trigger:"internal"})});l.data({bindEvent_mousewheel:true})}}if(l.data("scrollButtons_enable")){if(l.data("scrollButtons_scrollType")==="pixels"){if(l.data("horizontalScroll")){w.add(D).unbind("mousedown touchstart MSPointerDown pointerdown mouseup MSPointerUp pointerup mouseout MSPointerOut pointerout touchend",j,h);l.data({bindEvent_buttonsContinuous_x:false});if(!l.data("bindEvent_buttonsPixels_x")){w.bind("click",function(x){x.preventDefault();r(Math.abs(q.position().left)+l.data("scrollButtons_scrollAmount"))});D.bind("click",function(x){x.preventDefault();r(Math.abs(q.position().left)-l.data("scrollButtons_scrollAmount"))});l.data({bindEvent_buttonsPixels_x:true})}}else{f.add(A).unbind("mousedown touchstart MSPointerDown pointerdown mouseup MSPointerUp pointerup mouseout MSPointerOut pointerout touchend",j,h);l.data({bindEvent_buttonsContinuous_y:false});if(!l.data("bindEvent_buttonsPixels_y")){f.bind("click",function(x){x.preventDefault();r(Math.abs(q.position().top)+l.data("scrollButtons_scrollAmount"))});A.bind("click",function(x){x.preventDefault();r(Math.abs(q.position().top)-l.data("scrollButtons_scrollAmount"))});l.data({bindEvent_buttonsPixels_y:true})}}function r(x){if(!k.data("preventAction")){k.data("preventAction",true);l.mCustomScrollbar("scrollTo",x,{trigger:"internal"})}}}else{if(l.data("horizontalScroll")){w.add(D).unbind("click");l.data({bindEvent_buttonsPixels_x:false});if(!l.data("bindEvent_buttonsContinuous_x")){w.bind("mousedown touchstart MSPointerDown pointerdown",function(y){y.preventDefault();var x=B();l.data({mCSB_buttonScrollRight:setInterval(function(){l.mCustomScrollbar("scrollTo",Math.abs(q.position().left)+x,{trigger:"internal",scrollEasing:"easeOutCirc"})},17)})});var j=function(x){x.preventDefault();clearInterval(l.data("mCSB_buttonScrollRight"))};w.bind("mouseup touchend MSPointerUp pointerup mouseout MSPointerOut pointerout",j);D.bind("mousedown touchstart MSPointerDown pointerdown",function(y){y.preventDefault();var x=B();l.data({mCSB_buttonScrollLeft:setInterval(function(){l.mCustomScrollbar("scrollTo",Math.abs(q.position().left)-x,{trigger:"internal",scrollEasing:"easeOutCirc"})},17)})});var h=function(x){x.preventDefault();clearInterval(l.data("mCSB_buttonScrollLeft"))};D.bind("mouseup touchend MSPointerUp pointerup mouseout MSPointerOut pointerout",h);l.data({bindEvent_buttonsContinuous_x:true})}}else{f.add(A).unbind("click");l.data({bindEvent_buttonsPixels_y:false});if(!l.data("bindEvent_buttonsContinuous_y")){f.bind("mousedown touchstart MSPointerDown pointerdown",function(y){y.preventDefault();var x=B();l.data({mCSB_buttonScrollDown:setInterval(function(){l.mCustomScrollbar("scrollTo",Math.abs(q.position().top)+x,{trigger:"internal",scrollEasing:"easeOutCirc"})},17)})});var u=function(x){x.preventDefault();clearInterval(l.data("mCSB_buttonScrollDown"))};f.bind("mouseup touchend MSPointerUp pointerup mouseout MSPointerOut pointerout",u);A.bind("mousedown touchstart MSPointerDown pointerdown",function(y){y.preventDefault();var x=B();l.data({mCSB_buttonScrollUp:setInterval(function(){l.mCustomScrollbar("scrollTo",Math.abs(q.position().top)-x,{trigger:"internal",scrollEasing:"easeOutCirc"})},17)})});var g=function(x){x.preventDefault();clearInterval(l.data("mCSB_buttonScrollUp"))};A.bind("mouseup touchend MSPointerUp pointerup mouseout MSPointerOut pointerout",g);l.data({bindEvent_buttonsContinuous_y:true})}}function B(){var x=l.data("scrollButtons_scrollSpeed");if(l.data("scrollButtons_scrollSpeed")==="auto"){x=Math.round((l.data("scrollInertia")+100)/40)}return x}}}if(l.data("autoScrollOnFocus")){if(!l.data("bindEvent_focusin")){i.bind("focusin",function(){i.scrollTop(0).scrollLeft(0);var x=c(document.activeElement);if(x.is("input,textarea,select,button,a[tabindex],area,object")){var J=q.position().top,y=x.position().top,I=i.height()-x.outerHeight();if(l.data("horizontalScroll")){J=q.position().left;y=x.position().left;I=i.width()-x.outerWidth()}if(J+y<0||J+y>I){l.mCustomScrollbar("scrollTo",y,{trigger:"internal"})}}});l.data({bindEvent_focusin:true})}}if(l.data("autoHideScrollbar")&&!l.data("alwaysShowScrollbar")){if(!l.data("bindEvent_autoHideScrollbar")){i.bind("mouseenter",function(x){i.addClass("mCS-mouse-over");d.showScrollbar.call(i.children(".mCSB_scrollTools"))}).bind("mouseleave touchend",function(x){i.removeClass("mCS-mouse-over");if(x.type==="mouseleave"){d.hideScrollbar.call(i.children(".mCSB_scrollTools"))}});l.data({bindEvent_autoHideScrollbar:true})}}},scrollTo:function(e,f){var i=c(this),o={moveDragger:false,trigger:"external",callbacks:true,scrollInertia:i.data("scrollInertia"),scrollEasing:i.data("scrollEasing")},f=c.extend(o,f),p,g=i.children(".mCustomScrollBox"),k=g.children(".mCSB_container"),r=g.children(".mCSB_scrollTools"),j=r.children(".mCSB_draggerContainer"),h=j.children(".mCSB_dragger"),t=draggerSpeed=f.scrollInertia,q,s,m,l;if(!k.hasClass("mCS_no_scrollbar")){i.data({mCS_trigger:f.trigger});if(i.data("mCS_Init")){f.callbacks=false}if(e||e===0){if(typeof(e)==="number"){if(f.moveDragger){p=e;if(i.data("horizontalScroll")){e=h.position().left*i.data("scrollAmount")}else{e=h.position().top*i.data("scrollAmount")}draggerSpeed=0}else{p=e/i.data("scrollAmount")}}else{if(typeof(e)==="string"){var v;if(e==="top"){v=0}else{if(e==="bottom"&&!i.data("horizontalScroll")){v=k.outerHeight()-g.height()}else{if(e==="left"){v=0}else{if(e==="right"&&i.data("horizontalScroll")){v=k.outerWidth()-g.width()}else{if(e==="first"){v=i.find(".mCSB_container").find(":first")}else{if(e==="last"){v=i.find(".mCSB_container").find(":last")}else{v=i.find(e)}}}}}}if(v.length===1){if(i.data("horizontalScroll")){e=v.position().left}else{e=v.position().top}p=e/i.data("scrollAmount")}else{p=e=v}}}if(i.data("horizontalScroll")){if(i.data("onTotalScrollBack_Offset")){s=-i.data("onTotalScrollBack_Offset")}if(i.data("onTotalScroll_Offset")){l=g.width()-k.outerWidth()+i.data("onTotalScroll_Offset")}if(p<0){p=e=0;clearInterval(i.data("mCSB_buttonScrollLeft"));if(!s){q=true}}else{if(p>=j.width()-h.width()){p=j.width()-h.width();e=g.width()-k.outerWidth();clearInterval(i.data("mCSB_buttonScrollRight"));if(!l){m=true}}else{e=-e}}var n=i.data("snapAmount");if(n){e=Math.round(e/n)*n-i.data("snapOffset")}d.mTweenAxis.call(this,h[0],"left",Math.round(p),draggerSpeed,f.scrollEasing);d.mTweenAxis.call(this,k[0],"left",Math.round(e),t,f.scrollEasing,{onStart:function(){if(f.callbacks&&!i.data("mCS_tweenRunning")){u("onScrollStart")}if(i.data("autoHideScrollbar")&&!i.data("alwaysShowScrollbar")){d.showScrollbar.call(r)}},onUpdate:function(){if(f.callbacks){u("whileScrolling")}},onComplete:function(){if(f.callbacks){u("onScroll");if(q||(s&&k.position().left>=s)){u("onTotalScrollBack")}if(m||(l&&k.position().left<=l)){u("onTotalScroll")}}h.data("preventAction",false);i.data("mCS_tweenRunning",false);if(i.data("autoHideScrollbar")&&!i.data("alwaysShowScrollbar")){if(!g.hasClass("mCS-mouse-over")){d.hideScrollbar.call(r)}}}})}else{if(i.data("onTotalScrollBack_Offset")){s=-i.data("onTotalScrollBack_Offset")}if(i.data("onTotalScroll_Offset")){l=g.height()-k.outerHeight()+i.data("onTotalScroll_Offset")}if(p<0){p=e=0;clearInterval(i.data("mCSB_buttonScrollUp"));if(!s){q=true}}else{if(p>=j.height()-h.height()){p=j.height()-h.height();e=g.height()-k.outerHeight();clearInterval(i.data("mCSB_buttonScrollDown"));if(!l){m=true}}else{e=-e}}var n=i.data("snapAmount");if(n){e=Math.round(e/n)*n-i.data("snapOffset")}d.mTweenAxis.call(this,h[0],"top",Math.round(p),draggerSpeed,f.scrollEasing);d.mTweenAxis.call(this,k[0],"top",Math.round(e),t,f.scrollEasing,{onStart:function(){if(f.callbacks&&!i.data("mCS_tweenRunning")){u("onScrollStart")}if(i.data("autoHideScrollbar")&&!i.data("alwaysShowScrollbar")){d.showScrollbar.call(r)}},onUpdate:function(){if(f.callbacks){u("whileScrolling")}},onComplete:function(){if(f.callbacks){u("onScroll");if(q||(s&&k.position().top>=s)){u("onTotalScrollBack")}if(m||(l&&k.position().top<=l)){u("onTotalScroll")}}h.data("preventAction",false);i.data("mCS_tweenRunning",false);if(i.data("autoHideScrollbar")&&!i.data("alwaysShowScrollbar")){if(!g.hasClass("mCS-mouse-over")){d.hideScrollbar.call(r)}}}})}if(i.data("mCS_Init")){i.data({mCS_Init:false})}}}function u(w){if(i.data("mCustomScrollbarIndex")){this.mcs={top:k.position().top,left:k.position().left,draggerTop:h.position().top,draggerLeft:h.position().left,topPct:Math.round((100*Math.abs(k.position().top))/Math.abs(k.outerHeight()-g.height())),leftPct:Math.round((100*Math.abs(k.position().left))/Math.abs(k.outerWidth()-g.width()))};switch(w){case"onScrollStart":i.data("mCS_tweenRunning",true).data("onScrollStart_Callback").call(i,this.mcs);break;case"whileScrolling":i.data("whileScrolling_Callback").call(i,this.mcs);break;case"onScroll":i.data("onScroll_Callback").call(i,this.mcs);break;case"onTotalScrollBack":i.data("onTotalScrollBack_Callback").call(i,this.mcs);break;case"onTotalScroll":i.data("onTotalScroll_Callback").call(i,this.mcs);break}}}},stop:function(){var g=c(this),e=g.children().children(".mCSB_container"),f=g.children().children().children().children(".mCSB_dragger");d.mTweenAxisStop.call(this,e[0]);d.mTweenAxisStop.call(this,f[0])},disable:function(e){var j=c(this),f=j.children(".mCustomScrollBox"),h=f.children(".mCSB_container"),g=f.children(".mCSB_scrollTools"),i=g.children().children(".mCSB_dragger");f.unbind("mousewheel focusin mouseenter mouseleave touchend");h.unbind("touchstart touchmove");if(e){if(j.data("horizontalScroll")){i.add(h).css("left",0)}else{i.add(h).css("top",0)}}g.css("display","none");h.addClass("mCS_no_scrollbar");j.data({bindEvent_mousewheel:false,bindEvent_focusin:false,bindEvent_content_touch:false,bindEvent_autoHideScrollbar:false}).addClass("mCS_disabled")},destroy:function(){var e=c(this);e.removeClass("mCustomScrollbar _mCS_"+e.data("mCustomScrollbarIndex")).addClass("mCS_destroyed").children().children(".mCSB_container").unwrap().children().unwrap().siblings(".mCSB_scrollTools").remove();c(document).unbind("mousemove."+e.data("mCustomScrollbarIndex")+" mouseup."+e.data("mCustomScrollbarIndex")+" MSPointerMove."+e.data("mCustomScrollbarIndex")+" MSPointerUp."+e.data("mCustomScrollbarIndex"));c(window).unbind("resize."+e.data("mCustomScrollbarIndex"))}},d={showScrollbar:function(){this.stop().animate({opacity:1},"fast")},hideScrollbar:function(){this.stop().animate({opacity:0},"fast")},mTweenAxis:function(g,i,h,f,o,y){var y=y||{},v=y.onStart||function(){},p=y.onUpdate||function(){},w=y.onComplete||function(){};var n=t(),l,j=0,r=g.offsetTop,s=g.style;if(i==="left"){r=g.offsetLeft}var m=h-r;q();e();function t(){if(window.performance&&window.performance.now){return window.performance.now()}else{if(window.performance&&window.performance.webkitNow){return window.performance.webkitNow()}else{if(Date.now){return Date.now()}else{return new Date().getTime()}}}}function x(){if(!j){v.call()}j=t()-n;u();if(j>=g._time){g._time=(j>g._time)?j+l-(j-g._time):j+l-1;if(g._time<j+1){g._time=j+1}}if(g._time<f){g._id=_request(x)}else{w.call()}}function u(){if(f>0){g.currVal=k(g._time,r,m,f,o);s[i]=Math.round(g.currVal)+"px"}else{s[i]=h+"px"}p.call()}function e(){l=1000/60;g._time=j+l;_request=(!window.requestAnimationFrame)?function(z){u();return setTimeout(z,0.01)}:window.requestAnimationFrame;g._id=_request(x)}function q(){if(g._id==null){return}if(!window.requestAnimationFrame){clearTimeout(g._id)}else{window.cancelAnimationFrame(g._id)}g._id=null}function k(B,A,F,E,C){switch(C){case"linear":return F*B/E+A;break;case"easeOutQuad":B/=E;return -F*B*(B-2)+A;break;case"easeInOutQuad":B/=E/2;if(B<1){return F/2*B*B+A}B--;return -F/2*(B*(B-2)-1)+A;break;case"easeOutCubic":B/=E;B--;return F*(B*B*B+1)+A;break;case"easeOutQuart":B/=E;B--;return -F*(B*B*B*B-1)+A;break;case"easeOutQuint":B/=E;B--;return F*(B*B*B*B*B+1)+A;break;case"easeOutCirc":B/=E;B--;return F*Math.sqrt(1-B*B)+A;break;case"easeOutSine":return F*Math.sin(B/E*(Math.PI/2))+A;break;case"easeOutExpo":return F*(-Math.pow(2,-10*B/E)+1)+A;break;case"mcsEaseOut":var D=(B/=E)*B,z=D*B;return A+F*(0.499999999999997*z*D+-2.5*D*D+5.5*z+-6.5*D+4*B);break;case"draggerRailEase":B/=E/2;if(B<1){return F/2*B*B*B+A}B-=2;return F/2*(B*B*B+2)+A;break}}},mTweenAxisStop:function(e){if(e._id==null){return}if(!window.requestAnimationFrame){clearTimeout(e._id)}else{window.cancelAnimationFrame(e._id)}e._id=null},rafPolyfill:function(){var f=["ms","moz","webkit","o"],e=f.length;while(--e>-1&&!window.requestAnimationFrame){window.requestAnimationFrame=window[f[e]+"RequestAnimationFrame"];window.cancelAnimationFrame=window[f[e]+"CancelAnimationFrame"]||window[f[e]+"CancelRequestAnimationFrame"]}}};d.rafPolyfill.call();c.support.touch=!!("ontouchstart" in window);c.support.pointer=window.navigator.pointerEnabled;c.support.msPointer=window.navigator.msPointerEnabled;var a=("https:"==document.location.protocol)?"https:":"http:";c.event.special.mousewheel||document.write('<script src="'+a+'//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.0.6/jquery.mousewheel.min.js"><\/script>');c.fn.mCustomScrollbar=function(e){if(b[e]){return b[e].apply(this,Array.prototype.slice.call(arguments,1))}else{if(typeof e==="object"||!e){return b.init.apply(this,arguments)}else{c.error("Method "+e+" does not exist")}}}})(jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-mCustomScrollbar.min.js
jquery-mCustomScrollbar.min.js
(function(a){typeof define=="function"&&define.amd?define(["jquery"],a):a(jQuery)})(function(a){"use strict";var b={},c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I=0;c=function(){return{common:{type:"line",lineColor:"#00f",fillColor:"#cdf",defaultPixelsPerValue:3,width:"auto",height:"auto",composite:!1,tagValuesAttribute:"values",tagOptionsPrefix:"spark",enableTagOptions:!1,enableHighlight:!0,highlightLighten:1.4,tooltipSkipNull:!0,tooltipPrefix:"",tooltipSuffix:"",disableHiddenCheck:!1,numberFormatter:!1,numberDigitGroupCount:3,numberDigitGroupSep:",",numberDecimalMark:".",disableTooltips:!1,disableInteraction:!1},line:{spotColor:"#f80",highlightSpotColor:"#5f5",highlightLineColor:"#f22",spotRadius:1.5,minSpotColor:"#f80",maxSpotColor:"#f80",lineWidth:1,normalRangeMin:undefined,normalRangeMax:undefined,normalRangeColor:"#ccc",drawNormalOnTop:!1,chartRangeMin:undefined,chartRangeMax:undefined,chartRangeMinX:undefined,chartRangeMaxX:undefined,tooltipFormat:new e('<span style="color: {{color}}">&#9679;</span> {{prefix}}{{y}}{{suffix}}')},bar:{barColor:"#3366cc",negBarColor:"#f44",stackedBarColor:["#3366cc","#dc3912","#ff9900","#109618","#66aa00","#dd4477","#0099c6","#990099"],zeroColor:undefined,nullColor:undefined,zeroAxis:!0,barWidth:4,barSpacing:1,chartRangeMax:undefined,chartRangeMin:undefined,chartRangeClip:!1,colorMap:undefined,tooltipFormat:new e('<span style="color: {{color}}">&#9679;</span> {{prefix}}{{value}}{{suffix}}')},tristate:{barWidth:4,barSpacing:1,posBarColor:"#6f6",negBarColor:"#f44",zeroBarColor:"#999",colorMap:{},tooltipFormat:new e('<span style="color: {{color}}">&#9679;</span> {{value:map}}'),tooltipValueLookups:{map:{"-1":"Loss",0:"Draw",1:"Win"}}},discrete:{lineHeight:"auto",thresholdColor:undefined,thresholdValue:0,chartRangeMax:undefined,chartRangeMin:undefined,chartRangeClip:!1,tooltipFormat:new e("{{prefix}}{{value}}{{suffix}}")},bullet:{targetColor:"#f33",targetWidth:3,performanceColor:"#33f",rangeColors:["#d3dafe","#a8b6ff","#7f94ff"],base:undefined,tooltipFormat:new e("{{fieldkey:fields}} - {{value}}"),tooltipValueLookups:{fields:{r:"Range",p:"Performance",t:"Target"}}},pie:{offset:0,sliceColors:["#3366cc","#dc3912","#ff9900","#109618","#66aa00","#dd4477","#0099c6","#990099"],borderWidth:0,borderColor:"#000",tooltipFormat:new e('<span style="color: {{color}}">&#9679;</span> {{value}} ({{percent.1}}%)')},box:{raw:!1,boxLineColor:"#000",boxFillColor:"#cdf",whiskerColor:"#000",outlierLineColor:"#333",outlierFillColor:"#fff",medianColor:"#f00",showOutliers:!0,outlierIQR:1.5,spotRadius:1.5,target:undefined,targetColor:"#4a2",chartRangeMax:undefined,chartRangeMin:undefined,tooltipFormat:new e("{{field:fields}}: {{value}}"),tooltipFormatFieldlistKey:"field",tooltipValueLookups:{fields:{lq:"Lower Quartile",med:"Median",uq:"Upper Quartile",lo:"Left Outlier",ro:"Right Outlier",lw:"Left Whisker",rw:"Right Whisker"}}}}},B='.jqstooltip { position: absolute;left: 0px;top: 0px;visibility: hidden;background: rgb(0, 0, 0) transparent;background-color: rgba(0,0,0,0.6);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";color: white;font: 10px arial, san serif;text-align: left;white-space: nowrap;padding: 5px;border: 1px solid white;z-index: 10000;}.jqsfield { color: white;font: 10px arial, san serif;text-align: left;}',d=function(){var b,c;return b=function(){this.init.apply(this,arguments)},arguments.length>1?(arguments[0]?(b.prototype=a.extend(new arguments[0],arguments[arguments.length-1]),b._super=arguments[0].prototype):b.prototype=arguments[arguments.length-1],arguments.length>2&&(c=Array.prototype.slice.call(arguments,1,-1),c.unshift(b.prototype),a.extend.apply(a,c))):b.prototype=arguments[0],b.prototype.cls=b,b},a.SPFormatClass=e=d({fre:/\{\{([\w.]+?)(:(.+?))?\}\}/g,precre:/(\w+)\.(\d+)/,init:function(a,b){this.format=a,this.fclass=b},render:function(a,b,c){var d=this,e=a,f,g,h,i,j;return this.format.replace(this.fre,function(){var a;return g=arguments[1],h=arguments[3],f=d.precre.exec(g),f?(j=f[2],g=f[1]):j=!1,i=e[g],i===undefined?"":h&&b&&b[h]?(a=b[h],a.get?b[h].get(i)||i:b[h][i]||i):(k(i)&&(c.get("numberFormatter")?i=c.get("numberFormatter")(i):i=p(i,j,c.get("numberDigitGroupCount"),c.get("numberDigitGroupSep"),c.get("numberDecimalMark"))),i)})}}),a.spformat=function(a,b){return new e(a,b)},f=function(a,b,c){return a<b?b:a>c?c:a},g=function(a,b){var c;return b===2?(c=Math.floor(a.length/2),a.length%2?a[c]:(a[c-1]+a[c])/2):a.length%2?(c=(a.length*b+b)/4,c%1?(a[Math.floor(c)]+a[Math.floor(c)-1])/2:a[c-1]):(c=(a.length*b+2)/4,c%1?(a[Math.floor(c)]+a[Math.floor(c)-1])/2:a[c-1])},h=function(a){var b;switch(a){case"undefined":a=undefined;break;case"null":a=null;break;case"true":a=!0;break;case"false":a=!1;break;default:b=parseFloat(a),a==b&&(a=b)}return a},i=function(a){var b,c=[];for(b=a.length;b--;)c[b]=h(a[b]);return c},j=function(a,b){var c,d,e=[];for(c=0,d=a.length;c<d;c++)a[c]!==b&&e.push(a[c]);return e},k=function(a){return!isNaN(parseFloat(a))&&isFinite(a)},p=function(b,c,d,e,f){var g,h;b=(c===!1?parseFloat(b).toString():b.toFixed(c)).split(""),g=(g=a.inArray(".",b))<0?b.length:g,g<b.length&&(b[g]=f);for(h=g-d;h>0;h-=d)b.splice(h,0,e);return b.join("")},l=function(a,b,c){var d;for(d=b.length;d--;){if(c&&b[d]===null)continue;if(b[d]!==a)return!1}return!0},m=function(a){var b=0,c;for(c=a.length;c--;)b+=typeof a[c]=="number"?a[c]:0;return b},o=function(b){return a.isArray(b)?b:[b]},n=function(a){var b;document.createStyleSheet?document.createStyleSheet().cssText=a:(b=document.createElement("style"),b.type="text/css",document.getElementsByTagName("head")[0].appendChild(b),b[typeof document.body.style.WebkitAppearance=="string"?"innerText":"innerHTML"]=a)},a.fn.simpledraw=function(b,c,d,e){var f,g;if(d&&(f=this.data("_jqs_vcanvas")))return f;b===undefined&&(b=a(this).innerWidth()),c===undefined&&(c=a(this).innerHeight());if(a.fn.sparkline.hasCanvas)f=new F(b,c,this,e);else{if(!a.fn.sparkline.hasVML)return!1;f=new G(b,c,this)}return g=a(this).data("_jqs_mhandler"),g&&g.registerCanvas(f),f},a.fn.cleardraw=function(){var a=this.data("_jqs_vcanvas");a&&a.reset()},a.RangeMapClass=q=d({init:function(a){var b,c,d=[];for(b in a)a.hasOwnProperty(b)&&typeof b=="string"&&b.indexOf(":")>-1&&(c=b.split(":"),c[0]=c[0].length===0?-Infinity:parseFloat(c[0]),c[1]=c[1].length===0?Infinity:parseFloat(c[1]),c[2]=a[b],d.push(c));this.map=a,this.rangelist=d||!1},get:function(a){var b=this.rangelist,c,d,e;if((e=this.map[a])!==undefined)return e;if(b)for(c=b.length;c--;){d=b[c];if(d[0]<=a&&d[1]>=a)return d[2]}return undefined}}),a.range_map=function(a){return new q(a)},r=d({init:function(b,c){var d=a(b);this.$el=d,this.options=c,this.currentPageX=0,this.currentPageY=0,this.el=b,this.splist=[],this.tooltip=null,this.over=!1,this.displayTooltips=!c.get("disableTooltips"),this.highlightEnabled=!c.get("disableHighlight")},registerSparkline:function(a){this.splist.push(a),this.over&&this.updateDisplay()},registerCanvas:function(b){var c=a(b.canvas);this.canvas=b,this.$canvas=c,c.mouseenter(a.proxy(this.mouseenter,this)),c.mouseleave(a.proxy(this.mouseleave,this)),c.click(a.proxy(this.mouseclick,this))},reset:function(a){this.splist=[],this.tooltip&&a&&(this.tooltip.remove(),this.tooltip=undefined)},mouseclick:function(b){var c=a.Event("sparklineClick");c.originalEvent=b,c.sparklines=this.splist,this.$el.trigger(c)},mouseenter:function(b){a(document.body).unbind("mousemove.jqs"),a(document.body).bind("mousemove.jqs",a.proxy(this.mousemove,this)),this.over=!0,this.currentPageX=b.pageX,this.currentPageY=b.pageY,this.currentEl=b.target,!this.tooltip&&this.displayTooltips&&(this.tooltip=new s(this.options),this.tooltip.updatePosition(b.pageX,b.pageY)),this.updateDisplay()},mouseleave:function(){a(document.body).unbind("mousemove.jqs");var b=this.splist,c=b.length,d=!1,e,f;this.over=!1,this.currentEl=null,this.tooltip&&(this.tooltip.remove(),this.tooltip=null);for(f=0;f<c;f++)e=b[f],e.clearRegionHighlight()&&(d=!0);d&&this.canvas.render()},mousemove:function(a){this.currentPageX=a.pageX,this.currentPageY=a.pageY,this.currentEl=a.target,this.tooltip&&this.tooltip.updatePosition(a.pageX,a.pageY),this.updateDisplay()},updateDisplay:function(){var b=this.splist,c=b.length,d=!1,e=this.$canvas.offset(),f=this.currentPageX-e.left,g=this.currentPageY-e.top,h,i,j,k,l;if(!this.over)return;for(j=0;j<c;j++)i=b[j],k=i.setRegionHighlight(this.currentEl,f,g),k&&(d=!0);if(d){l=a.Event("sparklineRegionChange"),l.sparklines=this.splist,this.$el.trigger(l);if(this.tooltip){h="";for(j=0;j<c;j++)i=b[j],h+=i.getCurrentRegionTooltip();this.tooltip.setContent(h)}this.disableHighlight||this.canvas.render()}k===null&&this.mouseleave()}}),s=d({sizeStyle:"position: static !important;display: block !important;visibility: hidden !important;float: left !important;",init:function(b){var c=b.get("tooltipClassname","jqstooltip"),d=this.sizeStyle,e;this.container=b.get("tooltipContainer")||document.body,this.tooltipOffsetX=b.get("tooltipOffsetX",10),this.tooltipOffsetY=b.get("tooltipOffsetY",12),a("#jqssizetip").remove(),a("#jqstooltip").remove(),this.sizetip=a("<div/>",{id:"jqssizetip",style:d,"class":c}),this.tooltip=a("<div/>",{id:"jqstooltip","class":c}).appendTo(this.container),e=this.tooltip.offset(),this.offsetLeft=e.left,this.offsetTop=e.top,this.hidden=!0,a(window).unbind("resize.jqs scroll.jqs"),a(window).bind("resize.jqs scroll.jqs",a.proxy(this.updateWindowDims,this)),this.updateWindowDims()},updateWindowDims:function(){this.scrollTop=a(window).scrollTop(),this.scrollLeft=a(window).scrollLeft(),this.scrollRight=this.scrollLeft+a(window).width(),this.updatePosition()},getSize:function(a){this.sizetip.html(a).appendTo(this.container),this.width=this.sizetip.width()+1,this.height=this.sizetip.height(),this.sizetip.remove()},setContent:function(a){if(!a){this.tooltip.css("visibility","hidden"),this.hidden=!0;return}this.getSize(a),this.tooltip.html(a).css({width:this.width,height:this.height,visibility:"visible"}),this.hidden&&(this.hidden=!1,this.updatePosition())},updatePosition:function(a,b){if(a===undefined){if(this.mousex===undefined)return;a=this.mousex-this.offsetLeft,b=this.mousey-this.offsetTop}else this.mousex=a-=this.offsetLeft,this.mousey=b-=this.offsetTop;if(!this.height||!this.width||this.hidden)return;b-=this.height+this.tooltipOffsetY,a+=this.tooltipOffsetX,b<this.scrollTop&&(b=this.scrollTop),a<this.scrollLeft?a=this.scrollLeft:a+this.width>this.scrollRight&&(a=this.scrollRight-this.width),this.tooltip.css({left:a,top:b})},remove:function(){this.tooltip.remove(),this.sizetip.remove(),this.sizetip=this.tooltip=undefined,a(window).unbind("resize.jqs scroll.jqs")}}),C=function(){n(B)},a(C),H=[],a.fn.sparkline=function(b,c){return this.each(function(){var d=new a.fn.sparkline.options(this,c),e=a(this),f,g;f=function(){var c,f,g,h,i,j,k;if(b==="html"||b===undefined){k=this.getAttribute(d.get("tagValuesAttribute"));if(k===undefined||k===null)k=e.html();c=k.replace(/(^\s*<!--)|(-->\s*$)|\s+/g,"").split(",")}else c=b;f=d.get("width")==="auto"?c.length*d.get("defaultPixelsPerValue"):d.get("width");if(d.get("height")==="auto"){if(!d.get("composite")||!a.data(this,"_jqs_vcanvas"))h=document.createElement("span"),h.innerHTML="a",e.html(h),g=a(h).innerHeight()||a(h).height(),a(h).remove(),h=null}else g=d.get("height");d.get("disableInteraction")?i=!1:(i=a.data(this,"_jqs_mhandler"),i?d.get("composite")||i.reset():(i=new r(this,d),a.data(this,"_jqs_mhandler",i)));if(d.get("composite")&&!a.data(this,"_jqs_vcanvas")){a.data(this,"_jqs_errnotify")||(alert("Attempted to attach a composite sparkline to an element with no existing sparkline"),a.data(this,"_jqs_errnotify",!0));return}j=new(a.fn.sparkline[d.get("type")])(this,c,d,f,g),j.render(),i&&i.registerSparkline(j)};if(a(this).html()&&!d.get("disableHiddenCheck")&&a(this).is(":hidden")||a.fn.jquery<"1.3.0"&&a(this).parents().is(":hidden")||!a(this).parents("body").length){if(!d.get("composite")&&a.data(this,"_jqs_pending"))for(g=H.length;g;g--)H[g-1][0]==this&&H.splice(g-1,1);H.push([this,f]),a.data(this,"_jqs_pending",!0)}else f.call(this)})},a.fn.sparkline.defaults=c(),a.sparkline_display_visible=function(){var b,c,d,e=[];for(c=0,d=H.length;c<d;c++)b=H[c][0],a(b).is(":visible")&&!a(b).parents().is(":hidden")?(H[c][1].call(b),a.data(H[c][0],"_jqs_pending",!1),e.push(c)):!a(b).closest("html").length&&!a.data(b,"_jqs_pending")&&(a.data(H[c][0],"_jqs_pending",!1),e.push(c));for(c=e.length;c;c--)H.splice(e[c-1],1)},a.fn.sparkline.options=d({init:function(c,d){var e,f,g,h;this.userOptions=d=d||{},this.tag=c,this.tagValCache={},f=a.fn.sparkline.defaults,g=f.common,this.tagOptionsPrefix=d.enableTagOptions&&(d.tagOptionsPrefix||g.tagOptionsPrefix),h=this.getTagSetting("type"),h===b?e=f[d.type||g.type]:e=f[h],this.mergedOptions=a.extend({},g,e,d)},getTagSetting:function(a){var c=this.tagOptionsPrefix,d,e,f,g;if(c===!1||c===undefined)return b;if(this.tagValCache.hasOwnProperty(a))d=this.tagValCache.key;else{d=this.tag.getAttribute(c+a);if(d===undefined||d===null)d=b;else if(d.substr(0,1)==="["){d=d.substr(1,d.length-2).split(",");for(e=d.length;e--;)d[e]=h(d[e].replace(/(^\s*)|(\s*$)/g,""))}else if(d.substr(0,1)==="{"){f=d.substr(1,d.length-2).split(","),d={};for(e=f.length;e--;)g=f[e].split(":",2),d[g[0].replace(/(^\s*)|(\s*$)/g,"")]=h(g[1].replace(/(^\s*)|(\s*$)/g,""))}else d=h(d);this.tagValCache.key=d}return d},get:function(a,c){var d=this.getTagSetting(a),e;return d!==b?d:(e=this.mergedOptions[a])===undefined?c:e}}),a.fn.sparkline._base=d({disabled:!1,init:function(b,c,d,e,f){this.el=b,this.$el=a(b),this.values=c,this.options=d,this.width=e,this.height=f,this.currentRegion=undefined},initTarget:function(){var a=!this.options.get("disableInteraction");(this.target=this.$el.simpledraw(this.width,this.height,this.options.get("composite"),a))?(this.canvasWidth=this.target.pixelWidth,this.canvasHeight=this.target.pixelHeight):this.disabled=!0},render:function(){return this.disabled?(this.el.innerHTML="",!1):!0},getRegion:function(a,b){},setRegionHighlight:function(a,b,c){var d=this.currentRegion,e=!this.options.get("disableHighlight"),f;return b>this.canvasWidth||c>this.canvasHeight||b<0||c<0?null:(f=this.getRegion(a,b,c),d!==f?(d!==undefined&&e&&this.removeHighlight(),this.currentRegion=f,f!==undefined&&e&&this.renderHighlight(),!0):!1)},clearRegionHighlight:function(){return this.currentRegion!==undefined?(this.removeHighlight(),this.currentRegion=undefined,!0):!1},renderHighlight:function(){this.changeHighlight(!0)},removeHighlight:function(){this.changeHighlight(!1)},changeHighlight:function(a){},getCurrentRegionTooltip:function(){var b=this.options,c="",d=[],f,g,h,i,j,k,l,m,n,o,p,q,r,s;if(this.currentRegion===undefined)return"";f=this.getCurrentRegionFields(),p=b.get("tooltipFormatter");if(p)return p(this,b,f);b.get("tooltipChartTitle")&&(c+='<div class="jqs jqstitle">'+b.get("tooltipChartTitle")+"</div>\n"),g=this.options.get("tooltipFormat");if(!g)return"";a.isArray(g)||(g=[g]),a.isArray(f)||(f=[f]),l=this.options.get("tooltipFormatFieldlist"),m=this.options.get("tooltipFormatFieldlistKey");if(l&&m){n=[];for(k=f.length;k--;)o=f[k][m],(s=a.inArray(o,l))!=-1&&(n[s]=f[k]);f=n}h=g.length,r=f.length;for(k=0;k<h;k++){q=g[k],typeof q=="string"&&(q=new e(q)),i=q.fclass||"jqsfield";for(s=0;s<r;s++)if(!f[s].isNull||!b.get("tooltipSkipNull"))a.extend(f[s],{prefix:b.get("tooltipPrefix"),suffix:b.get("tooltipSuffix")}),j=q.render(f[s],b.get("tooltipValueLookups"),b),d.push('<div class="'+i+'">'+j+"</div>")}return d.length?c+d.join("\n"):""},getCurrentRegionFields:function(){},calcHighlightColor:function(a,b){var c=b.get("highlightColor"),d=b.get("highlightLighten"),e,g,h,i;if(c)return c;if(d){e=/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(a)||/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(a);if(e){h=[],g=a.length===4?16:1;for(i=0;i<3;i++)h[i]=f(Math.round(parseInt(e[i+1],16)*g*d),0,255);return"rgb("+h.join(",")+")"}}return a}}),t={changeHighlight:function(b){var c=this.currentRegion,d=this.target,e=this.regionShapes[c],f;e&&(f=this.renderRegion(c,b),a.isArray(f)||a.isArray(e)?(d.replaceWithShapes(e,f),this.regionShapes[c]=a.map(f,function(a){return a.id})):(d.replaceWithShape(e,f),this.regionShapes[c]=f.id))},render:function(){var b=this.values,c=this.target,d=this.regionShapes,e,f,g,h;if(!this.cls._super.render.call(this))return;for(g=b.length;g--;){e=this.renderRegion(g);if(e)if(a.isArray(e)){f=[];for(h=e.length;h--;)e[h].append(),f.push(e[h].id);d[g]=f}else e.append(),d[g]=e.id;else d[g]=null}c.render()}},a.fn.sparkline.line=u=d(a.fn.sparkline._base,{type:"line",init:function(a,b,c,d,e){u._super.init.call(this,a,b,c,d,e),this.vertices=[],this.regionMap=[],this.xvalues=[],this.yvalues=[],this.yminmax=[],this.hightlightSpotId=null,this.lastShapeId=null,this.initTarget()},getRegion:function(a,b,c){var d,e=this.regionMap;for(d=e.length;d--;)if(e[d]!==null&&b>=e[d][0]&&b<=e[d][1])return e[d][2];return undefined},getCurrentRegionFields:function(){var a=this.currentRegion;return{isNull:this.yvalues[a]===null,x:this.xvalues[a],y:this.yvalues[a],color:this.options.get("lineColor"),fillColor:this.options.get("fillColor"),offset:a}},renderHighlight:function(){var a=this.currentRegion,b=this.target,c=this.vertices[a],d=this.options,e=d.get("spotRadius"),f=d.get("highlightSpotColor"),g=d.get("highlightLineColor"),h,i;if(!c)return;e&&f&&(h=b.drawCircle(c[0],c[1],e,undefined,f),this.highlightSpotId=h.id,b.insertAfterShape(this.lastShapeId,h)),g&&(i=b.drawLine(c[0],this.canvasTop,c[0],this.canvasTop+this.canvasHeight,g),this.highlightLineId=i.id,b.insertAfterShape(this.lastShapeId,i))},removeHighlight:function(){var a=this.target;this.highlightSpotId&&(a.removeShapeId(this.highlightSpotId),this.highlightSpotId=null),this.highlightLineId&&(a.removeShapeId(this.highlightLineId),this.highlightLineId=null)},scanValues:function(){var a=this.values,b=a.length,c=this.xvalues,d=this.yvalues,e=this.yminmax,f,g,h,i,j;for(f=0;f<b;f++)g=a[f],h=typeof a[f]=="string",i=typeof a[f]=="object"&&a[f]instanceof Array,j=h&&a[f].split(":"),h&&j.length===2?(c.push(Number(j[0])),d.push(Number(j[1])),e.push(Number(j[1]))):i?(c.push(g[0]),d.push(g[1]),e.push(g[1])):(c.push(f),a[f]===null||a[f]==="null"?d.push(null):(d.push(Number(g)),e.push(Number(g))));this.options.get("xvalues")&&(c=this.options.get("xvalues")),this.maxy=this.maxyorg=Math.max.apply(Math,e),this.miny=this.minyorg=Math.min.apply(Math,e),this.maxx=Math.max.apply(Math,c),this.minx=Math.min.apply(Math,c),this.xvalues=c,this.yvalues=d,this.yminmax=e},processRangeOptions:function(){var a=this.options,b=a.get("normalRangeMin"),c=a.get("normalRangeMax");b!==undefined&&(b<this.miny&&(this.miny=b),c>this.maxy&&(this.maxy=c)),a.get("chartRangeMin")!==undefined&&(a.get("chartRangeClip")||a.get("chartRangeMin")<this.miny)&&(this.miny=a.get("chartRangeMin")),a.get("chartRangeMax")!==undefined&&(a.get("chartRangeClip")||a.get("chartRangeMax")>this.maxy)&&(this.maxy=a.get("chartRangeMax")),a.get("chartRangeMinX")!==undefined&&(a.get("chartRangeClipX")||a.get("chartRangeMinX")<this.minx)&&(this.minx=a.get("chartRangeMinX")),a.get("chartRangeMaxX")!==undefined&&(a.get("chartRangeClipX")||a.get("chartRangeMaxX")>this.maxx)&&(this.maxx=a.get("chartRangeMaxX"))},drawNormalRange:function(a,b,c,d,e){var f=this.options.get("normalRangeMin"),g=this.options.get("normalRangeMax"),h=b+Math.round(c-c*((g-this.miny)/e)),i=Math.round(c*(g-f)/e);this.target.drawRect(a,h,d,i,undefined,this.options.get("normalRangeColor")).append()},render:function(){var b=this.options,c=this.target,d=this.canvasWidth,e=this.canvasHeight,f=this.vertices,g=b.get("spotRadius"),h=this.regionMap,i,j,k,l,m,n,o,p,r,s,t,v,w,x,y,z,A,B,C,D,E,F,G,H,I;if(!u._super.render.call(this))return;this.scanValues(),this.processRangeOptions(),G=this.xvalues,H=this.yvalues;if(!this.yminmax.length||this.yvalues.length<2)return;l=m=0,i=this.maxx-this.minx===0?1:this.maxx-this.minx,j=this.maxy-this.miny===0?1:this.maxy-this.miny,k=this.yvalues.length-1,g&&(d<g*4||e<g*4)&&(g=0);if(g){E=b.get("highlightSpotColor")&&!b.get("disableInteraction");if(E||b.get("minSpotColor")||b.get("spotColor")&&H[k]===this.miny)e-=Math.ceil(g);if(E||b.get("maxSpotColor")||b.get("spotColor")&&H[k]===this.maxy)e-=Math.ceil(g),l+=Math.ceil(g);if(E||(b.get("minSpotColor")||b.get("maxSpotColor"))&&(H[0]===this.miny||H[0]===this.maxy))m+=Math.ceil(g),d-=Math.ceil(g);if(E||b.get("spotColor")||b.get("minSpotColor")||b.get("maxSpotColor")&&(H[k]===this.miny||H[k]===this.maxy))d-=Math.ceil(g)}e--,b.get("normalRangeMin")!==undefined&&!b.get("drawNormalOnTop")&&this.drawNormalRange(m,l,e,d,j),o=[],p=[o],x=y=null,z=H.length;for(I=0;I<z;I++)r=G[I],t=G[I+1],s=H[I],v=m+Math.round((r-this.minx)*(d/i)),w=I<z-1?m+Math.round((t-this.minx)*(d/i)):d,y=v+(w-v)/2,h[I]=[x||0,y,I],x=y,s===null?I&&(H[I-1]!==null&&(o=[],p.push(o)),f.push(null)):(s<this.miny&&(s=this.miny),s>this.maxy&&(s=this.maxy),o.length||o.push([v,l+e]),n=[v,l+Math.round(e-e*((s-this.miny)/j))],o.push(n),f.push(n));A=[],B=[],C=p.length;for(I=0;I<C;I++)o=p[I],o.length&&(b.get("fillColor")&&(o.push([o[o.length-1][0],l+e]),B.push(o.slice(0)),o.pop()),o.length>2&&(o[0]=[o[0][0],o[1][1]]),A.push(o));C=B.length;for(I=0;I<C;I++)c.drawShape(B[I],b.get("fillColor"),b.get("fillColor")).append();b.get("normalRangeMin")!==undefined&&b.get("drawNormalOnTop")&&this.drawNormalRange(m,l,e,d,j),C=A.length;for(I=0;I<C;I++)c.drawShape(A[I],b.get("lineColor"),undefined,b.get("lineWidth")).append();if(g&&b.get("valueSpots")){D=b.get("valueSpots"),D.get===undefined&&(D=new q(D));for(I=0;I<z;I++)F=D.get(H[I]),F&&c.drawCircle(m+Math.round((G[I]-this.minx)*(d/i)),l+Math.round(e-e*((H[I]-this.miny)/j)),g,undefined,F).append()}g&&b.get("spotColor")&&H[k]!==null&&c.drawCircle(m+Math.round((G[G.length-1]-this.minx)*(d/i)),l+Math.round(e-e*((H[k]-this.miny)/j)),g,undefined,b.get("spotColor")).append(),this.maxy!==this.minyorg&&(g&&b.get("minSpotColor")&&(r=G[a.inArray(this.minyorg,H)],c.drawCircle(m+Math.round((r-this.minx)*(d/i)),l+Math.round(e-e*((this.minyorg-this.miny)/j)),g,undefined,b.get("minSpotColor")).append()),g&&b.get("maxSpotColor")&&(r=G[a.inArray(this.maxyorg,H)],c.drawCircle(m+Math.round((r-this.minx)*(d/i)),l+Math.round(e-e*((this.maxyorg-this.miny)/j)),g,undefined,b.get("maxSpotColor")).append())),this.lastShapeId=c.getLastShapeId(),this.canvasTop=l,c.render()}}),a.fn.sparkline.bar=v=d(a.fn.sparkline._base,t,{type:"bar",init:function(b,c,d,e,g){var k=parseInt(d.get("barWidth"),10),l=parseInt(d.get("barSpacing"),10),m=d.get("chartRangeMin"),n=d.get("chartRangeMax"),o=d.get("chartRangeClip"),p=Infinity,r=-Infinity,s,t,u,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P;v._super.init.call(this,b,c,d,e,g);for(y=0,z=c.length;y<z;y++){M=c[y],s=typeof M=="string"&&M.indexOf(":")>-1;if(s||a.isArray(M))H=!0,s&&(M=c[y]=i(M.split(":"))),M=j(M,null),t=Math.min.apply(Math,M),u=Math.max.apply(Math,M),t<p&&(p=t),u>r&&(r=u)}this.stacked=H,this.regionShapes={},this.barWidth=k,this.barSpacing=l,this.totalBarWidth=k+l,this.width=e=c.length*k+(c.length-1)*l,this.initTarget(),o&&(F=m===undefined?-Infinity:m,G=n===undefined?Infinity:n),x=[],w=H?[]:x;var Q=[],R=[];for(y=0,z=c.length;y<z;y++)if(H){I=c[y],c[y]=L=[],Q[y]=0,w[y]=R[y]=0;for(J=0,K=I.length;J<K;J++)M=L[J]=o?f(I[J],F,G):I[J],M!==null&&(M>0&&(Q[y]+=M),p<0&&r>0?M<0?R[y]+=Math.abs(M):w[y]+=M:w[y]+=Math.abs(M-(M<0?r:p)),x.push(M))}else M=o?f(c[y],F,G):c[y],M=c[y]=h(M),M!==null&&x.push(M);this.max=E=Math.max.apply(Math,x),this.min=D=Math.min.apply(Math,x),this.stackMax=r=H?Math.max.apply(Math,Q):E,this.stackMin=p=H?Math.min.apply(Math,x):D,d.get("chartRangeMin")!==undefined&&(d.get("chartRangeClip")||d.get("chartRangeMin")<D)&&(D=d.get("chartRangeMin")),d.get("chartRangeMax")!==undefined&&(d.get("chartRangeClip")||d.get("chartRangeMax")>E)&&(E=d.get("chartRangeMax")),this.zeroAxis=B=d.get("zeroAxis",!0),D<=0&&E>=0&&B?C=0:B==0?C=D:D>0?C=D:C=E,this.xaxisOffset=C,A=H?Math.max.apply(Math,w)+Math.max.apply(Math,R):E-D,this.canvasHeightEf=B&&D<0?this.canvasHeight-2:this.canvasHeight-1,D<C?(O=H&&E>=0?r:E,N=(O-C)/A*this.canvasHeight,N!==Math.ceil(N)&&(this.canvasHeightEf-=2,N=Math.ceil(N))):N=this.canvasHeight,this.yoffset=N,a.isArray(d.get("colorMap"))?(this.colorMapByIndex=d.get("colorMap"),this.colorMapByValue=null):(this.colorMapByIndex=null,this.colorMapByValue=d.get("colorMap"),this.colorMapByValue&&this.colorMapByValue.get===undefined&&(this.colorMapByValue=new q(this.colorMapByValue))),this.range=A},getRegion:function(a,b,c){var d=Math.floor(b/this.totalBarWidth);return d<0||d>=this.values.length?undefined:d},getCurrentRegionFields:function(){var a=this.currentRegion,b=o(this.values[a]),c=[],d,e;for(e=b.length;e--;)d=b[e],c.push({isNull:d===null,value:d,color:this.calcColor(e,d,a),offset:a});return c},calcColor:function(b,c,d){var e=this.colorMapByIndex,f=this.colorMapByValue,g=this.options,h,i;return this.stacked?h=g.get("stackedBarColor"):h=c<0?g.get("negBarColor"):g.get("barColor"),c===0&&g.get("zeroColor")!==undefined&&(h=g.get("zeroColor")),f&&(i=f.get(c))?h=i:e&&e.length>d&&(h=e[d]),a.isArray(h)?h[b%h.length]:h},renderRegion:function(b,c){var d=this.values[b],e=this.options,f=this.xaxisOffset,g=[],h=this.range,i=this.stacked,j=this.target,k=b*this.totalBarWidth,m=this.canvasHeightEf,n=this.yoffset,o,p,q,r,s,t,u,v,w,x;d=a.isArray(d)?d:[d],u=d.length,v=d[0],r=l(null,d),x=l(f,d,!0);if(r)return e.get("nullColor")?(q=c?e.get("nullColor"):this.calcHighlightColor(e.get("nullColor"),e),o=n>0?n-1:n,j.drawRect(k,o,this.barWidth-1,0,q,q)):undefined;s=n;for(t=0;t<u;t++){v=d[t];if(i&&v===f){if(!x||w)continue;w=!0}h>0?p=Math.floor(m*(Math.abs(v-f)/h))+1:p=1,v<f||v===f&&n===0?(o=s,s+=p):(o=n-p,n-=p),q=this.calcColor(t,v,b),c&&(q=this.calcHighlightColor(q,e)),g.push(j.drawRect(k,o,this.barWidth-1,p-1,q,q))}return g.length===1?g[0]:g}}),a.fn.sparkline.tristate=w=d(a.fn.sparkline._base,t,{type:"tristate",init:function(b,c,d,e,f){var g=parseInt(d.get("barWidth"),10),h=parseInt(d.get("barSpacing"),10);w._super.init.call(this,b,c,d,e,f),this.regionShapes={},this.barWidth=g,this.barSpacing=h,this.totalBarWidth=g+h,this.values=a.map(c,Number),this.width=e=c.length*g+(c.length-1)*h,a.isArray(d.get("colorMap"))?(this.colorMapByIndex=d.get("colorMap"),this.colorMapByValue=null):(this.colorMapByIndex=null,this.colorMapByValue=d.get("colorMap"),this.colorMapByValue&&this.colorMapByValue.get===undefined&&(this.colorMapByValue=new q(this.colorMapByValue))),this.initTarget()},getRegion:function(a,b,c){return Math.floor(b/this.totalBarWidth)},getCurrentRegionFields:function(){var a=this.currentRegion;return{isNull:this.values[a]===undefined,value:this.values[a],color:this.calcColor(this.values[a],a),offset:a}},calcColor:function(a,b){var c=this.values,d=this.options,e=this.colorMapByIndex,f=this.colorMapByValue,g,h;return f&&(h=f.get(a))?g=h:e&&e.length>b?g=e[b]:c[b]<0?g=d.get("negBarColor"):c[b]>0?g=d.get("posBarColor"):g=d.get("zeroBarColor"),g},renderRegion:function(a,b){var c=this.values,d=this.options,e=this.target,f,g,h,i,j,k;f=e.pixelHeight,h=Math.round(f/2),i=a*this.totalBarWidth,c[a]<0?(j=h,g=h-1):c[a]>0?(j=0,g=h-1):(j=h-1,g=2),k=this.calcColor(c[a],a);if(k===null)return;return b&&(k=this.calcHighlightColor(k,d)),e.drawRect(i,j,this.barWidth-1,g-1,k,k)}}),a.fn.sparkline.discrete=x=d(a.fn.sparkline._base,t,{type:"discrete",init:function(b,c,d,e,f){x._super.init.call(this,b,c,d,e,f),this.regionShapes={},this.values=c=a.map(c,Number),this.min=Math.min.apply(Math,c),this.max=Math.max.apply(Math,c),this.range=this.max-this.min,this.width=e=d.get("width")==="auto"?c.length*2:this.width,this.interval=Math.floor(e/c.length),this.itemWidth=e/c.length,d.get("chartRangeMin")!==undefined&&(d.get("chartRangeClip")||d.get("chartRangeMin")<this.min)&&(this.min=d.get("chartRangeMin")),d.get("chartRangeMax")!==undefined&&(d.get("chartRangeClip")||d.get("chartRangeMax")>this.max)&&(this.max=d.get("chartRangeMax")),this.initTarget(),this.target&&(this.lineHeight=d.get("lineHeight")==="auto"?Math.round(this.canvasHeight*.3):d.get("lineHeight"))},getRegion:function(a,b,c){return Math.floor(b/this.itemWidth)},getCurrentRegionFields:function(){var a=this.currentRegion;return{isNull:this.values[a]===undefined,value:this.values[a],offset:a}},renderRegion:function(a,b){var c=this.values,d=this.options,e=this.min,g=this.max,h=this.range,i=this.interval,j=this.target,k=this.canvasHeight,l=this.lineHeight,m=k-l,n,o,p,q;return o=f(c[a],e,g),q=a*i,n=Math.round(m-m*((o-e)/h)),p=d.get("thresholdColor")&&o<d.get("thresholdValue")?d.get("thresholdColor"):d.get("lineColor"),b&&(p=this.calcHighlightColor(p,d)),j.drawLine(q,n,q,n+l,p)}}),a.fn.sparkline.bullet=y=d(a.fn.sparkline._base,{type:"bullet",init:function(a,b,c,d,e){var f,g,h;y._super.init.call(this,a,b,c,d,e),this.values=b=i(b),h=b.slice(),h[0]=h[0]===null?h[2]:h[0],h[1]=b[1]===null?h[2]:h[1],f=Math.min.apply(Math,b),g=Math.max.apply(Math,b),c.get("base")===undefined?f=f<0?f:0:f=c.get("base"),this.min=f,this.max=g,this.range=g-f,this.shapes={},this.valueShapes={},this.regiondata={},this.width=d=c.get("width")==="auto"?"4.0em":d,this.target=this.$el.simpledraw(d,e,c.get("composite")),b.length||(this.disabled=!0),this.initTarget()},getRegion:function(a,b,c){var d=this.target.getShapeAt(a,b,c);return d!==undefined&&this.shapes[d]!==undefined?this.shapes[d]:undefined},getCurrentRegionFields:function(){var a=this.currentRegion;return{fieldkey:a.substr(0,1),value:this.values[a.substr(1)],region:a}},changeHighlight:function(a){var b=this.currentRegion,c=this.valueShapes[b],d;delete this.shapes[c];switch(b.substr(0,1)){case"r":d=this.renderRange(b.substr(1),a);break;case"p":d=this.renderPerformance(a);break;case"t":d=this.renderTarget(a)}this.valueShapes[b]=d.id,this.shapes[d.id]=b,this.target.replaceWithShape(c,d)},renderRange:function(a,b){var c=this.values[a],d=Math.round(this.canvasWidth*((c-this.min)/this.range)),e=this.options.get("rangeColors")[a-2];return b&&(e=this.calcHighlightColor(e,this.options)),this.target.drawRect(0,0,d-1,this.canvasHeight-1,e,e)},renderPerformance:function(a){var b=this.values[1],c=Math.round(this.canvasWidth*((b-this.min)/this.range)),d=this.options.get("performanceColor");return a&&(d=this.calcHighlightColor(d,this.options)),this.target.drawRect(0,Math.round(this.canvasHeight*.3),c-1,Math.round(this.canvasHeight*.4)-1,d,d)},renderTarget:function(a){var b=this.values[0],c=Math.round(this.canvasWidth*((b-this.min)/this.range)-this.options.get("targetWidth")/2),d=Math.round(this.canvasHeight*.1),e=this.canvasHeight-d*2,f=this.options.get("targetColor");return a&&(f=this.calcHighlightColor(f,this.options)),this.target.drawRect(c,d,this.options.get("targetWidth")-1,e-1,f,f)},render:function(){var a=this.values.length,b=this.target,c,d;if(!y._super.render.call(this))return;for(c=2;c<a;c++)d=this.renderRange(c).append(),this.shapes[d.id]="r"+c,this.valueShapes["r"+c]=d.id;this.values[1]!==null&&(d=this.renderPerformance().append(),this.shapes[d.id]="p1",this.valueShapes.p1=d.id),this.values[0]!==null&&(d=this.renderTarget().append(),this.shapes[d.id]="t0",this.valueShapes.t0=d.id),b.render()}}),a.fn.sparkline.pie=z=d(a.fn.sparkline._base,{type:"pie",init:function(b,c,d,e,f){var g=0,h;z._super.init.call(this,b,c,d,e,f),this.shapes={},this.valueShapes={},this.values=c=a.map(c,Number),d.get("width")==="auto"&&(this.width=this.height);if(c.length>0)for(h=c.length;h--;)g+=c[h];this.total=g,this.initTarget(),this.radius=Math.floor(Math.min(this.canvasWidth,this.canvasHeight)/2)},getRegion:function(a,b,c){var d=this.target.getShapeAt(a,b,c);return d!==undefined&&this.shapes[d]!==undefined?this.shapes[d]:undefined},getCurrentRegionFields:function(){var a=this.currentRegion;return{isNull:this.values[a]===undefined,value:this.values[a],percent:this.values[a]/this.total*100,color:this.options.get("sliceColors")[a%this.options.get("sliceColors").length],offset:a}},changeHighlight:function(a){var b=this.currentRegion,c=this.renderSlice(b,a),d=this.valueShapes[b];delete this.shapes[d],this.target.replaceWithShape(d,c),this.valueShapes[b]=c.id,this.shapes[c.id]=b},renderSlice:function(a,b){var c=this.target,d=this.options,e=this.radius,f=d.get("borderWidth"),g=d.get("offset"),h=2*Math.PI,i=this.values,j=this.total,k=g?2*Math.PI*(g/360):0,l,m,n,o,p;o=i.length;for(n=0;n<o;n++){l=k,m=k,j>0&&(m=k+h*(i[n]/j));if(a===n)return p=d.get("sliceColors")[n%d.get("sliceColors").length],b&&(p=this.calcHighlightColor(p,d)),c.drawPieSlice(e,e,e-f,l,m,undefined,p);k=m}},render:function(){var a=this.target,b=this.values,c=this.options,d=this.radius,e=c.get("borderWidth"),f,g;if(!z._super. render.call(this))return;e&&a.drawCircle(d,d,Math.floor(d-e/2),c.get("borderColor"),undefined,e).append();for(g=b.length;g--;)b[g]&&(f=this.renderSlice(g).append(),this.valueShapes[g]=f.id,this.shapes[f.id]=g);a.render()}}),a.fn.sparkline.box=A=d(a.fn.sparkline._base,{type:"box",init:function(b,c,d,e,f){A._super.init.call(this,b,c,d,e,f),this.values=a.map(c,Number),this.width=d.get("width")==="auto"?"4.0em":e,this.initTarget(),this.values.length||(this.disabled=1)},getRegion:function(){return 1},getCurrentRegionFields:function(){var a=[{field:"lq",value:this.quartiles[0]},{field:"med",value:this.quartiles[1]},{field:"uq",value:this.quartiles[2]}];return this.loutlier!==undefined&&a.push({field:"lo",value:this.loutlier}),this.routlier!==undefined&&a.push({field:"ro",value:this.routlier}),this.lwhisker!==undefined&&a.push({field:"lw",value:this.lwhisker}),this.rwhisker!==undefined&&a.push({field:"rw",value:this.rwhisker}),a},render:function(){var a=this.target,b=this.values,c=b.length,d=this.options,e=this.canvasWidth,f=this.canvasHeight,h=d.get("chartRangeMin")===undefined?Math.min.apply(Math,b):d.get("chartRangeMin"),i=d.get("chartRangeMax")===undefined?Math.max.apply(Math,b):d.get("chartRangeMax"),j=0,k,l,m,n,o,p,q,r,s,t,u;if(!A._super.render.call(this))return;if(d.get("raw"))d.get("showOutliers")&&b.length>5?(l=b[0],k=b[1],n=b[2],o=b[3],p=b[4],q=b[5],r=b[6]):(k=b[0],n=b[1],o=b[2],p=b[3],q=b[4]);else{b.sort(function(a,b){return a-b}),n=g(b,1),o=g(b,2),p=g(b,3),m=p-n;if(d.get("showOutliers")){k=q=undefined;for(s=0;s<c;s++)k===undefined&&b[s]>n-m*d.get("outlierIQR")&&(k=b[s]),b[s]<p+m*d.get("outlierIQR")&&(q=b[s]);l=b[0],r=b[c-1]}else k=b[0],q=b[c-1]}this.quartiles=[n,o,p],this.lwhisker=k,this.rwhisker=q,this.loutlier=l,this.routlier=r,u=e/(i-h+1),d.get("showOutliers")&&(j=Math.ceil(d.get("spotRadius")),e-=2*Math.ceil(d.get("spotRadius")),u=e/(i-h+1),l<k&&a.drawCircle((l-h)*u+j,f/2,d.get("spotRadius"),d.get("outlierLineColor"),d.get("outlierFillColor")).append(),r>q&&a.drawCircle((r-h)*u+j,f/2,d.get("spotRadius"),d.get("outlierLineColor"),d.get("outlierFillColor")).append()),a.drawRect(Math.round((n-h)*u+j),Math.round(f*.1),Math.round((p-n)*u),Math.round(f*.8),d.get("boxLineColor"),d.get("boxFillColor")).append(),a.drawLine(Math.round((k-h)*u+j),Math.round(f/2),Math.round((n-h)*u+j),Math.round(f/2),d.get("lineColor")).append(),a.drawLine(Math.round((k-h)*u+j),Math.round(f/4),Math.round((k-h)*u+j),Math.round(f-f/4),d.get("whiskerColor")).append(),a.drawLine(Math.round((q-h)*u+j),Math.round(f/2),Math.round((p-h)*u+j),Math.round(f/2),d.get("lineColor")).append(),a.drawLine(Math.round((q-h)*u+j),Math.round(f/4),Math.round((q-h)*u+j),Math.round(f-f/4),d.get("whiskerColor")).append(),a.drawLine(Math.round((o-h)*u+j),Math.round(f*.1),Math.round((o-h)*u+j),Math.round(f*.9),d.get("medianColor")).append(),d.get("target")&&(t=Math.ceil(d.get("spotRadius")),a.drawLine(Math.round((d.get("target")-h)*u+j),Math.round(f/2-t),Math.round((d.get("target")-h)*u+j),Math.round(f/2+t),d.get("targetColor")).append(),a.drawLine(Math.round((d.get("target")-h)*u+j-t),Math.round(f/2),Math.round((d.get("target")-h)*u+j+t),Math.round(f/2),d.get("targetColor")).append()),a.render()}}),function(){document.namespaces&&!document.namespaces.v?(a.fn.sparkline.hasVML=!0,document.namespaces.add("v","urn:schemas-microsoft-com:vml","#default#VML")):a.fn.sparkline.hasVML=!1;var b=document.createElement("canvas");a.fn.sparkline.hasCanvas=!!b.getContext&&!!b.getContext("2d")}(),D=d({init:function(a,b,c,d){this.target=a,this.id=b,this.type=c,this.args=d},append:function(){return this.target.appendShape(this),this}}),E=d({_pxregex:/(\d+)(px)?\s*$/i,init:function(b,c,d){if(!b)return;this.width=b,this.height=c,this.target=d,this.lastShapeId=null,d[0]&&(d=d[0]),a.data(d,"_jqs_vcanvas",this)},drawLine:function(a,b,c,d,e,f){return this.drawShape([[a,b],[c,d]],e,f)},drawShape:function(a,b,c,d){return this._genShape("Shape",[a,b,c,d])},drawCircle:function(a,b,c,d,e,f){return this._genShape("Circle",[a,b,c,d,e,f])},drawPieSlice:function(a,b,c,d,e,f,g){return this._genShape("PieSlice",[a,b,c,d,e,f,g])},drawRect:function(a,b,c,d,e,f){return this._genShape("Rect",[a,b,c,d,e,f])},getElement:function(){return this.canvas},getLastShapeId:function(){return this.lastShapeId},reset:function(){alert("reset not implemented")},_insert:function(b,c){a(c).html(b)},_calculatePixelDims:function(b,c,d){var e;e=this._pxregex.exec(c),e?this.pixelHeight=e[1]:this.pixelHeight=a(d).height(),e=this._pxregex.exec(b),e?this.pixelWidth=e[1]:this.pixelWidth=a(d).width()},_genShape:function(a,b){var c=I++;return b.unshift(c),new D(this,c,a,b)},appendShape:function(a){alert("appendShape not implemented")},replaceWithShape:function(a,b){alert("replaceWithShape not implemented")},insertAfterShape:function(a,b){alert("insertAfterShape not implemented")},removeShapeId:function(a){alert("removeShapeId not implemented")},getShapeAt:function(a,b,c){alert("getShapeAt not implemented")},render:function(){alert("render not implemented")}}),F=d(E,{init:function(b,c,d,e){F._super.init.call(this,b,c,d),this.canvas=document.createElement("canvas"),d[0]&&(d=d[0]),a.data(d,"_jqs_vcanvas",this),a(this.canvas).css({display:"inline-block",width:b,height:c,verticalAlign:"top"}),this._insert(this.canvas,d),this._calculatePixelDims(b,c,this.canvas),this.canvas.width=this.pixelWidth,this.canvas.height=this.pixelHeight,this.interact=e,this.shapes={},this.shapeseq=[],this.currentTargetShapeId=undefined,a(this.canvas).css({width:this.pixelWidth,height:this.pixelHeight})},_getContext:function(a,b,c){var d=this.canvas.getContext("2d");return a!==undefined&&(d.strokeStyle=a),d.lineWidth=c===undefined?1:c,b!==undefined&&(d.fillStyle=b),d},reset:function(){var a=this._getContext();a.clearRect(0,0,this.pixelWidth,this.pixelHeight),this.shapes={},this.shapeseq=[],this.currentTargetShapeId=undefined},_drawShape:function(a,b,c,d,e){var f=this._getContext(c,d,e),g,h;f.beginPath(),f.moveTo(b[0][0]+.5,b[0][1]+.5);for(g=1,h=b.length;g<h;g++)f.lineTo(b[g][0]+.5,b[g][1]+.5);c!==undefined&&f.stroke(),d!==undefined&&f.fill(),this.targetX!==undefined&&this.targetY!==undefined&&f.isPointInPath(this.targetX,this.targetY)&&(this.currentTargetShapeId=a)},_drawCircle:function(a,b,c,d,e,f,g){var h=this._getContext(e,f,g);h.beginPath(),h.arc(b,c,d,0,2*Math.PI,!1),this.targetX!==undefined&&this.targetY!==undefined&&h.isPointInPath(this.targetX,this.targetY)&&(this.currentTargetShapeId=a),e!==undefined&&h.stroke(),f!==undefined&&h.fill()},_drawPieSlice:function(a,b,c,d,e,f,g,h){var i=this._getContext(g,h);i.beginPath(),i.moveTo(b,c),i.arc(b,c,d,e,f,!1),i.lineTo(b,c),i.closePath(),g!==undefined&&i.stroke(),h&&i.fill(),this.targetX!==undefined&&this.targetY!==undefined&&i.isPointInPath(this.targetX,this.targetY)&&(this.currentTargetShapeId=a)},_drawRect:function(a,b,c,d,e,f,g){return this._drawShape(a,[[b,c],[b+d,c],[b+d,c+e],[b,c+e],[b,c]],f,g)},appendShape:function(a){return this.shapes[a.id]=a,this.shapeseq.push(a.id),this.lastShapeId=a.id,a.id},replaceWithShape:function(a,b){var c=this.shapeseq,d;this.shapes[b.id]=b;for(d=c.length;d--;)c[d]==a&&(c[d]=b.id);delete this.shapes[a]},replaceWithShapes:function(a,b){var c=this.shapeseq,d={},e,f,g;for(f=a.length;f--;)d[a[f]]=!0;for(f=c.length;f--;)e=c[f],d[e]&&(c.splice(f,1),delete this.shapes[e],g=f);for(f=b.length;f--;)c.splice(g,0,b[f].id),this.shapes[b[f].id]=b[f]},insertAfterShape:function(a,b){var c=this.shapeseq,d;for(d=c.length;d--;)if(c[d]===a){c.splice(d+1,0,b.id),this.shapes[b.id]=b;return}},removeShapeId:function(a){var b=this.shapeseq,c;for(c=b.length;c--;)if(b[c]===a){b.splice(c,1);break}delete this.shapes[a]},getShapeAt:function(a,b,c){return this.targetX=b,this.targetY=c,this.render(),this.currentTargetShapeId},render:function(){var a=this.shapeseq,b=this.shapes,c=a.length,d=this._getContext(),e,f,g;d.clearRect(0,0,this.pixelWidth,this.pixelHeight);for(g=0;g<c;g++)e=a[g],f=b[e],this["_draw"+f.type].apply(this,f.args);this.interact||(this.shapes={},this.shapeseq=[])}}),G=d(E,{init:function(b,c,d){var e;G._super.init.call(this,b,c,d),d[0]&&(d=d[0]),a.data(d,"_jqs_vcanvas",this),this.canvas=document.createElement("span"),a(this.canvas).css({display:"inline-block",position:"relative",overflow:"hidden",width:b,height:c,margin:"0px",padding:"0px",verticalAlign:"top"}),this._insert(this.canvas,d),this._calculatePixelDims(b,c,this.canvas),this.canvas.width=this.pixelWidth,this.canvas.height=this.pixelHeight,e='<v:group coordorigin="0 0" coordsize="'+this.pixelWidth+" "+this.pixelHeight+'"'+' style="position:absolute;top:0;left:0;width:'+this.pixelWidth+"px;height="+this.pixelHeight+'px;"></v:group>',this.canvas.insertAdjacentHTML("beforeEnd",e),this.group=a(this.canvas).children()[0],this.rendered=!1,this.prerender=""},_drawShape:function(a,b,c,d,e){var f=[],g,h,i,j,k,l,m;for(m=0,l=b.length;m<l;m++)f[m]=""+b[m][0]+","+b[m][1];return g=f.splice(0,1),e=e===undefined?1:e,h=c===undefined?' stroked="false" ':' strokeWeight="'+e+'px" strokeColor="'+c+'" ',i=d===undefined?' filled="false"':' fillColor="'+d+'" filled="true" ',j=f[0]===f[f.length-1]?"x ":"",k='<v:shape coordorigin="0 0" coordsize="'+this.pixelWidth+" "+this.pixelHeight+'" '+' id="jqsshape'+a+'" '+h+i+' style="position:absolute;left:0px;top:0px;height:'+this.pixelHeight+"px;width:"+this.pixelWidth+'px;padding:0px;margin:0px;" '+' path="m '+g+" l "+f.join(", ")+" "+j+'e">'+" </v:shape>",k},_drawCircle:function(a,b,c,d,e,f,g){var h,i,j;return b-=d,c-=d,h=e===undefined?' stroked="false" ':' strokeWeight="'+g+'px" strokeColor="'+e+'" ',i=f===undefined?' filled="false"':' fillColor="'+f+'" filled="true" ',j='<v:oval id="jqsshape'+a+'" '+h+i+' style="position:absolute;top:'+c+"px; left:"+b+"px; width:"+d*2+"px; height:"+d*2+'px"></v:oval>',j},_drawPieSlice:function(a,b,c,d,e,f,g,h){var i,j,k,l,m,n,o,p;if(e===f)return"";f-e===2*Math.PI&&(e=0,f=2*Math.PI),j=b+Math.round(Math.cos(e)*d),k=c+Math.round(Math.sin(e)*d),l=b+Math.round(Math.cos(f)*d),m=c+Math.round(Math.sin(f)*d);if(j===l&&k===m){if(f-e<Math.PI)return"";j=l=b+d,k=m=c}return j===l&&k===m&&f-e<Math.PI?"":(i=[b-d,c-d,b+d,c+d,j,k,l,m],n=g===undefined?' stroked="false" ':' strokeWeight="1px" strokeColor="'+g+'" ',o=h===undefined?' filled="false"':' fillColor="'+h+'" filled="true" ',p='<v:shape coordorigin="0 0" coordsize="'+this.pixelWidth+" "+this.pixelHeight+'" '+' id="jqsshape'+a+'" '+n+o+' style="position:absolute;left:0px;top:0px;height:'+this.pixelHeight+"px;width:"+this.pixelWidth+'px;padding:0px;margin:0px;" '+' path="m '+b+","+c+" wa "+i.join(", ")+' x e">'+" </v:shape>",p)},_drawRect:function(a,b,c,d,e,f,g){return this._drawShape(a,[[b,c],[b,c+e],[b+d,c+e],[b+d,c],[b,c]],f,g)},reset:function(){this.group.innerHTML=""},appendShape:function(a){var b=this["_draw"+a.type].apply(this,a.args);return this.rendered?this.group.insertAdjacentHTML("beforeEnd",b):this.prerender+=b,this.lastShapeId=a.id,a.id},replaceWithShape:function(b,c){var d=a("#jqsshape"+b),e=this["_draw"+c.type].apply(this,c.args);d[0].outerHTML=e},replaceWithShapes:function(b,c){var d=a("#jqsshape"+b[0]),e="",f=c.length,g;for(g=0;g<f;g++)e+=this["_draw"+c[g].type].apply(this,c[g].args);d[0].outerHTML=e;for(g=1;g<b.length;g++)a("#jqsshape"+b[g]).remove()},insertAfterShape:function(b,c){var d=a("#jqsshape"+b),e=this["_draw"+c.type].apply(this,c.args);d[0].insertAdjacentHTML("afterEnd",e)},removeShapeId:function(b){var c=a("#jqsshape"+b);this.group.removeChild(c[0])},getShapeAt:function(a,b,c){var d=a.id.substr(8);return d},render:function(){this.rendered||(this.group.innerHTML=this.prerender,this.rendered=!0)}})});
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-sparkline-2.1.1.min.js
jquery-sparkline-2.1.1.min.js
(function(X,l,n){var L=function(h){var j=function(e){function o(a,b){var c=j.defaults.columns,d=a.aoColumns.length,c=h.extend({},j.models.oColumn,c,{sSortingClass:a.oClasses.sSortable,sSortingClassJUI:a.oClasses.sSortJUI,nTh:b?b:l.createElement("th"),sTitle:c.sTitle?c.sTitle:b?b.innerHTML:"",aDataSort:c.aDataSort?c.aDataSort:[d],mData:c.mData?c.oDefaults:d});a.aoColumns.push(c);if(a.aoPreSearchCols[d]===n||null===a.aoPreSearchCols[d])a.aoPreSearchCols[d]=h.extend({},j.models.oSearch);else if(c=a.aoPreSearchCols[d], c.bRegex===n&&(c.bRegex=!0),c.bSmart===n&&(c.bSmart=!0),c.bCaseInsensitive===n)c.bCaseInsensitive=!0;m(a,d,null)}function m(a,b,c){var d=a.aoColumns[b];c!==n&&null!==c&&(c.mDataProp&&!c.mData&&(c.mData=c.mDataProp),c.sType!==n&&(d.sType=c.sType,d._bAutoType=!1),h.extend(d,c),p(d,c,"sWidth","sWidthOrig"),c.iDataSort!==n&&(d.aDataSort=[c.iDataSort]),p(d,c,"aDataSort"));var i=d.mRender?Q(d.mRender):null,f=Q(d.mData);d.fnGetData=function(a,b){var c=f(a,b);return d.mRender&&b&&""!==b?i(c,b,a):c};d.fnSetData= L(d.mData);a.oFeatures.bSort||(d.bSortable=!1);!d.bSortable||-1==h.inArray("asc",d.asSorting)&&-1==h.inArray("desc",d.asSorting)?(d.sSortingClass=a.oClasses.sSortableNone,d.sSortingClassJUI=""):-1==h.inArray("asc",d.asSorting)&&-1==h.inArray("desc",d.asSorting)?(d.sSortingClass=a.oClasses.sSortable,d.sSortingClassJUI=a.oClasses.sSortJUI):-1!=h.inArray("asc",d.asSorting)&&-1==h.inArray("desc",d.asSorting)?(d.sSortingClass=a.oClasses.sSortableAsc,d.sSortingClassJUI=a.oClasses.sSortJUIAscAllowed):-1== h.inArray("asc",d.asSorting)&&-1!=h.inArray("desc",d.asSorting)&&(d.sSortingClass=a.oClasses.sSortableDesc,d.sSortingClassJUI=a.oClasses.sSortJUIDescAllowed)}function k(a){if(!1===a.oFeatures.bAutoWidth)return!1;da(a);for(var b=0,c=a.aoColumns.length;b<c;b++)a.aoColumns[b].nTh.style.width=a.aoColumns[b].sWidth}function G(a,b){var c=r(a,"bVisible");return"number"===typeof c[b]?c[b]:null}function R(a,b){var c=r(a,"bVisible"),c=h.inArray(b,c);return-1!==c?c:null}function t(a){return r(a,"bVisible").length} function r(a,b){var c=[];h.map(a.aoColumns,function(a,i){a[b]&&c.push(i)});return c}function B(a){for(var b=j.ext.aTypes,c=b.length,d=0;d<c;d++){var i=b[d](a);if(null!==i)return i}return"string"}function u(a,b){for(var c=b.split(","),d=[],i=0,f=a.aoColumns.length;i<f;i++)for(var g=0;g<f;g++)if(a.aoColumns[i].sName==c[g]){d.push(g);break}return d}function M(a){for(var b="",c=0,d=a.aoColumns.length;c<d;c++)b+=a.aoColumns[c].sName+",";return b.length==d?"":b.slice(0,-1)}function ta(a,b,c,d){var i,f, g,e,w;if(b)for(i=b.length-1;0<=i;i--){var j=b[i].aTargets;h.isArray(j)||D(a,1,"aTargets must be an array of targets, not a "+typeof j);f=0;for(g=j.length;f<g;f++)if("number"===typeof j[f]&&0<=j[f]){for(;a.aoColumns.length<=j[f];)o(a);d(j[f],b[i])}else if("number"===typeof j[f]&&0>j[f])d(a.aoColumns.length+j[f],b[i]);else if("string"===typeof j[f]){e=0;for(w=a.aoColumns.length;e<w;e++)("_all"==j[f]||h(a.aoColumns[e].nTh).hasClass(j[f]))&&d(e,b[i])}}if(c){i=0;for(a=c.length;i<a;i++)d(i,c[i])}}function H(a, b){var c;c=h.isArray(b)?b.slice():h.extend(!0,{},b);var d=a.aoData.length,i=h.extend(!0,{},j.models.oRow);i._aData=c;a.aoData.push(i);for(var f,i=0,g=a.aoColumns.length;i<g;i++)c=a.aoColumns[i],"function"===typeof c.fnRender&&c.bUseRendered&&null!==c.mData?F(a,d,i,S(a,d,i)):F(a,d,i,v(a,d,i)),c._bAutoType&&"string"!=c.sType&&(f=v(a,d,i,"type"),null!==f&&""!==f&&(f=B(f),null===c.sType?c.sType=f:c.sType!=f&&"html"!=c.sType&&(c.sType="string")));a.aiDisplayMaster.push(d);a.oFeatures.bDeferRender||ea(a, d);return d}function ua(a){var b,c,d,i,f,g,e;if(a.bDeferLoading||null===a.sAjaxSource)for(b=a.nTBody.firstChild;b;){if("TR"==b.nodeName.toUpperCase()){c=a.aoData.length;b._DT_RowIndex=c;a.aoData.push(h.extend(!0,{},j.models.oRow,{nTr:b}));a.aiDisplayMaster.push(c);f=b.firstChild;for(d=0;f;){g=f.nodeName.toUpperCase();if("TD"==g||"TH"==g)F(a,c,d,h.trim(f.innerHTML)),d++;f=f.nextSibling}}b=b.nextSibling}i=T(a);d=[];b=0;for(c=i.length;b<c;b++)for(f=i[b].firstChild;f;)g=f.nodeName.toUpperCase(),("TD"== g||"TH"==g)&&d.push(f),f=f.nextSibling;c=0;for(i=a.aoColumns.length;c<i;c++){e=a.aoColumns[c];null===e.sTitle&&(e.sTitle=e.nTh.innerHTML);var w=e._bAutoType,o="function"===typeof e.fnRender,k=null!==e.sClass,n=e.bVisible,m,p;if(w||o||k||!n){g=0;for(b=a.aoData.length;g<b;g++)f=a.aoData[g],m=d[g*i+c],w&&"string"!=e.sType&&(p=v(a,g,c,"type"),""!==p&&(p=B(p),null===e.sType?e.sType=p:e.sType!=p&&"html"!=e.sType&&(e.sType="string"))),e.mRender?m.innerHTML=v(a,g,c,"display"):e.mData!==c&&(m.innerHTML=v(a, g,c,"display")),o&&(p=S(a,g,c),m.innerHTML=p,e.bUseRendered&&F(a,g,c,p)),k&&(m.className+=" "+e.sClass),n?f._anHidden[c]=null:(f._anHidden[c]=m,m.parentNode.removeChild(m)),e.fnCreatedCell&&e.fnCreatedCell.call(a.oInstance,m,v(a,g,c,"display"),f._aData,g,c)}}if(0!==a.aoRowCreatedCallback.length){b=0;for(c=a.aoData.length;b<c;b++)f=a.aoData[b],A(a,"aoRowCreatedCallback",null,[f.nTr,f._aData,b])}}function I(a,b){return b._DT_RowIndex!==n?b._DT_RowIndex:null}function fa(a,b,c){for(var b=J(a,b),d=0,a= a.aoColumns.length;d<a;d++)if(b[d]===c)return d;return-1}function Y(a,b,c,d){for(var i=[],f=0,g=d.length;f<g;f++)i.push(v(a,b,d[f],c));return i}function v(a,b,c,d){var i=a.aoColumns[c];if((c=i.fnGetData(a.aoData[b]._aData,d))===n)return a.iDrawError!=a.iDraw&&null===i.sDefaultContent&&(D(a,0,"Requested unknown parameter "+("function"==typeof i.mData?"{mData function}":"'"+i.mData+"'")+" from the data source for row "+b),a.iDrawError=a.iDraw),i.sDefaultContent;if(null===c&&null!==i.sDefaultContent)c= i.sDefaultContent;else if("function"===typeof c)return c();return"display"==d&&null===c?"":c}function F(a,b,c,d){a.aoColumns[c].fnSetData(a.aoData[b]._aData,d)}function Q(a){if(null===a)return function(){return null};if("function"===typeof a)return function(b,d,i){return a(b,d,i)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("["))){var b=function(a,d,i){var f=i.split("."),g;if(""!==i){var e=0;for(g=f.length;e<g;e++){if(i=f[e].match(U)){f[e]=f[e].replace(U,"");""!==f[e]&&(a=a[f[e]]); g=[];f.splice(0,e+1);for(var f=f.join("."),e=0,h=a.length;e<h;e++)g.push(b(a[e],d,f));a=i[0].substring(1,i[0].length-1);a=""===a?g:g.join(a);break}if(null===a||a[f[e]]===n)return n;a=a[f[e]]}}return a};return function(c,d){return b(c,d,a)}}return function(b){return b[a]}}function L(a){if(null===a)return function(){};if("function"===typeof a)return function(b,d){a(b,"set",d)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("["))){var b=function(a,d,i){var i=i.split("."),f,g,e=0;for(g= i.length-1;e<g;e++){if(f=i[e].match(U)){i[e]=i[e].replace(U,"");a[i[e]]=[];f=i.slice();f.splice(0,e+1);g=f.join(".");for(var h=0,j=d.length;h<j;h++)f={},b(f,d[h],g),a[i[e]].push(f);return}if(null===a[i[e]]||a[i[e]]===n)a[i[e]]={};a=a[i[e]]}a[i[i.length-1].replace(U,"")]=d};return function(c,d){return b(c,d,a)}}return function(b,d){b[a]=d}}function Z(a){for(var b=[],c=a.aoData.length,d=0;d<c;d++)b.push(a.aoData[d]._aData);return b}function ga(a){a.aoData.splice(0,a.aoData.length);a.aiDisplayMaster.splice(0, a.aiDisplayMaster.length);a.aiDisplay.splice(0,a.aiDisplay.length);y(a)}function ha(a,b){for(var c=-1,d=0,i=a.length;d<i;d++)a[d]==b?c=d:a[d]>b&&a[d]--; -1!=c&&a.splice(c,1)}function S(a,b,c){var d=a.aoColumns[c];return d.fnRender({iDataRow:b,iDataColumn:c,oSettings:a,aData:a.aoData[b]._aData,mDataProp:d.mData},v(a,b,c,"display"))}function ea(a,b){var c=a.aoData[b],d;if(null===c.nTr){c.nTr=l.createElement("tr");c.nTr._DT_RowIndex=b;c._aData.DT_RowId&&(c.nTr.id=c._aData.DT_RowId);c._aData.DT_RowClass&& (c.nTr.className=c._aData.DT_RowClass);for(var i=0,f=a.aoColumns.length;i<f;i++){var g=a.aoColumns[i];d=l.createElement(g.sCellType);d.innerHTML="function"===typeof g.fnRender&&(!g.bUseRendered||null===g.mData)?S(a,b,i):v(a,b,i,"display");null!==g.sClass&&(d.className=g.sClass);g.bVisible?(c.nTr.appendChild(d),c._anHidden[i]=null):c._anHidden[i]=d;g.fnCreatedCell&&g.fnCreatedCell.call(a.oInstance,d,v(a,b,i,"display"),c._aData,b,i)}A(a,"aoRowCreatedCallback",null,[c.nTr,c._aData,b])}}function va(a){var b, c,d;if(0!==h("th, td",a.nTHead).length){b=0;for(d=a.aoColumns.length;b<d;b++)if(c=a.aoColumns[b].nTh,c.setAttribute("role","columnheader"),a.aoColumns[b].bSortable&&(c.setAttribute("tabindex",a.iTabIndex),c.setAttribute("aria-controls",a.sTableId)),null!==a.aoColumns[b].sClass&&h(c).addClass(a.aoColumns[b].sClass),a.aoColumns[b].sTitle!=c.innerHTML)c.innerHTML=a.aoColumns[b].sTitle}else{var i=l.createElement("tr");b=0;for(d=a.aoColumns.length;b<d;b++)c=a.aoColumns[b].nTh,c.innerHTML=a.aoColumns[b].sTitle, c.setAttribute("tabindex","0"),null!==a.aoColumns[b].sClass&&h(c).addClass(a.aoColumns[b].sClass),i.appendChild(c);h(a.nTHead).html("")[0].appendChild(i);V(a.aoHeader,a.nTHead)}h(a.nTHead).children("tr").attr("role","row");if(a.bJUI){b=0;for(d=a.aoColumns.length;b<d;b++){c=a.aoColumns[b].nTh;i=l.createElement("div");i.className=a.oClasses.sSortJUIWrapper;h(c).contents().appendTo(i);var f=l.createElement("span");f.className=a.oClasses.sSortIcon;i.appendChild(f);c.appendChild(i)}}if(a.oFeatures.bSort)for(b= 0;b<a.aoColumns.length;b++)!1!==a.aoColumns[b].bSortable?ia(a,a.aoColumns[b].nTh,b):h(a.aoColumns[b].nTh).addClass(a.oClasses.sSortableNone);""!==a.oClasses.sFooterTH&&h(a.nTFoot).children("tr").children("th").addClass(a.oClasses.sFooterTH);if(null!==a.nTFoot){c=N(a,null,a.aoFooter);b=0;for(d=a.aoColumns.length;b<d;b++)c[b]&&(a.aoColumns[b].nTf=c[b],a.aoColumns[b].sClass&&h(c[b]).addClass(a.aoColumns[b].sClass))}}function W(a,b,c){var d,i,f,g=[],e=[],h=a.aoColumns.length,j;c===n&&(c=!1);d=0;for(i= b.length;d<i;d++){g[d]=b[d].slice();g[d].nTr=b[d].nTr;for(f=h-1;0<=f;f--)!a.aoColumns[f].bVisible&&!c&&g[d].splice(f,1);e.push([])}d=0;for(i=g.length;d<i;d++){if(a=g[d].nTr)for(;f=a.firstChild;)a.removeChild(f);f=0;for(b=g[d].length;f<b;f++)if(j=h=1,e[d][f]===n){a.appendChild(g[d][f].cell);for(e[d][f]=1;g[d+h]!==n&&g[d][f].cell==g[d+h][f].cell;)e[d+h][f]=1,h++;for(;g[d][f+j]!==n&&g[d][f].cell==g[d][f+j].cell;){for(c=0;c<h;c++)e[d+c][f+j]=1;j++}g[d][f].cell.rowSpan=h;g[d][f].cell.colSpan=j}}}function x(a){var b= A(a,"aoPreDrawCallback","preDraw",[a]);if(-1!==h.inArray(!1,b))E(a,!1);else{var c,d,b=[],i=0,f=a.asStripeClasses.length;c=a.aoOpenRows.length;a.bDrawing=!0;a.iInitDisplayStart!==n&&-1!=a.iInitDisplayStart&&(a._iDisplayStart=a.oFeatures.bServerSide?a.iInitDisplayStart:a.iInitDisplayStart>=a.fnRecordsDisplay()?0:a.iInitDisplayStart,a.iInitDisplayStart=-1,y(a));if(a.bDeferLoading)a.bDeferLoading=!1,a.iDraw++;else if(a.oFeatures.bServerSide){if(!a.bDestroying&&!wa(a))return}else a.iDraw++;if(0!==a.aiDisplay.length){var g= a._iDisplayStart;d=a._iDisplayEnd;a.oFeatures.bServerSide&&(g=0,d=a.aoData.length);for(;g<d;g++){var e=a.aoData[a.aiDisplay[g]];null===e.nTr&&ea(a,a.aiDisplay[g]);var j=e.nTr;if(0!==f){var o=a.asStripeClasses[i%f];e._sRowStripe!=o&&(h(j).removeClass(e._sRowStripe).addClass(o),e._sRowStripe=o)}A(a,"aoRowCallback",null,[j,a.aoData[a.aiDisplay[g]]._aData,i,g]);b.push(j);i++;if(0!==c)for(e=0;e<c;e++)if(j==a.aoOpenRows[e].nParent){b.push(a.aoOpenRows[e].nTr);break}}}else b[0]=l.createElement("tr"),a.asStripeClasses[0]&& (b[0].className=a.asStripeClasses[0]),c=a.oLanguage,f=c.sZeroRecords,1==a.iDraw&&null!==a.sAjaxSource&&!a.oFeatures.bServerSide?f=c.sLoadingRecords:c.sEmptyTable&&0===a.fnRecordsTotal()&&(f=c.sEmptyTable),c=l.createElement("td"),c.setAttribute("valign","top"),c.colSpan=t(a),c.className=a.oClasses.sRowEmpty,c.innerHTML=ja(a,f),b[i].appendChild(c);A(a,"aoHeaderCallback","header",[h(a.nTHead).children("tr")[0],Z(a),a._iDisplayStart,a.fnDisplayEnd(),a.aiDisplay]);A(a,"aoFooterCallback","footer",[h(a.nTFoot).children("tr")[0], Z(a),a._iDisplayStart,a.fnDisplayEnd(),a.aiDisplay]);i=l.createDocumentFragment();c=l.createDocumentFragment();if(a.nTBody){f=a.nTBody.parentNode;c.appendChild(a.nTBody);if(!a.oScroll.bInfinite||!a._bInitComplete||a.bSorted||a.bFiltered)for(;c=a.nTBody.firstChild;)a.nTBody.removeChild(c);c=0;for(d=b.length;c<d;c++)i.appendChild(b[c]);a.nTBody.appendChild(i);null!==f&&f.appendChild(a.nTBody)}A(a,"aoDrawCallback","draw",[a]);a.bSorted=!1;a.bFiltered=!1;a.bDrawing=!1;a.oFeatures.bServerSide&&(E(a,!1), a._bInitComplete||$(a))}}function aa(a){a.oFeatures.bSort?O(a,a.oPreviousSearch):a.oFeatures.bFilter?K(a,a.oPreviousSearch):(y(a),x(a))}function xa(a){var b=h("<div></div>")[0];a.nTable.parentNode.insertBefore(b,a.nTable);a.nTableWrapper=h('<div id="'+a.sTableId+'_wrapper" class="'+a.oClasses.sWrapper+'" role="grid"></div>')[0];a.nTableReinsertBefore=a.nTable.nextSibling;for(var c=a.nTableWrapper,d=a.sDom.split(""),i,f,g,e,w,o,k,m=0;m<d.length;m++){f=0;g=d[m];if("<"==g){e=h("<div></div>")[0];w=d[m+ 1];if("'"==w||'"'==w){o="";for(k=2;d[m+k]!=w;)o+=d[m+k],k++;"H"==o?o=a.oClasses.sJUIHeader:"F"==o&&(o=a.oClasses.sJUIFooter);-1!=o.indexOf(".")?(w=o.split("."),e.id=w[0].substr(1,w[0].length-1),e.className=w[1]):"#"==o.charAt(0)?e.id=o.substr(1,o.length-1):e.className=o;m+=k}c.appendChild(e);c=e}else if(">"==g)c=c.parentNode;else if("l"==g&&a.oFeatures.bPaginate&&a.oFeatures.bLengthChange)i=ya(a),f=1;else if("f"==g&&a.oFeatures.bFilter)i=za(a),f=1;else if("r"==g&&a.oFeatures.bProcessing)i=Aa(a),f= 1;else if("t"==g)i=Ba(a),f=1;else if("i"==g&&a.oFeatures.bInfo)i=Ca(a),f=1;else if("p"==g&&a.oFeatures.bPaginate)i=Da(a),f=1;else if(0!==j.ext.aoFeatures.length){e=j.ext.aoFeatures;k=0;for(w=e.length;k<w;k++)if(g==e[k].cFeature){(i=e[k].fnInit(a))&&(f=1);break}}1==f&&null!==i&&("object"!==typeof a.aanFeatures[g]&&(a.aanFeatures[g]=[]),a.aanFeatures[g].push(i),c.appendChild(i))}b.parentNode.replaceChild(a.nTableWrapper,b)}function V(a,b){var c=h(b).children("tr"),d,i,f,g,e,j,o,k,m,p;a.splice(0,a.length); f=0;for(j=c.length;f<j;f++)a.push([]);f=0;for(j=c.length;f<j;f++){d=c[f];for(i=d.firstChild;i;){if("TD"==i.nodeName.toUpperCase()||"TH"==i.nodeName.toUpperCase()){k=1*i.getAttribute("colspan");m=1*i.getAttribute("rowspan");k=!k||0===k||1===k?1:k;m=!m||0===m||1===m?1:m;g=0;for(e=a[f];e[g];)g++;o=g;p=1===k?!0:!1;for(e=0;e<k;e++)for(g=0;g<m;g++)a[f+g][o+e]={cell:i,unique:p},a[f+g].nTr=d}i=i.nextSibling}}}function N(a,b,c){var d=[];c||(c=a.aoHeader,b&&(c=[],V(c,b)));for(var b=0,i=c.length;b<i;b++)for(var f= 0,g=c[b].length;f<g;f++)if(c[b][f].unique&&(!d[f]||!a.bSortCellsTop))d[f]=c[b][f].cell;return d}function wa(a){if(a.bAjaxDataGet){a.iDraw++;E(a,!0);var b=Ea(a);ka(a,b);a.fnServerData.call(a.oInstance,a.sAjaxSource,b,function(b){Fa(a,b)},a);return!1}return!0}function Ea(a){var b=a.aoColumns.length,c=[],d,i,f,g;c.push({name:"sEcho",value:a.iDraw});c.push({name:"iColumns",value:b});c.push({name:"sColumns",value:M(a)});c.push({name:"iDisplayStart",value:a._iDisplayStart});c.push({name:"iDisplayLength", value:!1!==a.oFeatures.bPaginate?a._iDisplayLength:-1});for(f=0;f<b;f++)d=a.aoColumns[f].mData,c.push({name:"mDataProp_"+f,value:"function"===typeof d?"function":d});if(!1!==a.oFeatures.bFilter){c.push({name:"sSearch",value:a.oPreviousSearch.sSearch});c.push({name:"bRegex",value:a.oPreviousSearch.bRegex});for(f=0;f<b;f++)c.push({name:"sSearch_"+f,value:a.aoPreSearchCols[f].sSearch}),c.push({name:"bRegex_"+f,value:a.aoPreSearchCols[f].bRegex}),c.push({name:"bSearchable_"+f,value:a.aoColumns[f].bSearchable})}if(!1!== a.oFeatures.bSort){var e=0;d=null!==a.aaSortingFixed?a.aaSortingFixed.concat(a.aaSorting):a.aaSorting.slice();for(f=0;f<d.length;f++){i=a.aoColumns[d[f][0]].aDataSort;for(g=0;g<i.length;g++)c.push({name:"iSortCol_"+e,value:i[g]}),c.push({name:"sSortDir_"+e,value:d[f][1]}),e++}c.push({name:"iSortingCols",value:e});for(f=0;f<b;f++)c.push({name:"bSortable_"+f,value:a.aoColumns[f].bSortable})}return c}function ka(a,b){A(a,"aoServerParams","serverParams",[b])}function Fa(a,b){if(b.sEcho!==n){if(1*b.sEcho< a.iDraw)return;a.iDraw=1*b.sEcho}(!a.oScroll.bInfinite||a.oScroll.bInfinite&&(a.bSorted||a.bFiltered))&&ga(a);a._iRecordsTotal=parseInt(b.iTotalRecords,10);a._iRecordsDisplay=parseInt(b.iTotalDisplayRecords,10);var c=M(a),c=b.sColumns!==n&&""!==c&&b.sColumns!=c,d;c&&(d=u(a,b.sColumns));for(var i=Q(a.sAjaxDataProp)(b),f=0,g=i.length;f<g;f++)if(c){for(var e=[],h=0,j=a.aoColumns.length;h<j;h++)e.push(i[f][d[h]]);H(a,e)}else H(a,i[f]);a.aiDisplay=a.aiDisplayMaster.slice();a.bAjaxDataGet=!1;x(a);a.bAjaxDataGet= !0;E(a,!1)}function za(a){var b=a.oPreviousSearch,c=a.oLanguage.sSearch,c=-1!==c.indexOf("_INPUT_")?c.replace("_INPUT_",'<input type="text" />'):""===c?'<input type="text" />':c+' <input type="text" />',d=l.createElement("div");d.className=a.oClasses.sFilter;d.innerHTML="<label>"+c+"</label>";a.aanFeatures.f||(d.id=a.sTableId+"_filter");c=h('input[type="text"]',d);d._DT_Input=c[0];c.val(b.sSearch.replace('"',"&quot;"));c.bind("keyup.DT",function(){for(var c=a.aanFeatures.f,d=this.value===""?"":this.value, g=0,e=c.length;g<e;g++)c[g]!=h(this).parents("div.dataTables_filter")[0]&&h(c[g]._DT_Input).val(d);d!=b.sSearch&&K(a,{sSearch:d,bRegex:b.bRegex,bSmart:b.bSmart,bCaseInsensitive:b.bCaseInsensitive})});c.attr("aria-controls",a.sTableId).bind("keypress.DT",function(a){if(a.keyCode==13)return false});return d}function K(a,b,c){var d=a.oPreviousSearch,i=a.aoPreSearchCols,f=function(a){d.sSearch=a.sSearch;d.bRegex=a.bRegex;d.bSmart=a.bSmart;d.bCaseInsensitive=a.bCaseInsensitive};if(a.oFeatures.bServerSide)f(b); else{Ga(a,b.sSearch,c,b.bRegex,b.bSmart,b.bCaseInsensitive);f(b);for(b=0;b<a.aoPreSearchCols.length;b++)Ha(a,i[b].sSearch,b,i[b].bRegex,i[b].bSmart,i[b].bCaseInsensitive);Ia(a)}a.bFiltered=!0;h(a.oInstance).trigger("filter",a);a._iDisplayStart=0;y(a);x(a);la(a,0)}function Ia(a){for(var b=j.ext.afnFiltering,c=r(a,"bSearchable"),d=0,i=b.length;d<i;d++)for(var f=0,g=0,e=a.aiDisplay.length;g<e;g++){var h=a.aiDisplay[g-f];b[d](a,Y(a,h,"filter",c),h)||(a.aiDisplay.splice(g-f,1),f++)}}function Ha(a,b,c, d,i,f){if(""!==b)for(var g=0,b=ma(b,d,i,f),d=a.aiDisplay.length-1;0<=d;d--)i=Ja(v(a,a.aiDisplay[d],c,"filter"),a.aoColumns[c].sType),b.test(i)||(a.aiDisplay.splice(d,1),g++)}function Ga(a,b,c,d,i,f){d=ma(b,d,i,f);i=a.oPreviousSearch;c||(c=0);0!==j.ext.afnFiltering.length&&(c=1);if(0>=b.length)a.aiDisplay.splice(0,a.aiDisplay.length),a.aiDisplay=a.aiDisplayMaster.slice();else if(a.aiDisplay.length==a.aiDisplayMaster.length||i.sSearch.length>b.length||1==c||0!==b.indexOf(i.sSearch)){a.aiDisplay.splice(0, a.aiDisplay.length);la(a,1);for(b=0;b<a.aiDisplayMaster.length;b++)d.test(a.asDataSearch[b])&&a.aiDisplay.push(a.aiDisplayMaster[b])}else for(b=c=0;b<a.asDataSearch.length;b++)d.test(a.asDataSearch[b])||(a.aiDisplay.splice(b-c,1),c++)}function la(a,b){if(!a.oFeatures.bServerSide){a.asDataSearch=[];for(var c=r(a,"bSearchable"),d=1===b?a.aiDisplayMaster:a.aiDisplay,i=0,f=d.length;i<f;i++)a.asDataSearch[i]=na(a,Y(a,d[i],"filter",c))}}function na(a,b){var c=b.join(" ");-1!==c.indexOf("&")&&(c=h("<div>").html(c).text()); return c.replace(/[\n\r]/g," ")}function ma(a,b,c,d){if(c)return a=b?a.split(" "):oa(a).split(" "),a="^(?=.*?"+a.join(")(?=.*?")+").*$",RegExp(a,d?"i":"");a=b?a:oa(a);return RegExp(a,d?"i":"")}function Ja(a,b){return"function"===typeof j.ext.ofnSearch[b]?j.ext.ofnSearch[b](a):null===a?"":"html"==b?a.replace(/[\r\n]/g," ").replace(/<.*?>/g,""):"string"===typeof a?a.replace(/[\r\n]/g," "):a}function oa(a){return a.replace(RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\|\\$|\\^|\\-)","g"), "\\$1")}function Ca(a){var b=l.createElement("div");b.className=a.oClasses.sInfo;a.aanFeatures.i||(a.aoDrawCallback.push({fn:Ka,sName:"information"}),b.id=a.sTableId+"_info");a.nTable.setAttribute("aria-describedby",a.sTableId+"_info");return b}function Ka(a){if(a.oFeatures.bInfo&&0!==a.aanFeatures.i.length){var b=a.oLanguage,c=a._iDisplayStart+1,d=a.fnDisplayEnd(),i=a.fnRecordsTotal(),f=a.fnRecordsDisplay(),g;g=0===f?b.sInfoEmpty:b.sInfo;f!=i&&(g+=" "+b.sInfoFiltered);g+=b.sInfoPostFix;g=ja(a,g); null!==b.fnInfoCallback&&(g=b.fnInfoCallback.call(a.oInstance,a,c,d,i,f,g));a=a.aanFeatures.i;b=0;for(c=a.length;b<c;b++)h(a[b]).html(g)}}function ja(a,b){var c=a.fnFormatNumber(a._iDisplayStart+1),d=a.fnDisplayEnd(),d=a.fnFormatNumber(d),i=a.fnRecordsDisplay(),i=a.fnFormatNumber(i),f=a.fnRecordsTotal(),f=a.fnFormatNumber(f);a.oScroll.bInfinite&&(c=a.fnFormatNumber(1));return b.replace(/_START_/g,c).replace(/_END_/g,d).replace(/_TOTAL_/g,i).replace(/_MAX_/g,f)}function ba(a){var b,c,d=a.iInitDisplayStart; if(!1===a.bInitialised)setTimeout(function(){ba(a)},200);else{xa(a);va(a);W(a,a.aoHeader);a.nTFoot&&W(a,a.aoFooter);E(a,!0);a.oFeatures.bAutoWidth&&da(a);b=0;for(c=a.aoColumns.length;b<c;b++)null!==a.aoColumns[b].sWidth&&(a.aoColumns[b].nTh.style.width=q(a.aoColumns[b].sWidth));a.oFeatures.bSort?O(a):a.oFeatures.bFilter?K(a,a.oPreviousSearch):(a.aiDisplay=a.aiDisplayMaster.slice(),y(a),x(a));null!==a.sAjaxSource&&!a.oFeatures.bServerSide?(c=[],ka(a,c),a.fnServerData.call(a.oInstance,a.sAjaxSource, c,function(c){var f=a.sAjaxDataProp!==""?Q(a.sAjaxDataProp)(c):c;for(b=0;b<f.length;b++)H(a,f[b]);a.iInitDisplayStart=d;if(a.oFeatures.bSort)O(a);else{a.aiDisplay=a.aiDisplayMaster.slice();y(a);x(a)}E(a,false);$(a,c)},a)):a.oFeatures.bServerSide||(E(a,!1),$(a))}}function $(a,b){a._bInitComplete=!0;A(a,"aoInitComplete","init",[a,b])}function pa(a){var b=j.defaults.oLanguage;!a.sEmptyTable&&(a.sZeroRecords&&"No data available in table"===b.sEmptyTable)&&p(a,a,"sZeroRecords","sEmptyTable");!a.sLoadingRecords&& (a.sZeroRecords&&"Loading..."===b.sLoadingRecords)&&p(a,a,"sZeroRecords","sLoadingRecords")}function ya(a){if(a.oScroll.bInfinite)return null;var b='<select size="1" '+('name="'+a.sTableId+'_length"')+">",c,d,i=a.aLengthMenu;if(2==i.length&&"object"===typeof i[0]&&"object"===typeof i[1]){c=0;for(d=i[0].length;c<d;c++)b+='<option value="'+i[0][c]+'">'+i[1][c]+"</option>"}else{c=0;for(d=i.length;c<d;c++)b+='<option value="'+i[c]+'">'+i[c]+"</option>"}b+="</select>";i=l.createElement("div");a.aanFeatures.l|| (i.id=a.sTableId+"_length");i.className=a.oClasses.sLength;i.innerHTML="<label>"+a.oLanguage.sLengthMenu.replace("_MENU_",b)+"</label>";h('select option[value="'+a._iDisplayLength+'"]',i).attr("selected",!0);h("select",i).bind("change.DT",function(){var b=h(this).val(),i=a.aanFeatures.l;c=0;for(d=i.length;c<d;c++)i[c]!=this.parentNode&&h("select",i[c]).val(b);a._iDisplayLength=parseInt(b,10);y(a);if(a.fnDisplayEnd()==a.fnRecordsDisplay()){a._iDisplayStart=a.fnDisplayEnd()-a._iDisplayLength;if(a._iDisplayStart< 0)a._iDisplayStart=0}if(a._iDisplayLength==-1)a._iDisplayStart=0;x(a)});h("select",i).attr("aria-controls",a.sTableId);return i}function y(a){a._iDisplayEnd=!1===a.oFeatures.bPaginate?a.aiDisplay.length:a._iDisplayStart+a._iDisplayLength>a.aiDisplay.length||-1==a._iDisplayLength?a.aiDisplay.length:a._iDisplayStart+a._iDisplayLength}function Da(a){if(a.oScroll.bInfinite)return null;var b=l.createElement("div");b.className=a.oClasses.sPaging+a.sPaginationType;j.ext.oPagination[a.sPaginationType].fnInit(a, b,function(a){y(a);x(a)});a.aanFeatures.p||a.aoDrawCallback.push({fn:function(a){j.ext.oPagination[a.sPaginationType].fnUpdate(a,function(a){y(a);x(a)})},sName:"pagination"});return b}function qa(a,b){var c=a._iDisplayStart;if("number"===typeof b)a._iDisplayStart=b*a._iDisplayLength,a._iDisplayStart>a.fnRecordsDisplay()&&(a._iDisplayStart=0);else if("first"==b)a._iDisplayStart=0;else if("previous"==b)a._iDisplayStart=0<=a._iDisplayLength?a._iDisplayStart-a._iDisplayLength:0,0>a._iDisplayStart&&(a._iDisplayStart= 0);else if("next"==b)0<=a._iDisplayLength?a._iDisplayStart+a._iDisplayLength<a.fnRecordsDisplay()&&(a._iDisplayStart+=a._iDisplayLength):a._iDisplayStart=0;else if("last"==b)if(0<=a._iDisplayLength){var d=parseInt((a.fnRecordsDisplay()-1)/a._iDisplayLength,10)+1;a._iDisplayStart=(d-1)*a._iDisplayLength}else a._iDisplayStart=0;else D(a,0,"Unknown paging action: "+b);h(a.oInstance).trigger("page",a);return c!=a._iDisplayStart}function Aa(a){var b=l.createElement("div");a.aanFeatures.r||(b.id=a.sTableId+ "_processing");b.innerHTML=a.oLanguage.sProcessing;b.className=a.oClasses.sProcessing;a.nTable.parentNode.insertBefore(b,a.nTable);return b}function E(a,b){if(a.oFeatures.bProcessing)for(var c=a.aanFeatures.r,d=0,i=c.length;d<i;d++)c[d].style.visibility=b?"visible":"hidden";h(a.oInstance).trigger("processing",[a,b])}function Ba(a){if(""===a.oScroll.sX&&""===a.oScroll.sY)return a.nTable;var b=l.createElement("div"),c=l.createElement("div"),d=l.createElement("div"),i=l.createElement("div"),f=l.createElement("div"), g=l.createElement("div"),e=a.nTable.cloneNode(!1),j=a.nTable.cloneNode(!1),o=a.nTable.getElementsByTagName("thead")[0],k=0===a.nTable.getElementsByTagName("tfoot").length?null:a.nTable.getElementsByTagName("tfoot")[0],m=a.oClasses;c.appendChild(d);f.appendChild(g);i.appendChild(a.nTable);b.appendChild(c);b.appendChild(i);d.appendChild(e);e.appendChild(o);null!==k&&(b.appendChild(f),g.appendChild(j),j.appendChild(k));b.className=m.sScrollWrapper;c.className=m.sScrollHead;d.className=m.sScrollHeadInner; i.className=m.sScrollBody;f.className=m.sScrollFoot;g.className=m.sScrollFootInner;a.oScroll.bAutoCss&&(c.style.overflow="hidden",c.style.position="relative",f.style.overflow="hidden",i.style.overflow="auto");c.style.border="0";c.style.width="100%";f.style.border="0";d.style.width=""!==a.oScroll.sXInner?a.oScroll.sXInner:"100%";e.removeAttribute("id");e.style.marginLeft="0";a.nTable.style.marginLeft="0";null!==k&&(j.removeAttribute("id"),j.style.marginLeft="0");d=h(a.nTable).children("caption");0< d.length&&(d=d[0],"top"===d._captionSide?e.appendChild(d):"bottom"===d._captionSide&&k&&j.appendChild(d));""!==a.oScroll.sX&&(c.style.width=q(a.oScroll.sX),i.style.width=q(a.oScroll.sX),null!==k&&(f.style.width=q(a.oScroll.sX)),h(i).scroll(function(){c.scrollLeft=this.scrollLeft;if(k!==null)f.scrollLeft=this.scrollLeft}));""!==a.oScroll.sY&&(i.style.height=q(a.oScroll.sY));a.aoDrawCallback.push({fn:La,sName:"scrolling"});a.oScroll.bInfinite&&h(i).scroll(function(){if(!a.bDrawing&&h(this).scrollTop()!== 0&&h(this).scrollTop()+h(this).height()>h(a.nTable).height()-a.oScroll.iLoadGap&&a.fnDisplayEnd()<a.fnRecordsDisplay()){qa(a,"next");y(a);x(a)}});a.nScrollHead=c;a.nScrollFoot=f;return b}function La(a){var b=a.nScrollHead.getElementsByTagName("div")[0],c=b.getElementsByTagName("table")[0],d=a.nTable.parentNode,i,f,g,e,j,o,k,m,p=[],n=[],l=null!==a.nTFoot?a.nScrollFoot.getElementsByTagName("div")[0]:null,R=null!==a.nTFoot?l.getElementsByTagName("table")[0]:null,r=a.oBrowser.bScrollOversize,s=function(a){k= a.style;k.paddingTop="0";k.paddingBottom="0";k.borderTopWidth="0";k.borderBottomWidth="0";k.height=0};h(a.nTable).children("thead, tfoot").remove();i=h(a.nTHead).clone()[0];a.nTable.insertBefore(i,a.nTable.childNodes[0]);g=a.nTHead.getElementsByTagName("tr");e=i.getElementsByTagName("tr");null!==a.nTFoot&&(j=h(a.nTFoot).clone()[0],a.nTable.insertBefore(j,a.nTable.childNodes[1]),o=a.nTFoot.getElementsByTagName("tr"),j=j.getElementsByTagName("tr"));""===a.oScroll.sX&&(d.style.width="100%",b.parentNode.style.width= "100%");var t=N(a,i);i=0;for(f=t.length;i<f;i++)m=G(a,i),t[i].style.width=a.aoColumns[m].sWidth;null!==a.nTFoot&&C(function(a){a.style.width=""},j);a.oScroll.bCollapse&&""!==a.oScroll.sY&&(d.style.height=d.offsetHeight+a.nTHead.offsetHeight+"px");i=h(a.nTable).outerWidth();if(""===a.oScroll.sX){if(a.nTable.style.width="100%",r&&(h("tbody",d).height()>d.offsetHeight||"scroll"==h(d).css("overflow-y")))a.nTable.style.width=q(h(a.nTable).outerWidth()-a.oScroll.iBarWidth)}else""!==a.oScroll.sXInner?a.nTable.style.width= q(a.oScroll.sXInner):i==h(d).width()&&h(d).height()<h(a.nTable).height()?(a.nTable.style.width=q(i-a.oScroll.iBarWidth),h(a.nTable).outerWidth()>i-a.oScroll.iBarWidth&&(a.nTable.style.width=q(i))):a.nTable.style.width=q(i);i=h(a.nTable).outerWidth();C(s,e);C(function(a){p.push(q(h(a).width()))},e);C(function(a,b){a.style.width=p[b]},g);h(e).height(0);null!==a.nTFoot&&(C(s,j),C(function(a){n.push(q(h(a).width()))},j),C(function(a,b){a.style.width=n[b]},o),h(j).height(0));C(function(a,b){a.innerHTML= "";a.style.width=p[b]},e);null!==a.nTFoot&&C(function(a,b){a.innerHTML="";a.style.width=n[b]},j);if(h(a.nTable).outerWidth()<i){g=d.scrollHeight>d.offsetHeight||"scroll"==h(d).css("overflow-y")?i+a.oScroll.iBarWidth:i;if(r&&(d.scrollHeight>d.offsetHeight||"scroll"==h(d).css("overflow-y")))a.nTable.style.width=q(g-a.oScroll.iBarWidth);d.style.width=q(g);a.nScrollHead.style.width=q(g);null!==a.nTFoot&&(a.nScrollFoot.style.width=q(g));""===a.oScroll.sX?D(a,1,"The table cannot fit into the current element which will cause column misalignment. The table has been drawn at its minimum possible width."): ""!==a.oScroll.sXInner&&D(a,1,"The table cannot fit into the current element which will cause column misalignment. Increase the sScrollXInner value or remove it to allow automatic calculation")}else d.style.width=q("100%"),a.nScrollHead.style.width=q("100%"),null!==a.nTFoot&&(a.nScrollFoot.style.width=q("100%"));""===a.oScroll.sY&&r&&(d.style.height=q(a.nTable.offsetHeight+a.oScroll.iBarWidth));""!==a.oScroll.sY&&a.oScroll.bCollapse&&(d.style.height=q(a.oScroll.sY),r=""!==a.oScroll.sX&&a.nTable.offsetWidth> d.offsetWidth?a.oScroll.iBarWidth:0,a.nTable.offsetHeight<d.offsetHeight&&(d.style.height=q(a.nTable.offsetHeight+r)));r=h(a.nTable).outerWidth();c.style.width=q(r);b.style.width=q(r);c=h(a.nTable).height()>d.clientHeight||"scroll"==h(d).css("overflow-y");b.style.paddingRight=c?a.oScroll.iBarWidth+"px":"0px";null!==a.nTFoot&&(R.style.width=q(r),l.style.width=q(r),l.style.paddingRight=c?a.oScroll.iBarWidth+"px":"0px");h(d).scroll();if(a.bSorted||a.bFiltered)d.scrollTop=0}function C(a,b,c){for(var d= 0,i=0,f=b.length,g,e;i<f;){g=b[i].firstChild;for(e=c?c[i].firstChild:null;g;)1===g.nodeType&&(c?a(g,e,d):a(g,d),d++),g=g.nextSibling,e=c?e.nextSibling:null;i++}}function Ma(a,b){if(!a||null===a||""===a)return 0;b||(b=l.body);var c,d=l.createElement("div");d.style.width=q(a);b.appendChild(d);c=d.offsetWidth;b.removeChild(d);return c}function da(a){var b=0,c,d=0,i=a.aoColumns.length,f,e,j=h("th",a.nTHead),o=a.nTable.getAttribute("width");e=a.nTable.parentNode;for(f=0;f<i;f++)a.aoColumns[f].bVisible&& (d++,null!==a.aoColumns[f].sWidth&&(c=Ma(a.aoColumns[f].sWidthOrig,e),null!==c&&(a.aoColumns[f].sWidth=q(c)),b++));if(i==j.length&&0===b&&d==i&&""===a.oScroll.sX&&""===a.oScroll.sY)for(f=0;f<a.aoColumns.length;f++)c=h(j[f]).width(),null!==c&&(a.aoColumns[f].sWidth=q(c));else{b=a.nTable.cloneNode(!1);f=a.nTHead.cloneNode(!0);d=l.createElement("tbody");c=l.createElement("tr");b.removeAttribute("id");b.appendChild(f);null!==a.nTFoot&&(b.appendChild(a.nTFoot.cloneNode(!0)),C(function(a){a.style.width= ""},b.getElementsByTagName("tr")));b.appendChild(d);d.appendChild(c);d=h("thead th",b);0===d.length&&(d=h("tbody tr:eq(0)>td",b));j=N(a,f);for(f=d=0;f<i;f++){var k=a.aoColumns[f];k.bVisible&&null!==k.sWidthOrig&&""!==k.sWidthOrig?j[f-d].style.width=q(k.sWidthOrig):k.bVisible?j[f-d].style.width="":d++}for(f=0;f<i;f++)a.aoColumns[f].bVisible&&(d=Na(a,f),null!==d&&(d=d.cloneNode(!0),""!==a.aoColumns[f].sContentPadding&&(d.innerHTML+=a.aoColumns[f].sContentPadding),c.appendChild(d)));e.appendChild(b); ""!==a.oScroll.sX&&""!==a.oScroll.sXInner?b.style.width=q(a.oScroll.sXInner):""!==a.oScroll.sX?(b.style.width="",h(b).width()<e.offsetWidth&&(b.style.width=q(e.offsetWidth))):""!==a.oScroll.sY?b.style.width=q(e.offsetWidth):o&&(b.style.width=q(o));b.style.visibility="hidden";Oa(a,b);i=h("tbody tr:eq(0)",b).children();0===i.length&&(i=N(a,h("thead",b)[0]));if(""!==a.oScroll.sX){for(f=d=e=0;f<a.aoColumns.length;f++)a.aoColumns[f].bVisible&&(e=null===a.aoColumns[f].sWidthOrig?e+h(i[d]).outerWidth(): e+(parseInt(a.aoColumns[f].sWidth.replace("px",""),10)+(h(i[d]).outerWidth()-h(i[d]).width())),d++);b.style.width=q(e);a.nTable.style.width=q(e)}for(f=d=0;f<a.aoColumns.length;f++)a.aoColumns[f].bVisible&&(e=h(i[d]).width(),null!==e&&0<e&&(a.aoColumns[f].sWidth=q(e)),d++);i=h(b).css("width");a.nTable.style.width=-1!==i.indexOf("%")?i:q(h(b).outerWidth());b.parentNode.removeChild(b)}o&&(a.nTable.style.width=q(o))}function Oa(a,b){""===a.oScroll.sX&&""!==a.oScroll.sY?(h(b).width(),b.style.width=q(h(b).outerWidth()- a.oScroll.iBarWidth)):""!==a.oScroll.sX&&(b.style.width=q(h(b).outerWidth()))}function Na(a,b){var c=Pa(a,b);if(0>c)return null;if(null===a.aoData[c].nTr){var d=l.createElement("td");d.innerHTML=v(a,c,b,"");return d}return J(a,c)[b]}function Pa(a,b){for(var c=-1,d=-1,i=0;i<a.aoData.length;i++){var e=v(a,i,b,"display")+"",e=e.replace(/<.*?>/g,"");e.length>c&&(c=e.length,d=i)}return d}function q(a){if(null===a)return"0px";if("number"==typeof a)return 0>a?"0px":a+"px";var b=a.charCodeAt(a.length-1); return 48>b||57<b?a:a+"px"}function Qa(){var a=l.createElement("p"),b=a.style;b.width="100%";b.height="200px";b.padding="0px";var c=l.createElement("div"),b=c.style;b.position="absolute";b.top="0px";b.left="0px";b.visibility="hidden";b.width="200px";b.height="150px";b.padding="0px";b.overflow="hidden";c.appendChild(a);l.body.appendChild(c);b=a.offsetWidth;c.style.overflow="scroll";a=a.offsetWidth;b==a&&(a=c.clientWidth);l.body.removeChild(c);return b-a}function O(a,b){var c,d,i,e,g,k,o=[],m=[],p= j.ext.oSort,l=a.aoData,q=a.aoColumns,G=a.oLanguage.oAria;if(!a.oFeatures.bServerSide&&(0!==a.aaSorting.length||null!==a.aaSortingFixed)){o=null!==a.aaSortingFixed?a.aaSortingFixed.concat(a.aaSorting):a.aaSorting.slice();for(c=0;c<o.length;c++)if(d=o[c][0],i=R(a,d),e=a.aoColumns[d].sSortDataType,j.ext.afnSortData[e])if(g=j.ext.afnSortData[e].call(a.oInstance,a,d,i),g.length===l.length){i=0;for(e=l.length;i<e;i++)F(a,i,d,g[i])}else D(a,0,"Returned data sort array (col "+d+") is the wrong length");c= 0;for(d=a.aiDisplayMaster.length;c<d;c++)m[a.aiDisplayMaster[c]]=c;var r=o.length,s;c=0;for(d=l.length;c<d;c++)for(i=0;i<r;i++){s=q[o[i][0]].aDataSort;g=0;for(k=s.length;g<k;g++)e=q[s[g]].sType,e=p[(e?e:"string")+"-pre"],l[c]._aSortData[s[g]]=e?e(v(a,c,s[g],"sort")):v(a,c,s[g],"sort")}a.aiDisplayMaster.sort(function(a,b){var c,d,e,i,f;for(c=0;c<r;c++){f=q[o[c][0]].aDataSort;d=0;for(e=f.length;d<e;d++)if(i=q[f[d]].sType,i=p[(i?i:"string")+"-"+o[c][1]](l[a]._aSortData[f[d]],l[b]._aSortData[f[d]]),0!== i)return i}return p["numeric-asc"](m[a],m[b])})}(b===n||b)&&!a.oFeatures.bDeferRender&&P(a);c=0;for(d=a.aoColumns.length;c<d;c++)e=q[c].sTitle.replace(/<.*?>/g,""),i=q[c].nTh,i.removeAttribute("aria-sort"),i.removeAttribute("aria-label"),q[c].bSortable?0<o.length&&o[0][0]==c?(i.setAttribute("aria-sort","asc"==o[0][1]?"ascending":"descending"),i.setAttribute("aria-label",e+("asc"==(q[c].asSorting[o[0][2]+1]?q[c].asSorting[o[0][2]+1]:q[c].asSorting[0])?G.sSortAscending:G.sSortDescending))):i.setAttribute("aria-label", e+("asc"==q[c].asSorting[0]?G.sSortAscending:G.sSortDescending)):i.setAttribute("aria-label",e);a.bSorted=!0;h(a.oInstance).trigger("sort",a);a.oFeatures.bFilter?K(a,a.oPreviousSearch,1):(a.aiDisplay=a.aiDisplayMaster.slice(),a._iDisplayStart=0,y(a),x(a))}function ia(a,b,c,d){Ra(b,{},function(b){if(!1!==a.aoColumns[c].bSortable){var e=function(){var d,e;if(b.shiftKey){for(var f=!1,h=0;h<a.aaSorting.length;h++)if(a.aaSorting[h][0]==c){f=!0;d=a.aaSorting[h][0];e=a.aaSorting[h][2]+1;a.aoColumns[d].asSorting[e]? (a.aaSorting[h][1]=a.aoColumns[d].asSorting[e],a.aaSorting[h][2]=e):a.aaSorting.splice(h,1);break}!1===f&&a.aaSorting.push([c,a.aoColumns[c].asSorting[0],0])}else 1==a.aaSorting.length&&a.aaSorting[0][0]==c?(d=a.aaSorting[0][0],e=a.aaSorting[0][2]+1,a.aoColumns[d].asSorting[e]||(e=0),a.aaSorting[0][1]=a.aoColumns[d].asSorting[e],a.aaSorting[0][2]=e):(a.aaSorting.splice(0,a.aaSorting.length),a.aaSorting.push([c,a.aoColumns[c].asSorting[0],0]));O(a)};a.oFeatures.bProcessing?(E(a,!0),setTimeout(function(){e(); a.oFeatures.bServerSide||E(a,!1)},0)):e();"function"==typeof d&&d(a)}})}function P(a){var b,c,d,e,f,g=a.aoColumns.length,j=a.oClasses;for(b=0;b<g;b++)a.aoColumns[b].bSortable&&h(a.aoColumns[b].nTh).removeClass(j.sSortAsc+" "+j.sSortDesc+" "+a.aoColumns[b].sSortingClass);c=null!==a.aaSortingFixed?a.aaSortingFixed.concat(a.aaSorting):a.aaSorting.slice();for(b=0;b<a.aoColumns.length;b++)if(a.aoColumns[b].bSortable){f=a.aoColumns[b].sSortingClass;e=-1;for(d=0;d<c.length;d++)if(c[d][0]==b){f="asc"==c[d][1]? j.sSortAsc:j.sSortDesc;e=d;break}h(a.aoColumns[b].nTh).addClass(f);a.bJUI&&(f=h("span."+j.sSortIcon,a.aoColumns[b].nTh),f.removeClass(j.sSortJUIAsc+" "+j.sSortJUIDesc+" "+j.sSortJUI+" "+j.sSortJUIAscAllowed+" "+j.sSortJUIDescAllowed),f.addClass(-1==e?a.aoColumns[b].sSortingClassJUI:"asc"==c[e][1]?j.sSortJUIAsc:j.sSortJUIDesc))}else h(a.aoColumns[b].nTh).addClass(a.aoColumns[b].sSortingClass);f=j.sSortColumn;if(a.oFeatures.bSort&&a.oFeatures.bSortClasses){a=J(a);e=[];for(b=0;b<g;b++)e.push("");b=0; for(d=1;b<c.length;b++)j=parseInt(c[b][0],10),e[j]=f+d,3>d&&d++;f=RegExp(f+"[123]");var o;b=0;for(c=a.length;b<c;b++)j=b%g,d=a[b].className,o=e[j],j=d.replace(f,o),j!=d?a[b].className=h.trim(j):0<o.length&&-1==d.indexOf(o)&&(a[b].className=d+" "+o)}}function ra(a){if(a.oFeatures.bStateSave&&!a.bDestroying){var b,c;b=a.oScroll.bInfinite;var d={iCreate:(new Date).getTime(),iStart:b?0:a._iDisplayStart,iEnd:b?a._iDisplayLength:a._iDisplayEnd,iLength:a._iDisplayLength,aaSorting:h.extend(!0,[],a.aaSorting), oSearch:h.extend(!0,{},a.oPreviousSearch),aoSearchCols:h.extend(!0,[],a.aoPreSearchCols),abVisCols:[]};b=0;for(c=a.aoColumns.length;b<c;b++)d.abVisCols.push(a.aoColumns[b].bVisible);A(a,"aoStateSaveParams","stateSaveParams",[a,d]);a.fnStateSave.call(a.oInstance,a,d)}}function Sa(a,b){if(a.oFeatures.bStateSave){var c=a.fnStateLoad.call(a.oInstance,a);if(c){var d=A(a,"aoStateLoadParams","stateLoadParams",[a,c]);if(-1===h.inArray(!1,d)){a.oLoadedState=h.extend(!0,{},c);a._iDisplayStart=c.iStart;a.iInitDisplayStart= c.iStart;a._iDisplayEnd=c.iEnd;a._iDisplayLength=c.iLength;a.aaSorting=c.aaSorting.slice();a.saved_aaSorting=c.aaSorting.slice();h.extend(a.oPreviousSearch,c.oSearch);h.extend(!0,a.aoPreSearchCols,c.aoSearchCols);b.saved_aoColumns=[];for(d=0;d<c.abVisCols.length;d++)b.saved_aoColumns[d]={},b.saved_aoColumns[d].bVisible=c.abVisCols[d];A(a,"aoStateLoaded","stateLoaded",[a,c])}}}}function s(a){for(var b=0;b<j.settings.length;b++)if(j.settings[b].nTable===a)return j.settings[b];return null}function T(a){for(var b= [],a=a.aoData,c=0,d=a.length;c<d;c++)null!==a[c].nTr&&b.push(a[c].nTr);return b}function J(a,b){var c=[],d,e,f,g,h,j;e=0;var o=a.aoData.length;b!==n&&(e=b,o=b+1);for(f=e;f<o;f++)if(j=a.aoData[f],null!==j.nTr){e=[];for(d=j.nTr.firstChild;d;)g=d.nodeName.toLowerCase(),("td"==g||"th"==g)&&e.push(d),d=d.nextSibling;g=d=0;for(h=a.aoColumns.length;g<h;g++)a.aoColumns[g].bVisible?c.push(e[g-d]):(c.push(j._anHidden[g]),d++)}return c}function D(a,b,c){a=null===a?"DataTables warning: "+c:"DataTables warning (table id = '"+ a.sTableId+"'): "+c;if(0===b)if("alert"==j.ext.sErrMode)alert(a);else throw Error(a);else X.console&&console.log&&console.log(a)}function p(a,b,c,d){d===n&&(d=c);b[c]!==n&&(a[d]=b[c])}function Ta(a,b){var c,d;for(d in b)b.hasOwnProperty(d)&&(c=b[d],"object"===typeof e[d]&&null!==c&&!1===h.isArray(c)?h.extend(!0,a[d],c):a[d]=c);return a}function Ra(a,b,c){h(a).bind("click.DT",b,function(b){a.blur();c(b)}).bind("keypress.DT",b,function(a){13===a.which&&c(a)}).bind("selectstart.DT",function(){return!1})} function z(a,b,c,d){c&&a[b].push({fn:c,sName:d})}function A(a,b,c,d){for(var b=a[b],e=[],f=b.length-1;0<=f;f--)e.push(b[f].fn.apply(a.oInstance,d));null!==c&&h(a.oInstance).trigger(c,d);return e}function Ua(a){var b=h('<div style="position:absolute; top:0; left:0; height:1px; width:1px; overflow:hidden"><div style="position:absolute; top:1px; left:1px; width:100px; overflow:scroll;"><div id="DT_BrowserTest" style="width:100%; height:10px;"></div></div></div>')[0];l.body.appendChild(b);a.oBrowser.bScrollOversize= 100===h("#DT_BrowserTest",b)[0].offsetWidth?!0:!1;l.body.removeChild(b)}function Va(a){return function(){var b=[s(this[j.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return j.ext.oApi[a].apply(this,b)}}var U=/\[.*?\]$/,Wa=X.JSON?JSON.stringify:function(a){var b=typeof a;if("object"!==b||null===a)return"string"===b&&(a='"'+a+'"'),a+"";var c,d,e=[],f=h.isArray(a);for(c in a)d=a[c],b=typeof d,"string"===b?d='"'+d+'"':"object"===b&&null!==d&&(d=Wa(d)),e.push((f?"":'"'+c+'":')+d);return(f? "[":"{")+e+(f?"]":"}")};this.$=function(a,b){var c,d,e=[],f;d=s(this[j.ext.iApiIndex]);var g=d.aoData,o=d.aiDisplay,k=d.aiDisplayMaster;b||(b={});b=h.extend({},{filter:"none",order:"current",page:"all"},b);if("current"==b.page){c=d._iDisplayStart;for(d=d.fnDisplayEnd();c<d;c++)(f=g[o[c]].nTr)&&e.push(f)}else if("current"==b.order&&"none"==b.filter){c=0;for(d=k.length;c<d;c++)(f=g[k[c]].nTr)&&e.push(f)}else if("current"==b.order&&"applied"==b.filter){c=0;for(d=o.length;c<d;c++)(f=g[o[c]].nTr)&&e.push(f)}else if("original"== b.order&&"none"==b.filter){c=0;for(d=g.length;c<d;c++)(f=g[c].nTr)&&e.push(f)}else if("original"==b.order&&"applied"==b.filter){c=0;for(d=g.length;c<d;c++)f=g[c].nTr,-1!==h.inArray(c,o)&&f&&e.push(f)}else D(d,1,"Unknown selection options");e=h(e);c=e.filter(a);e=e.find(a);return h([].concat(h.makeArray(c),h.makeArray(e)))};this._=function(a,b){var c=[],d,e,f=this.$(a,b);d=0;for(e=f.length;d<e;d++)c.push(this.fnGetData(f[d]));return c};this.fnAddData=function(a,b){if(0===a.length)return[];var c=[], d,e=s(this[j.ext.iApiIndex]);if("object"===typeof a[0]&&null!==a[0])for(var f=0;f<a.length;f++){d=H(e,a[f]);if(-1==d)return c;c.push(d)}else{d=H(e,a);if(-1==d)return c;c.push(d)}e.aiDisplay=e.aiDisplayMaster.slice();(b===n||b)&&aa(e);return c};this.fnAdjustColumnSizing=function(a){var b=s(this[j.ext.iApiIndex]);k(b);a===n||a?this.fnDraw(!1):(""!==b.oScroll.sX||""!==b.oScroll.sY)&&this.oApi._fnScrollDraw(b)};this.fnClearTable=function(a){var b=s(this[j.ext.iApiIndex]);ga(b);(a===n||a)&&x(b)};this.fnClose= function(a){for(var b=s(this[j.ext.iApiIndex]),c=0;c<b.aoOpenRows.length;c++)if(b.aoOpenRows[c].nParent==a)return(a=b.aoOpenRows[c].nTr.parentNode)&&a.removeChild(b.aoOpenRows[c].nTr),b.aoOpenRows.splice(c,1),0;return 1};this.fnDeleteRow=function(a,b,c){var d=s(this[j.ext.iApiIndex]),e,f,a="object"===typeof a?I(d,a):a,g=d.aoData.splice(a,1);e=0;for(f=d.aoData.length;e<f;e++)null!==d.aoData[e].nTr&&(d.aoData[e].nTr._DT_RowIndex=e);e=h.inArray(a,d.aiDisplay);d.asDataSearch.splice(e,1);ha(d.aiDisplayMaster, a);ha(d.aiDisplay,a);"function"===typeof b&&b.call(this,d,g);d._iDisplayStart>=d.fnRecordsDisplay()&&(d._iDisplayStart-=d._iDisplayLength,0>d._iDisplayStart&&(d._iDisplayStart=0));if(c===n||c)y(d),x(d);return g};this.fnDestroy=function(a){var b=s(this[j.ext.iApiIndex]),c=b.nTableWrapper.parentNode,d=b.nTBody,i,f,a=a===n?!1:a;b.bDestroying=!0;A(b,"aoDestroyCallback","destroy",[b]);if(!a){i=0;for(f=b.aoColumns.length;i<f;i++)!1===b.aoColumns[i].bVisible&&this.fnSetColumnVis(i,!0)}h(b.nTableWrapper).find("*").andSelf().unbind(".DT"); h("tbody>tr>td."+b.oClasses.sRowEmpty,b.nTable).parent().remove();b.nTable!=b.nTHead.parentNode&&(h(b.nTable).children("thead").remove(),b.nTable.appendChild(b.nTHead));b.nTFoot&&b.nTable!=b.nTFoot.parentNode&&(h(b.nTable).children("tfoot").remove(),b.nTable.appendChild(b.nTFoot));b.nTable.parentNode.removeChild(b.nTable);h(b.nTableWrapper).remove();b.aaSorting=[];b.aaSortingFixed=[];P(b);h(T(b)).removeClass(b.asStripeClasses.join(" "));h("th, td",b.nTHead).removeClass([b.oClasses.sSortable,b.oClasses.sSortableAsc, b.oClasses.sSortableDesc,b.oClasses.sSortableNone].join(" "));b.bJUI&&(h("th span."+b.oClasses.sSortIcon+", td span."+b.oClasses.sSortIcon,b.nTHead).remove(),h("th, td",b.nTHead).each(function(){var a=h("div."+b.oClasses.sSortJUIWrapper,this),c=a.contents();h(this).append(c);a.remove()}));!a&&b.nTableReinsertBefore?c.insertBefore(b.nTable,b.nTableReinsertBefore):a||c.appendChild(b.nTable);i=0;for(f=b.aoData.length;i<f;i++)null!==b.aoData[i].nTr&&d.appendChild(b.aoData[i].nTr);!0===b.oFeatures.bAutoWidth&& (b.nTable.style.width=q(b.sDestroyWidth));if(f=b.asDestroyStripes.length){a=h(d).children("tr");for(i=0;i<f;i++)a.filter(":nth-child("+f+"n + "+i+")").addClass(b.asDestroyStripes[i])}i=0;for(f=j.settings.length;i<f;i++)j.settings[i]==b&&j.settings.splice(i,1);e=b=null};this.fnDraw=function(a){var b=s(this[j.ext.iApiIndex]);!1===a?(y(b),x(b)):aa(b)};this.fnFilter=function(a,b,c,d,e,f){var g=s(this[j.ext.iApiIndex]);if(g.oFeatures.bFilter){if(c===n||null===c)c=!1;if(d===n||null===d)d=!0;if(e===n||null=== e)e=!0;if(f===n||null===f)f=!0;if(b===n||null===b){if(K(g,{sSearch:a+"",bRegex:c,bSmart:d,bCaseInsensitive:f},1),e&&g.aanFeatures.f){b=g.aanFeatures.f;c=0;for(d=b.length;c<d;c++)try{b[c]._DT_Input!=l.activeElement&&h(b[c]._DT_Input).val(a)}catch(o){h(b[c]._DT_Input).val(a)}}}else h.extend(g.aoPreSearchCols[b],{sSearch:a+"",bRegex:c,bSmart:d,bCaseInsensitive:f}),K(g,g.oPreviousSearch,1)}};this.fnGetData=function(a,b){var c=s(this[j.ext.iApiIndex]);if(a!==n){var d=a;if("object"===typeof a){var e=a.nodeName.toLowerCase(); "tr"===e?d=I(c,a):"td"===e&&(d=I(c,a.parentNode),b=fa(c,d,a))}return b!==n?v(c,d,b,""):c.aoData[d]!==n?c.aoData[d]._aData:null}return Z(c)};this.fnGetNodes=function(a){var b=s(this[j.ext.iApiIndex]);return a!==n?b.aoData[a]!==n?b.aoData[a].nTr:null:T(b)};this.fnGetPosition=function(a){var b=s(this[j.ext.iApiIndex]),c=a.nodeName.toUpperCase();return"TR"==c?I(b,a):"TD"==c||"TH"==c?(c=I(b,a.parentNode),a=fa(b,c,a),[c,R(b,a),a]):null};this.fnIsOpen=function(a){for(var b=s(this[j.ext.iApiIndex]),c=0;c< b.aoOpenRows.length;c++)if(b.aoOpenRows[c].nParent==a)return!0;return!1};this.fnOpen=function(a,b,c){var d=s(this[j.ext.iApiIndex]),e=T(d);if(-1!==h.inArray(a,e)){this.fnClose(a);var e=l.createElement("tr"),f=l.createElement("td");e.appendChild(f);f.className=c;f.colSpan=t(d);"string"===typeof b?f.innerHTML=b:h(f).html(b);b=h("tr",d.nTBody);-1!=h.inArray(a,b)&&h(e).insertAfter(a);d.aoOpenRows.push({nTr:e,nParent:a});return e}};this.fnPageChange=function(a,b){var c=s(this[j.ext.iApiIndex]);qa(c,a); y(c);(b===n||b)&&x(c)};this.fnSetColumnVis=function(a,b,c){var d=s(this[j.ext.iApiIndex]),e,f,g=d.aoColumns,h=d.aoData,o,m;if(g[a].bVisible!=b){if(b){for(e=f=0;e<a;e++)g[e].bVisible&&f++;m=f>=t(d);if(!m)for(e=a;e<g.length;e++)if(g[e].bVisible){o=e;break}e=0;for(f=h.length;e<f;e++)null!==h[e].nTr&&(m?h[e].nTr.appendChild(h[e]._anHidden[a]):h[e].nTr.insertBefore(h[e]._anHidden[a],J(d,e)[o]))}else{e=0;for(f=h.length;e<f;e++)null!==h[e].nTr&&(o=J(d,e)[a],h[e]._anHidden[a]=o,o.parentNode.removeChild(o))}g[a].bVisible= b;W(d,d.aoHeader);d.nTFoot&&W(d,d.aoFooter);e=0;for(f=d.aoOpenRows.length;e<f;e++)d.aoOpenRows[e].nTr.colSpan=t(d);if(c===n||c)k(d),x(d);ra(d)}};this.fnSettings=function(){return s(this[j.ext.iApiIndex])};this.fnSort=function(a){var b=s(this[j.ext.iApiIndex]);b.aaSorting=a;O(b)};this.fnSortListener=function(a,b,c){ia(s(this[j.ext.iApiIndex]),a,b,c)};this.fnUpdate=function(a,b,c,d,e){var f=s(this[j.ext.iApiIndex]),b="object"===typeof b?I(f,b):b;if(h.isArray(a)&&c===n){f.aoData[b]._aData=a.slice(); for(c=0;c<f.aoColumns.length;c++)this.fnUpdate(v(f,b,c),b,c,!1,!1)}else if(h.isPlainObject(a)&&c===n){f.aoData[b]._aData=h.extend(!0,{},a);for(c=0;c<f.aoColumns.length;c++)this.fnUpdate(v(f,b,c),b,c,!1,!1)}else{F(f,b,c,a);var a=v(f,b,c,"display"),g=f.aoColumns[c];null!==g.fnRender&&(a=S(f,b,c),g.bUseRendered&&F(f,b,c,a));null!==f.aoData[b].nTr&&(J(f,b)[c].innerHTML=a)}c=h.inArray(b,f.aiDisplay);f.asDataSearch[c]=na(f,Y(f,b,"filter",r(f,"bSearchable")));(e===n||e)&&k(f);(d===n||d)&&aa(f);return 0}; this.fnVersionCheck=j.ext.fnVersionCheck;this.oApi={_fnExternApiFunc:Va,_fnInitialise:ba,_fnInitComplete:$,_fnLanguageCompat:pa,_fnAddColumn:o,_fnColumnOptions:m,_fnAddData:H,_fnCreateTr:ea,_fnGatherData:ua,_fnBuildHead:va,_fnDrawHead:W,_fnDraw:x,_fnReDraw:aa,_fnAjaxUpdate:wa,_fnAjaxParameters:Ea,_fnAjaxUpdateDraw:Fa,_fnServerParams:ka,_fnAddOptionsHtml:xa,_fnFeatureHtmlTable:Ba,_fnScrollDraw:La,_fnAdjustColumnSizing:k,_fnFeatureHtmlFilter:za,_fnFilterComplete:K,_fnFilterCustom:Ia,_fnFilterColumn:Ha, _fnFilter:Ga,_fnBuildSearchArray:la,_fnBuildSearchRow:na,_fnFilterCreateSearch:ma,_fnDataToSearch:Ja,_fnSort:O,_fnSortAttachListener:ia,_fnSortingClasses:P,_fnFeatureHtmlPaginate:Da,_fnPageChange:qa,_fnFeatureHtmlInfo:Ca,_fnUpdateInfo:Ka,_fnFeatureHtmlLength:ya,_fnFeatureHtmlProcessing:Aa,_fnProcessingDisplay:E,_fnVisibleToColumnIndex:G,_fnColumnIndexToVisible:R,_fnNodeToDataIndex:I,_fnVisbleColumns:t,_fnCalculateEnd:y,_fnConvertToWidth:Ma,_fnCalculateColumnWidths:da,_fnScrollingWidthAdjust:Oa,_fnGetWidestNode:Na, _fnGetMaxLenString:Pa,_fnStringToCss:q,_fnDetectType:B,_fnSettingsFromNode:s,_fnGetDataMaster:Z,_fnGetTrNodes:T,_fnGetTdNodes:J,_fnEscapeRegex:oa,_fnDeleteIndex:ha,_fnReOrderIndex:u,_fnColumnOrdering:M,_fnLog:D,_fnClearTable:ga,_fnSaveState:ra,_fnLoadState:Sa,_fnCreateCookie:function(a,b,c,d,e){var f=new Date;f.setTime(f.getTime()+1E3*c);var c=X.location.pathname.split("/"),a=a+"_"+c.pop().replace(/[\/:]/g,"").toLowerCase(),g;null!==e?(g="function"===typeof h.parseJSON?h.parseJSON(b):eval("("+b+")"), b=e(a,g,f.toGMTString(),c.join("/")+"/")):b=a+"="+encodeURIComponent(b)+"; expires="+f.toGMTString()+"; path="+c.join("/")+"/";a=l.cookie.split(";");e=b.split(";")[0].length;f=[];if(4096<e+l.cookie.length+10){for(var j=0,o=a.length;j<o;j++)if(-1!=a[j].indexOf(d)){var k=a[j].split("=");try{(g=eval("("+decodeURIComponent(k[1])+")"))&&g.iCreate&&f.push({name:k[0],time:g.iCreate})}catch(m){}}for(f.sort(function(a,b){return b.time-a.time});4096<e+l.cookie.length+10;){if(0===f.length)return;d=f.pop();l.cookie= d.name+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path="+c.join("/")+"/"}}l.cookie=b},_fnReadCookie:function(a){for(var b=X.location.pathname.split("/"),a=a+"_"+b[b.length-1].replace(/[\/:]/g,"").toLowerCase()+"=",b=l.cookie.split(";"),c=0;c<b.length;c++){for(var d=b[c];" "==d.charAt(0);)d=d.substring(1,d.length);if(0===d.indexOf(a))return decodeURIComponent(d.substring(a.length,d.length))}return null},_fnDetectHeader:V,_fnGetUniqueThs:N,_fnScrollBarWidth:Qa,_fnApplyToChildren:C,_fnMap:p,_fnGetRowData:Y, _fnGetCellData:v,_fnSetCellData:F,_fnGetObjectDataFn:Q,_fnSetObjectDataFn:L,_fnApplyColumnDefs:ta,_fnBindAction:Ra,_fnExtend:Ta,_fnCallbackReg:z,_fnCallbackFire:A,_fnJsonString:Wa,_fnRender:S,_fnNodeToColumnIndex:fa,_fnInfoMacros:ja,_fnBrowserDetect:Ua,_fnGetColumns:r};h.extend(j.ext.oApi,this.oApi);for(var sa in j.ext.oApi)sa&&(this[sa]=Va(sa));var ca=this;this.each(function(){var a=0,b,c,d;c=this.getAttribute("id");var i=!1,f=!1;if("table"!=this.nodeName.toLowerCase())D(null,0,"Attempted to initialise DataTables on a node which is not a table: "+ this.nodeName);else{a=0;for(b=j.settings.length;a<b;a++){if(j.settings[a].nTable==this){if(e===n||e.bRetrieve)return j.settings[a].oInstance;if(e.bDestroy){j.settings[a].oInstance.fnDestroy();break}else{D(j.settings[a],0,"Cannot reinitialise DataTable.\n\nTo retrieve the DataTables object for this table, pass no arguments or see the docs for bRetrieve and bDestroy");return}}if(j.settings[a].sTableId==this.id){j.settings.splice(a,1);break}}if(null===c||""===c)this.id=c="DataTables_Table_"+j.ext._oExternConfig.iNextUnique++; var g=h.extend(!0,{},j.models.oSettings,{nTable:this,oApi:ca.oApi,oInit:e,sDestroyWidth:h(this).width(),sInstance:c,sTableId:c});j.settings.push(g);g.oInstance=1===ca.length?ca:h(this).dataTable();e||(e={});e.oLanguage&&pa(e.oLanguage);e=Ta(h.extend(!0,{},j.defaults),e);p(g.oFeatures,e,"bPaginate");p(g.oFeatures,e,"bLengthChange");p(g.oFeatures,e,"bFilter");p(g.oFeatures,e,"bSort");p(g.oFeatures,e,"bInfo");p(g.oFeatures,e,"bProcessing");p(g.oFeatures,e,"bAutoWidth");p(g.oFeatures,e,"bSortClasses"); p(g.oFeatures,e,"bServerSide");p(g.oFeatures,e,"bDeferRender");p(g.oScroll,e,"sScrollX","sX");p(g.oScroll,e,"sScrollXInner","sXInner");p(g.oScroll,e,"sScrollY","sY");p(g.oScroll,e,"bScrollCollapse","bCollapse");p(g.oScroll,e,"bScrollInfinite","bInfinite");p(g.oScroll,e,"iScrollLoadGap","iLoadGap");p(g.oScroll,e,"bScrollAutoCss","bAutoCss");p(g,e,"asStripeClasses");p(g,e,"asStripClasses","asStripeClasses");p(g,e,"fnServerData");p(g,e,"fnFormatNumber");p(g,e,"sServerMethod");p(g,e,"aaSorting");p(g, e,"aaSortingFixed");p(g,e,"aLengthMenu");p(g,e,"sPaginationType");p(g,e,"sAjaxSource");p(g,e,"sAjaxDataProp");p(g,e,"iCookieDuration");p(g,e,"sCookiePrefix");p(g,e,"sDom");p(g,e,"bSortCellsTop");p(g,e,"iTabIndex");p(g,e,"oSearch","oPreviousSearch");p(g,e,"aoSearchCols","aoPreSearchCols");p(g,e,"iDisplayLength","_iDisplayLength");p(g,e,"bJQueryUI","bJUI");p(g,e,"fnCookieCallback");p(g,e,"fnStateLoad");p(g,e,"fnStateSave");p(g.oLanguage,e,"fnInfoCallback");z(g,"aoDrawCallback",e.fnDrawCallback,"user"); z(g,"aoServerParams",e.fnServerParams,"user");z(g,"aoStateSaveParams",e.fnStateSaveParams,"user");z(g,"aoStateLoadParams",e.fnStateLoadParams,"user");z(g,"aoStateLoaded",e.fnStateLoaded,"user");z(g,"aoRowCallback",e.fnRowCallback,"user");z(g,"aoRowCreatedCallback",e.fnCreatedRow,"user");z(g,"aoHeaderCallback",e.fnHeaderCallback,"user");z(g,"aoFooterCallback",e.fnFooterCallback,"user");z(g,"aoInitComplete",e.fnInitComplete,"user");z(g,"aoPreDrawCallback",e.fnPreDrawCallback,"user");g.oFeatures.bServerSide&& g.oFeatures.bSort&&g.oFeatures.bSortClasses?z(g,"aoDrawCallback",P,"server_side_sort_classes"):g.oFeatures.bDeferRender&&z(g,"aoDrawCallback",P,"defer_sort_classes");e.bJQueryUI?(h.extend(g.oClasses,j.ext.oJUIClasses),e.sDom===j.defaults.sDom&&"lfrtip"===j.defaults.sDom&&(g.sDom='<"H"lfr>t<"F"ip>')):h.extend(g.oClasses,j.ext.oStdClasses);h(this).addClass(g.oClasses.sTable);if(""!==g.oScroll.sX||""!==g.oScroll.sY)g.oScroll.iBarWidth=Qa();g.iInitDisplayStart===n&&(g.iInitDisplayStart=e.iDisplayStart, g._iDisplayStart=e.iDisplayStart);e.bStateSave&&(g.oFeatures.bStateSave=!0,Sa(g,e),z(g,"aoDrawCallback",ra,"state_save"));null!==e.iDeferLoading&&(g.bDeferLoading=!0,a=h.isArray(e.iDeferLoading),g._iRecordsDisplay=a?e.iDeferLoading[0]:e.iDeferLoading,g._iRecordsTotal=a?e.iDeferLoading[1]:e.iDeferLoading);null!==e.aaData&&(f=!0);""!==e.oLanguage.sUrl?(g.oLanguage.sUrl=e.oLanguage.sUrl,h.getJSON(g.oLanguage.sUrl,null,function(a){pa(a);h.extend(true,g.oLanguage,e.oLanguage,a);ba(g)}),i=!0):h.extend(!0, g.oLanguage,e.oLanguage);null===e.asStripeClasses&&(g.asStripeClasses=[g.oClasses.sStripeOdd,g.oClasses.sStripeEven]);b=g.asStripeClasses.length;g.asDestroyStripes=[];if(b){c=!1;d=h(this).children("tbody").children("tr:lt("+b+")");for(a=0;a<b;a++)d.hasClass(g.asStripeClasses[a])&&(c=!0,g.asDestroyStripes.push(g.asStripeClasses[a]));c&&d.removeClass(g.asStripeClasses.join(" "))}c=[];a=this.getElementsByTagName("thead");0!==a.length&&(V(g.aoHeader,a[0]),c=N(g));if(null===e.aoColumns){d=[];a=0;for(b= c.length;a<b;a++)d.push(null)}else d=e.aoColumns;a=0;for(b=d.length;a<b;a++)e.saved_aoColumns!==n&&e.saved_aoColumns.length==b&&(null===d[a]&&(d[a]={}),d[a].bVisible=e.saved_aoColumns[a].bVisible),o(g,c?c[a]:null);ta(g,e.aoColumnDefs,d,function(a,b){m(g,a,b)});a=0;for(b=g.aaSorting.length;a<b;a++){g.aaSorting[a][0]>=g.aoColumns.length&&(g.aaSorting[a][0]=0);var k=g.aoColumns[g.aaSorting[a][0]];g.aaSorting[a][2]===n&&(g.aaSorting[a][2]=0);e.aaSorting===n&&g.saved_aaSorting===n&&(g.aaSorting[a][1]= k.asSorting[0]);c=0;for(d=k.asSorting.length;c<d;c++)if(g.aaSorting[a][1]==k.asSorting[c]){g.aaSorting[a][2]=c;break}}P(g);Ua(g);a=h(this).children("caption").each(function(){this._captionSide=h(this).css("caption-side")});b=h(this).children("thead");0===b.length&&(b=[l.createElement("thead")],this.appendChild(b[0]));g.nTHead=b[0];b=h(this).children("tbody");0===b.length&&(b=[l.createElement("tbody")],this.appendChild(b[0]));g.nTBody=b[0];g.nTBody.setAttribute("role","alert");g.nTBody.setAttribute("aria-live", "polite");g.nTBody.setAttribute("aria-relevant","all");b=h(this).children("tfoot");if(0===b.length&&0<a.length&&(""!==g.oScroll.sX||""!==g.oScroll.sY))b=[l.createElement("tfoot")],this.appendChild(b[0]);0<b.length&&(g.nTFoot=b[0],V(g.aoFooter,g.nTFoot));if(f)for(a=0;a<e.aaData.length;a++)H(g,e.aaData[a]);else ua(g);g.aiDisplay=g.aiDisplayMaster.slice();g.bInitialised=!0;!1===i&&ba(g)}});ca=null;return this};j.fnVersionCheck=function(e){for(var h=function(e,h){for(;e.length<h;)e+="0";return e},m=j.ext.sVersion.split("."), e=e.split("."),k="",n="",l=0,t=e.length;l<t;l++)k+=h(m[l],3),n+=h(e[l],3);return parseInt(k,10)>=parseInt(n,10)};j.fnIsDataTable=function(e){for(var h=j.settings,m=0;m<h.length;m++)if(h[m].nTable===e||h[m].nScrollHead===e||h[m].nScrollFoot===e)return!0;return!1};j.fnTables=function(e){var o=[];jQuery.each(j.settings,function(j,k){(!e||!0===e&&h(k.nTable).is(":visible"))&&o.push(k.nTable)});return o};j.version="1.9.4";j.settings=[];j.models={};j.models.ext={afnFiltering:[],afnSortData:[],aoFeatures:[], aTypes:[],fnVersionCheck:j.fnVersionCheck,iApiIndex:0,ofnSearch:{},oApi:{},oStdClasses:{},oJUIClasses:{},oPagination:{},oSort:{},sVersion:j.version,sErrMode:"alert",_oExternConfig:{iNextUnique:0}};j.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0};j.models.oRow={nTr:null,_aData:[],_aSortData:[],_anHidden:[],_sRowStripe:""};j.models.oColumn={aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bUseRendered:null,bVisible:null,_bAutoType:!0,fnCreatedCell:null,fnGetData:null, fnRender:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std",sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null};j.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0, bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollAutoCss:!0,bScrollCollapse:!1,bScrollInfinite:!1,bServerSide:!1,bSort:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1,fnCookieCallback:null,fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(e){if(1E3>e)return e;for(var h=e+"",e=h.split(""),j="",h=h.length,k=0;k<h;k++)0===k%3&&0!==k&&(j=this.oLanguage.sInfoThousands+j),j=e[h-k-1]+j;return j},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null, fnRowCallback:null,fnServerData:function(e,j,m,k){k.jqXHR=h.ajax({url:e,data:j,success:function(e){e.sError&&k.oApi._fnLog(k,0,e.sError);h(k.oInstance).trigger("xhr",[k,e]);m(e)},dataType:"json",cache:!1,type:k.sServerMethod,error:function(e,h){"parsererror"==h&&k.oApi._fnLog(k,0,"DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error.")}})},fnServerParams:null,fnStateLoad:function(e){var e=this.oApi._fnReadCookie(e.sCookiePrefix+e.sInstance),j;try{j= "function"===typeof h.parseJSON?h.parseJSON(e):eval("("+e+")")}catch(m){j=null}return j},fnStateLoadParams:null,fnStateLoaded:null,fnStateSave:function(e,h){this.oApi._fnCreateCookie(e.sCookiePrefix+e.sInstance,this.oApi._fnJsonString(h),e.iCookieDuration,e.sCookiePrefix,e.fnCookieCallback)},fnStateSaveParams:null,iCookieDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iScrollLoadGap:100,iTabIndex:0,oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"}, oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"},sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sInfoThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sUrl:"",sZeroRecords:"No matching records found"},oSearch:h.extend({},j.models.oSearch),sAjaxDataProp:"aaData", sAjaxSource:null,sCookiePrefix:"SpryMedia_DataTables_",sDom:"lfrtip",sPaginationType:"two_button",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET"};j.defaults.columns={aDataSort:null,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bUseRendered:!0,bVisible:!0,fnCreatedCell:null,fnRender:null,iDataSort:-1,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null};j.models.oSettings={oFeatures:{bAutoWidth:null, bDeferRender:null,bFilter:null,bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortClasses:null,bStateSave:null},oScroll:{bAutoCss:null,bCollapse:null,bInfinite:null,iBarWidth:0,iLoadGap:null,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1},aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aoColumns:[],aoHeader:[],aoFooter:[],asDataSearch:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:null, asStripeClasses:null,asDestroyStripes:[],sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,sPaginationType:"two_button",iCookieDuration:0,sCookiePrefix:"",fnCookieCallback:null,aoStateSave:[],aoStateLoad:[], oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,bAjaxDataGet:!0,jqXHR:null,fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iDisplayEnd:10,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return this.oFeatures.bServerSide?parseInt(this._iRecordsTotal,10):this.aiDisplayMaster.length}, fnRecordsDisplay:function(){return this.oFeatures.bServerSide?parseInt(this._iRecordsDisplay,10):this.aiDisplay.length},fnDisplayEnd:function(){return this.oFeatures.bServerSide?!1===this.oFeatures.bPaginate||-1==this._iDisplayLength?this._iDisplayStart+this.aiDisplay.length:Math.min(this._iDisplayStart+this._iDisplayLength,this._iRecordsDisplay):this._iDisplayEnd},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null};j.ext=h.extend(!0,{},j.models.ext);h.extend(j.ext.oStdClasses, {sTable:"dataTable",sPagePrevEnabled:"paginate_enabled_previous",sPagePrevDisabled:"paginate_disabled_previous",sPageNextEnabled:"paginate_enabled_next",sPageNextDisabled:"paginate_disabled_next",sPageJUINext:"",sPageJUIPrev:"",sPageButton:"paginate_button",sPageButtonActive:"paginate_active",sPageButtonStaticDisabled:"paginate_button paginate_button_disabled",sPageFirst:"first",sPagePrevious:"previous",sPageNext:"next",sPageLast:"last",sStripeOdd:"odd",sStripeEven:"even",sRowEmpty:"dataTables_empty", sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"", sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody",sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sFooterTH:"",sJUIHeader:"",sJUIFooter:""});h.extend(j.ext.oJUIClasses,j.ext.oStdClasses,{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",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",sPageLast:"last ui-corner-tr ui-corner-br",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_", sSortAsc:"ui-state-default",sSortDesc:"ui-state-default",sSortable:"ui-state-default",sSortableAsc:"ui-state-default",sSortableDesc:"ui-state-default",sSortableNone:"ui-state-default",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", sScrollHead:"dataTables_scrollHead ui-state-default",sScrollFoot:"dataTables_scrollFoot ui-state-default",sFooterTH:"ui-state-default",sJUIHeader:"fg-toolbar ui-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix",sJUIFooter:"fg-toolbar ui-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"});h.extend(j.ext.oPagination,{two_button:{fnInit:function(e,j,m){var k=e.oLanguage.oPaginate,n=function(h){e.oApi._fnPageChange(e,h.data.action)&&m(e)},k=!e.bJUI?'<a class="'+ e.oClasses.sPagePrevDisabled+'" tabindex="'+e.iTabIndex+'" role="button">'+k.sPrevious+'</a><a class="'+e.oClasses.sPageNextDisabled+'" tabindex="'+e.iTabIndex+'" role="button">'+k.sNext+"</a>":'<a class="'+e.oClasses.sPagePrevDisabled+'" tabindex="'+e.iTabIndex+'" role="button"><span class="'+e.oClasses.sPageJUIPrev+'"></span></a><a class="'+e.oClasses.sPageNextDisabled+'" tabindex="'+e.iTabIndex+'" role="button"><span class="'+e.oClasses.sPageJUINext+'"></span></a>';h(j).append(k);var l=h("a",j), k=l[0],l=l[1];e.oApi._fnBindAction(k,{action:"previous"},n);e.oApi._fnBindAction(l,{action:"next"},n);e.aanFeatures.p||(j.id=e.sTableId+"_paginate",k.id=e.sTableId+"_previous",l.id=e.sTableId+"_next",k.setAttribute("aria-controls",e.sTableId),l.setAttribute("aria-controls",e.sTableId))},fnUpdate:function(e){if(e.aanFeatures.p)for(var h=e.oClasses,j=e.aanFeatures.p,k,l=0,n=j.length;l<n;l++)if(k=j[l].firstChild)k.className=0===e._iDisplayStart?h.sPagePrevDisabled:h.sPagePrevEnabled,k=k.nextSibling, k.className=e.fnDisplayEnd()==e.fnRecordsDisplay()?h.sPageNextDisabled:h.sPageNextEnabled}},iFullNumbersShowPages:5,full_numbers:{fnInit:function(e,j,m){var k=e.oLanguage.oPaginate,l=e.oClasses,n=function(h){e.oApi._fnPageChange(e,h.data.action)&&m(e)};h(j).append('<a tabindex="'+e.iTabIndex+'" class="'+l.sPageButton+" "+l.sPageFirst+'">'+k.sFirst+'</a><a tabindex="'+e.iTabIndex+'" class="'+l.sPageButton+" "+l.sPagePrevious+'">'+k.sPrevious+'</a><span></span><a tabindex="'+e.iTabIndex+'" class="'+ l.sPageButton+" "+l.sPageNext+'">'+k.sNext+'</a><a tabindex="'+e.iTabIndex+'" class="'+l.sPageButton+" "+l.sPageLast+'">'+k.sLast+"</a>");var t=h("a",j),k=t[0],l=t[1],r=t[2],t=t[3];e.oApi._fnBindAction(k,{action:"first"},n);e.oApi._fnBindAction(l,{action:"previous"},n);e.oApi._fnBindAction(r,{action:"next"},n);e.oApi._fnBindAction(t,{action:"last"},n);e.aanFeatures.p||(j.id=e.sTableId+"_paginate",k.id=e.sTableId+"_first",l.id=e.sTableId+"_previous",r.id=e.sTableId+"_next",t.id=e.sTableId+"_last")}, fnUpdate:function(e,o){if(e.aanFeatures.p){var m=j.ext.oPagination.iFullNumbersShowPages,k=Math.floor(m/2),l=Math.ceil(e.fnRecordsDisplay()/e._iDisplayLength),n=Math.ceil(e._iDisplayStart/e._iDisplayLength)+1,t="",r,B=e.oClasses,u,M=e.aanFeatures.p,L=function(h){e.oApi._fnBindAction(this,{page:h+r-1},function(h){e.oApi._fnPageChange(e,h.data.page);o(e);h.preventDefault()})};-1===e._iDisplayLength?n=k=r=1:l<m?(r=1,k=l):n<=k?(r=1,k=m):n>=l-k?(r=l-m+1,k=l):(r=n-Math.ceil(m/2)+1,k=r+m-1);for(m=r;m<=k;m++)t+= n!==m?'<a tabindex="'+e.iTabIndex+'" class="'+B.sPageButton+'">'+e.fnFormatNumber(m)+"</a>":'<a tabindex="'+e.iTabIndex+'" class="'+B.sPageButtonActive+'">'+e.fnFormatNumber(m)+"</a>";m=0;for(k=M.length;m<k;m++)u=M[m],u.hasChildNodes()&&(h("span:eq(0)",u).html(t).children("a").each(L),u=u.getElementsByTagName("a"),u=[u[0],u[1],u[u.length-2],u[u.length-1]],h(u).removeClass(B.sPageButton+" "+B.sPageButtonActive+" "+B.sPageButtonStaticDisabled),h([u[0],u[1]]).addClass(1==n?B.sPageButtonStaticDisabled: B.sPageButton),h([u[2],u[3]]).addClass(0===l||n===l||-1===e._iDisplayLength?B.sPageButtonStaticDisabled:B.sPageButton))}}}});h.extend(j.ext.oSort,{"string-pre":function(e){"string"!=typeof e&&(e=null!==e&&e.toString?e.toString():"");return e.toLowerCase()},"string-asc":function(e,h){return e<h?-1:e>h?1:0},"string-desc":function(e,h){return e<h?1:e>h?-1:0},"html-pre":function(e){return e.replace(/<.*?>/g,"").toLowerCase()},"html-asc":function(e,h){return e<h?-1:e>h?1:0},"html-desc":function(e,h){return e< h?1:e>h?-1:0},"date-pre":function(e){e=Date.parse(e);if(isNaN(e)||""===e)e=Date.parse("01/01/1970 00:00:00");return e},"date-asc":function(e,h){return e-h},"date-desc":function(e,h){return h-e},"numeric-pre":function(e){return"-"==e||""===e?0:1*e},"numeric-asc":function(e,h){return e-h},"numeric-desc":function(e,h){return h-e}});h.extend(j.ext.aTypes,[function(e){if("number"===typeof e)return"numeric";if("string"!==typeof e)return null;var h,j=!1;h=e.charAt(0);if(-1=="0123456789-".indexOf(h))return null; for(var k=1;k<e.length;k++){h=e.charAt(k);if(-1=="0123456789.".indexOf(h))return null;if("."==h){if(j)return null;j=!0}}return"numeric"},function(e){var h=Date.parse(e);return null!==h&&!isNaN(h)||"string"===typeof e&&0===e.length?"date":null},function(e){return"string"===typeof e&&-1!=e.indexOf("<")&&-1!=e.indexOf(">")?"html":null}]);h.fn.DataTable=j;h.fn.dataTable=j;h.fn.dataTableSettings=j.settings;h.fn.dataTableExt=j.ext};"function"===typeof define&&define.amd?define(["jquery"],L):jQuery&&!jQuery.fn.dataTable&& L(jQuery)})(window,document);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/jquery-dataTables-1.9.4.min.js
jquery-dataTables-1.9.4.min.js
!function(t){"use strict";var i=function(t,i){this.init(t,i)};i.prototype={constructor:i,init:function(i,e){var n=this;this.options=e,this.$element=t(i).delegate('[data-dismiss="modal"]',"click.dismiss.modal",t.proxy(this.hide,this)),this.options.remote&&this.$element.find(".modal-body").load(this.options.remote,function(){var i=t.Event("loaded");n.$element.trigger(i)});var s="function"==typeof this.options.manager?this.options.manager.call(this):this.options.manager;(s=s.appendModal?s:t(s).modalmanager().data("modalmanager")).appendModal(this)},toggle:function(){return this[this.isShown?"hide":"show"]()},show:function(){var i=t.Event("show");this.isShown||(this.$element.trigger(i),i.isDefaultPrevented()||(this.escape(),this.tab(),this.options.loading&&this.loading()))},hide:function(i){if(i&&i.preventDefault(),i=t.Event("hide"),this.$element.trigger(i),!this.isShown||i.isDefaultPrevented())return this.isShown=!1;this.isShown=!1,this.escape(),this.tab(),this.isLoading&&this.loading(),t(document).off("focusin.modal"),this.$element.removeClass("in").removeClass("animated").removeClass(this.options.attentionAnimation).removeClass("modal-overflow").attr("aria-hidden",!0),t.support.transition&&this.$element.hasClass("fade")?this.hideWithTransition():this.hideModal()},layout:function(){var i=this.options.height?"height":"max-height",e=this.options.height||this.options.maxHeight;if(this.options.width){this.$element.css("width",this.options.width);var n=this;this.$element.css("margin-left",function(){return/%/gi.test(n.options.width)?-parseInt(n.options.width)/2+"%":-t(this).width()/2+"px"})}else this.$element.css("width",""),this.$element.css("margin-left","");if(this.$element.find(this.options.overflow).css("overflow","").css(i,""),e){var s=this.$element.find(this.options.overflow);void 0===s.css("overflow")&&s.style("overflow","auto","important"),s.style(i,("function"==typeof e?e():e)+"px","important")}t(window).height(),this.$element.height();this.$element.css("margin-top",0).addClass("modal-overflow")},tab:function(){var i=this;this.isShown&&this.options.consumeTab?this.$element.on("keydown.tabindex.modal","[data-tabindex]",function(e){if(e.keyCode&&9==e.keyCode){var n=[],s=Number(t(this).data("tabindex"));i.$element.find("[data-tabindex]:enabled:visible:not([readonly])").each(function(i){n.push(Number(t(this).data("tabindex")))}),n.sort(function(t,i){return t-i});var o=t.inArray(s,n);e.shiftKey?0==o?i.$element.find("[data-tabindex="+n[n.length-1]+"]").focus():i.$element.find("[data-tabindex="+n[o-1]+"]").focus():o<n.length-1?i.$element.find("[data-tabindex="+n[o+1]+"]").focus():i.$element.find("[data-tabindex="+n[0]+"]").focus(),e.preventDefault()}}):this.isShown||this.$element.off("keydown.tabindex.modal")},escape:function(){var t=this;this.isShown&&this.options.keyboard?(this.$element.attr("tabindex")||this.$element.attr("tabindex",-1),this.$element.on("keyup.dismiss.modal",function(i){27==i.which&&t.hide()})):this.isShown||this.$element.off("keyup.dismiss.modal")},hideWithTransition:function(){var i=this,e=setTimeout(function(){i.$element.off(t.support.transition.end),i.hideModal()},500);this.$element.one(t.support.transition.end,function(){clearTimeout(e),i.hideModal()})},hideModal:function(){var t=this.options.height?"height":"max-height";(this.options.height||this.options.maxHeight)&&this.$element.find(this.options.overflow).css("overflow","").css(t,""),this.$element.hide().trigger("hidden")},removeLoading:function(){this.$loading.remove(),this.$loading=null,this.isLoading=!1},loading:function(i){i=i||function(){};var e=this.$element.hasClass("fade")?"fade":"";if(this.isLoading)if(this.isLoading&&this.$loading){this.$loading.removeClass("in");var n=this;t.support.transition&&this.$element.hasClass("fade")?this.$loading.one(t.support.transition.end,function(){n.removeLoading()}):n.removeLoading()}else i&&i(this.isLoading);else{var s=t.support.transition&&e;this.$loading=t('<div class="loading-mask '+e+'">').append(this.options.spinner).appendTo(this.$element),s&&this.$loading[0].offsetWidth,this.$loading.addClass("in"),this.isLoading=!0,s?this.$loading.one(t.support.transition.end,i):i()}},focus:function(){var t=this.$element.find(this.options.focusOn);(t=t.length?t:this.$element).focus()},attention:function(){if(this.options.attentionAnimation){this.$element.removeClass("animated").removeClass(this.options.attentionAnimation);var t=this;setTimeout(function(){t.$element.addClass("animated").addClass(t.options.attentionAnimation)},0)}this.focus()},destroy:function(){var i=t.Event("destroy");this.$element.trigger(i),i.isDefaultPrevented()||(this.$element.off(".modal").removeData("modal").removeClass("in").attr("aria-hidden",!0),this.$parent!==this.$element.parent()?this.$element.appendTo(this.$parent):this.$parent.length||(this.$element.remove(),this.$element=null),this.$element.trigger("destroyed"))}},t.fn.modal=function(e,n){return this.each(function(){var s=t(this),o=s.data("modal"),a=t.extend({},t.fn.modal.defaults,s.data(),"object"==typeof e&&e);o||s.data("modal",o=new i(this,a)),"string"==typeof e?o[e].apply(o,[].concat(n)):a.show&&o.show()})},t.fn.modal.defaults={keyboard:!0,backdrop:!0,loading:!1,show:!0,width:null,height:null,maxHeight:null,modalOverflow:!1,consumeTab:!0,focusOn:null,replace:!1,resize:!1,overflow:".modal-body",attentionAnimation:"shake",manager:"body",spinner:'<div class="loading-spinner" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',backdropTemplate:'<div class="modal-backdrop" />'},t.fn.modal.Constructor=i,t(function(){t(document).off("click.modal").on("click.modal.data-api",'[data-toggle="modal"]',function(i){var e=t(this),n=e.attr("href"),s=t(e.attr("data-target")||n&&n.replace(/.*(?=#[^\s]+$)/,"")),o=s.data("modal")?"toggle":t.extend({remote:!/#/.test(n)&&n},s.data(),e.data());i.preventDefault(),s.modal(o).one("hide",function(){e.focus()})})})}(window.jQuery);
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/bootstrap-modal.min.js
bootstrap-modal.min.js
(function ($) { //Shortcut for fancyBox object var F = $.fancybox; //Add helper object F.helpers.buttons = { defaults : { skipSingle : false, // disables if gallery contains single image position : 'top', // 'top' or 'bottom' tpl : '<div id="fancybox-buttons"><ul><li><a class="btnPrev" title="Previous" href="javascript:;"></a></li><li><a class="btnPlay" title="Start slideshow" href="javascript:;"></a></li><li><a class="btnNext" title="Next" href="javascript:;"></a></li><li><a class="btnToggle" title="Toggle size" href="javascript:;"></a></li><li><a class="btnClose" title="Close" href="javascript:;"></a></li></ul></div>' }, list : null, buttons: null, beforeLoad: function (opts, obj) { //Remove self if gallery do not have at least two items if (opts.skipSingle && obj.group.length < 2) { obj.helpers.buttons = false; obj.closeBtn = true; return; } //Increase top margin to give space for buttons obj.margin[ opts.position === 'bottom' ? 2 : 0 ] += 30; }, onPlayStart: function () { if (this.buttons) { this.buttons.play.attr('title', 'Pause slideshow').addClass('btnPlayOn'); } }, onPlayEnd: function () { if (this.buttons) { this.buttons.play.attr('title', 'Start slideshow').removeClass('btnPlayOn'); } }, afterShow: function (opts, obj) { var buttons = this.buttons; if (!buttons) { this.list = $(opts.tpl).addClass(opts.position).appendTo('body'); buttons = { prev : this.list.find('.btnPrev').click( F.prev ), next : this.list.find('.btnNext').click( F.next ), play : this.list.find('.btnPlay').click( F.play ), toggle : this.list.find('.btnToggle').click( F.toggle ), close : this.list.find('.btnClose').click( F.close ) } } //Prev if (obj.index > 0 || obj.loop) { buttons.prev.removeClass('btnDisabled'); } else { buttons.prev.addClass('btnDisabled'); } //Next / Play if (obj.loop || obj.index < obj.group.length - 1) { buttons.next.removeClass('btnDisabled'); buttons.play.removeClass('btnDisabled'); } else { buttons.next.addClass('btnDisabled'); buttons.play.addClass('btnDisabled'); } this.buttons = buttons; this.onUpdate(opts, obj); }, onUpdate: function (opts, obj) { var toggle; if (!this.buttons) { return; } toggle = this.buttons.toggle.removeClass('btnDisabled btnToggleOn'); //Size toggle button if (obj.canShrink) { toggle.addClass('btnToggleOn'); } else if (!obj.canExpand) { toggle.addClass('btnDisabled'); } }, beforeClose: function () { if (this.list) { this.list.remove(); } this.list = null; this.buttons = null; } }; }(jQuery));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/fancybox-helpers/fancybox-buttons.js
fancybox-buttons.js
(function(b){var a=b.fancybox,c=function(d,e,f){f=f||"";if(b.type(f)==="object"){f=b.param(f,true)}b.each(e,function(g,h){d=d.replace("$"+g,h||"")});if(f.length){d+=(d.indexOf("?")>0?"&":"?")+f}return d};a.helpers.media={defaults:{youtube:{matcher:/(youtube\.com|youtu\.be|youtube-nocookie\.com)\/(watch\?v=|v\/|u\/|embed\/?)?(videoseries\?list=(.*)|[\w-]{11}|\?listType=(.*)&list=(.*)).*/i,params:{autoplay:1,autohide:1,fs:1,rel:0,hd:1,wmode:"opaque",enablejsapi:1},type:"iframe",url:"//www.youtube.com/embed/$3"},vimeo:{matcher:/(?:vimeo(?:pro)?.com)\/(?:[^\d]+)?(\d+)(?:.*)/,params:{autoplay:1,hd:1,show_title:1,show_byline:1,show_portrait:0,fullscreen:1},type:"iframe",url:"//player.vimeo.com/video/$1"},metacafe:{matcher:/metacafe.com\/(?:watch|fplayer)\/([\w\-]{1,10})/,params:{autoPlay:"yes"},type:"swf",url:function(e,f,d){d.swf.flashVars="playerVars="+b.param(f,true);return"//www.metacafe.com/fplayer/"+e[1]+"/.swf"}},dailymotion:{matcher:/dailymotion.com\/video\/(.*)\/?(.*)/,params:{additionalInfos:0,autoStart:1},type:"swf",url:"//www.dailymotion.com/swf/video/$1"},twitvid:{matcher:/twitvid\.com\/([a-zA-Z0-9_\-\?\=]+)/i,params:{autoplay:0},type:"iframe",url:"//www.twitvid.com/embed.php?guid=$1"},twitpic:{matcher:/twitpic\.com\/(?!(?:place|photos|events)\/)([a-zA-Z0-9\?\=\-]+)/i,type:"image",url:"//twitpic.com/show/full/$1/"},instagram:{matcher:/(instagr\.am|instagram\.com)\/p\/([a-zA-Z0-9_\-]+)\/?/i,type:"image",url:"//$1/p/$2/media/?size=l"},google_maps:{matcher:/maps\.google\.([a-z]{2,3}(\.[a-z]{2})?)\/(\?ll=|maps\?)(.*)/i,type:"iframe",url:function(d){return"//maps.google."+d[1]+"/"+d[3]+""+d[4]+"&output="+(d[4].indexOf("layer=c")>0?"svembed":"embed")}}},beforeLoad:function(g,j){var d=j.href||"",e=false,i,f,h,k;for(i in g){if(g.hasOwnProperty(i)){f=g[i];h=d.match(f.matcher);if(h){e=f.type;k=b.extend(true,{},f.params,j[i]||(b.isPlainObject(g[i])?g[i].params:null));d=b.type(f.url)==="function"?f.url.call(this,h,k,j):c(f.url,h,k);break}}}if(e){j.href=d;j.type=e;j.autoHeight=false}}}}(jQuery));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/fancybox-helpers/fancybox-media.min.js
fancybox-media.min.js
(function ($) { //Shortcut for fancyBox object var F = $.fancybox; //Add helper object F.helpers.thumbs = { defaults : { width : 50, // thumbnail width height : 50, // thumbnail height position : 'bottom', // 'top' or 'bottom' source : function ( item ) { // function to obtain the URL of the thumbnail image var href; if (item.element) { href = $(item.element).find('img').attr('src'); } if (!href && item.type === 'image' && item.href) { href = item.href; } return href; } }, wrap : null, list : null, width : 0, init: function (opts, obj) { var that = this, list, thumbWidth = opts.width, thumbHeight = opts.height, thumbSource = opts.source; //Build list structure list = ''; for (var n = 0; n < obj.group.length; n++) { list += '<li><a style="width:' + thumbWidth + 'px;height:' + thumbHeight + 'px;" href="javascript:jQuery.fancybox.jumpto(' + n + ');"></a></li>'; } this.wrap = $('<div id="fancybox-thumbs"></div>').addClass(opts.position).appendTo('body'); this.list = $('<ul>' + list + '</ul>').appendTo(this.wrap); //Load each thumbnail $.each(obj.group, function (i) { var href = thumbSource( obj.group[ i ] ); if (!href) { return; } $("<img />").load(function () { var width = this.width, height = this.height, widthRatio, heightRatio, parent; if (!that.list || !width || !height) { return; } //Calculate thumbnail width/height and center it widthRatio = width / thumbWidth; heightRatio = height / thumbHeight; parent = that.list.children().eq(i).find('a'); if (widthRatio >= 1 && heightRatio >= 1) { if (widthRatio > heightRatio) { width = Math.floor(width / heightRatio); height = thumbHeight; } else { width = thumbWidth; height = Math.floor(height / widthRatio); } } $(this).css({ width : width, height : height, top : Math.floor(thumbHeight / 2 - height / 2), left : Math.floor(thumbWidth / 2 - width / 2) }); parent.width(thumbWidth).height(thumbHeight); $(this).hide().appendTo(parent).fadeIn(300); }).attr('src', href); }); //Set initial width this.width = this.list.children().eq(0).outerWidth(true); this.list.width(this.width * (obj.group.length + 1)).css('left', Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5))); }, beforeLoad: function (opts, obj) { //Remove self if gallery do not have at least two items if (obj.group.length < 2) { obj.helpers.thumbs = false; return; } //Increase bottom margin to give space for thumbs obj.margin[ opts.position === 'top' ? 0 : 2 ] += ((opts.height) + 15); }, afterShow: function (opts, obj) { //Check if exists and create or update list if (this.list) { this.onUpdate(opts, obj); } else { this.init(opts, obj); } //Set active element this.list.children().removeClass('active').eq(obj.index).addClass('active'); }, //Center list onUpdate: function (opts, obj) { if (this.list) { this.list.stop(true).animate({ 'left': Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5)) }, 150); } }, beforeClose: function () { if (this.wrap) { this.wrap.remove(); } this.wrap = null; this.list = null; this.width = 0; } } }(jQuery));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/fancybox-helpers/fancybox-thumbs.js
fancybox-thumbs.js
(function ($) { "use strict"; //Shortcut for fancyBox object var F = $.fancybox, format = function( url, rez, params ) { params = params || ''; if ( $.type( params ) === "object" ) { params = $.param(params, true); } $.each(rez, function(key, value) { url = url.replace( '$' + key, value || '' ); }); if (params.length) { url += ( url.indexOf('?') > 0 ? '&' : '?' ) + params; } return url; }; //Add helper object F.helpers.media = { defaults : { youtube : { matcher : /(youtube\.com|youtu\.be|youtube-nocookie\.com)\/(watch\?v=|v\/|u\/|embed\/?)?(videoseries\?list=(.*)|[\w-]{11}|\?listType=(.*)&list=(.*)).*/i, params : { autoplay : 1, autohide : 1, fs : 1, rel : 0, hd : 1, wmode : 'opaque', enablejsapi : 1 }, type : 'iframe', url : '//www.youtube.com/embed/$3' }, vimeo : { matcher : /(?:vimeo(?:pro)?.com)\/(?:[^\d]+)?(\d+)(?:.*)/, params : { autoplay : 1, hd : 1, show_title : 1, show_byline : 1, show_portrait : 0, fullscreen : 1 }, type : 'iframe', url : '//player.vimeo.com/video/$1' }, metacafe : { matcher : /metacafe.com\/(?:watch|fplayer)\/([\w\-]{1,10})/, params : { autoPlay : 'yes' }, type : 'swf', url : function( rez, params, obj ) { obj.swf.flashVars = 'playerVars=' + $.param( params, true ); return '//www.metacafe.com/fplayer/' + rez[1] + '/.swf'; } }, dailymotion : { matcher : /dailymotion.com\/video\/(.*)\/?(.*)/, params : { additionalInfos : 0, autoStart : 1 }, type : 'swf', url : '//www.dailymotion.com/swf/video/$1' }, twitvid : { matcher : /twitvid\.com\/([a-zA-Z0-9_\-\?\=]+)/i, params : { autoplay : 0 }, type : 'iframe', url : '//www.twitvid.com/embed.php?guid=$1' }, twitpic : { matcher : /twitpic\.com\/(?!(?:place|photos|events)\/)([a-zA-Z0-9\?\=\-]+)/i, type : 'image', url : '//twitpic.com/show/full/$1/' }, instagram : { matcher : /(instagr\.am|instagram\.com)\/p\/([a-zA-Z0-9_\-]+)\/?/i, type : 'image', url : '//$1/p/$2/media/?size=l' }, google_maps : { matcher : /maps\.google\.([a-z]{2,3}(\.[a-z]{2})?)\/(\?ll=|maps\?)(.*)/i, type : 'iframe', url : function( rez ) { return '//maps.google.' + rez[1] + '/' + rez[3] + '' + rez[4] + '&output=' + (rez[4].indexOf('layer=c') > 0 ? 'svembed' : 'embed'); } } }, beforeLoad : function(opts, obj) { var url = obj.href || '', type = false, what, item, rez, params; for (what in opts) { if (opts.hasOwnProperty(what)) { item = opts[ what ]; rez = url.match( item.matcher ); if (rez) { type = item.type; params = $.extend(true, {}, item.params, obj[ what ] || ($.isPlainObject(opts[ what ]) ? opts[ what ].params : null)); url = $.type( item.url ) === "function" ? item.url.call( this, rez, params, obj ) : format( item.url, rez, params ); break; } } } if (type) { obj.href = url; obj.type = type; obj.autoHeight = false; } } }; }(jQuery));
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/resources/js/ext/fancybox-helpers/fancybox-media.js
fancybox-media.js
# import standard packages # import Zope3 interfaces from z3c.json.interfaces import IJSONWriter from zope.tales.interfaces import ITALESFunctionNamespace # import local interfaces from ztfy.myams.interfaces import IMyAMSApplication, IObjectData from ztfy.myams.interfaces.configuration import IMyAMSConfiguration, IMyAMSStaticConfiguration, \ MYAMS_CONFIGURATION_NAME_KEY from ztfy.myams.tal.interfaces import IMyAMSTalesAPI # import Zope3 packages from zope.component import getUtility, queryUtility from zope.interface import implements from zope.security.proxy import removeSecurityProxy # import local packages from ztfy.utils.request import getRequestData from ztfy.utils.traversing import getParent class MyAMSTalesAdapter(object): """myams: TALES adapter""" implements(IMyAMSTalesAPI, ITALESFunctionNamespace) def __init__(self, context): self.context = context def setEngine(self, engine): self.request = engine.vars['request'] def data(self): data = IObjectData(self.context, None) if (data is not None) and data.object_data: writer = getUtility(IJSONWriter) return writer.write(data.object_data) @property def application(self): return getParent(self.context, IMyAMSApplication) def configuration(self): application = self.application if application is not None: return IMyAMSConfiguration(application, None) def static_configuration(self): configuration_name = getRequestData(MYAMS_CONFIGURATION_NAME_KEY, self.request) if configuration_name: configuration = queryUtility(IMyAMSStaticConfiguration, name=configuration_name) if configuration is not None: return configuration configuration = self.configuration() if configuration is not None: return configuration.static_configuration def resources(self): application = getParent(self.context, IMyAMSApplication) if application is not None: for resource in application.resources: removeSecurityProxy(resource).need()
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/src/ztfy/myams/tal/api.py
api.py
.. contents:: Introduction ============ A ZTFY package providing a new Bootstrap-based application management skin What is it? =========== MyAMS, "My Application Management Skin", is a new ZTFY package which provides a complete application management skin based on Bootstrap. It is heavilly using AJAX and HTML5 "data" API, and already includes a few JQuery plug-ins like DataTables or Validate. No end-user or even developer documentation is available yet. I hope to be able to produce one as well as a complete demonstration site as soon as possible.
ztfy.myams
/ztfy.myams-0.1.33.tar.gz/ztfy.myams-0.1.33/docs/README.txt
README.txt
__docformat__ = "restructuredtext" # import standard packages from apscheduler.jobstores.base import JobStore # import Zope3 interfaces # import local interfaces from ztfy.utils.interfaces import IZEOConnection # import Zope3 packages from zope.component import getUtility, queryUtility from zope.traversing.api import getParent, getPath # import local packages class ZODBJobsStore(JobStore): """ZODB jobs store""" def __new__(cls, scheduler_util, scheduler_process): zeo_connection_util = queryUtility(IZEOConnection, scheduler_util.zeo_connection) if zeo_connection_util is None: return None return JobStore.__new__(cls, scheduler_util, scheduler_process) def __init__(self, scheduler_util, scheduler_process): self.scheduler_util = scheduler_util self.scheduler_path = getPath(scheduler_util) self.scheduler_process = scheduler_process def load_jobs(self): jobs = [] for task in self.scheduler_util.tasks: trigger = task.getTrigger() if trigger is not None: zeo_connection = getUtility(IZEOConnection, name=getParent(task).zeo_connection, context=task) job = self.scheduler_process.add_job(trigger, task, args=None, kwargs={'zeo_settings': zeo_connection.getSettings()}) job.id = task.internal_id jobs.append(job) self.jobs = jobs def add_job(self, job): if job not in self.jobs: self.jobs.append(job) def update_job(self, job): for index, my_job in enumerate(self.jobs): if my_job.id == job.id: self.jobs[index] = job def remove_job(self, job): if job in self.jobs: self.jobs.remove(job) def close(self): pass def __repr__(self): return '<%s (ZODB=%s)>' % (self.__class__.__name__, self.scheduler_util.zeo_connection)
ztfy.scheduler
/ztfy.scheduler-0.5.2.tar.gz/ztfy.scheduler-0.5.2/src/ztfy/scheduler/jobstore.py
jobstore.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from zope.component.interfaces import IObjectEvent from zope.container.interfaces import IContainer # import local interfaces from ztfy.i18n.interfaces import II18nAttributesAware from ztfy.security.interfaces import ILocalRoleManager # import Zope3 packages from zope.container.constraints import containers, contains from zope.deprecation.deprecation import deprecated from zope.interface import Interface, Attribute, invariant, Invalid from zope.schema import TextLine, Text, Password, URI, Bool, Int, Datetime, Choice, List, Object # import local packages from ztfy.i18n.schema import I18nTextLine from ztfy.security.schema import PrincipalList from ztfy.scheduler import _ # Jobs run interfaces class IBeforeJobRunEvent(IObjectEvent): """Interface for events notified before a job is run""" class IAfterJobRunEvent(IObjectEvent): """Interface for events notified after a job run""" status = Attribute(_("Job execution status")) # Scheduler task history interfaces class ISchedulerTaskHistoryInfo(Interface): """Scheduler task history item""" date = Datetime(title=_("Execution date"), required=True) status = Choice(title=_("Execution status"), values=('OK', 'Warning', 'Error', 'Empty')) report = Text(title=_("Execution report"), required=True) # Scheduler task interfaces class ISchedulerTaskInfo(Interface): """Base interface for scheduler tasks""" containers('ztfy.scheduler.interfaces.IScheduler') title = TextLine(title=_("Task name"), description=_("Descriptive name given to this task"), required=False) schedule_mode = Choice(title=_("Scheduling mode"), description=_("Scheduling mode defines how task will be scheduled"), vocabulary="ZTFY scheduling modes", required=True) report_source = TextLine(title=_("Reports source"), description=_("Mail address from which reports will be sent"), required=False) report_target = TextLine(title=_("Reports target"), description=_("Mail address to which execution reports will be sent"), required=False) report_mailer = Choice(title=_("Reports mailer"), description=_("Mail delivery utility used to send mails"), required=False, vocabulary='ZTFY mail deliveries') report_errors_only = Bool(title=_("Only report errors?"), description=_("If 'Yes', only error reports will be sent to given target"), required=True, default=False) send_empty_reports = Bool(title=_("Send empty reports?"), description=_("If 'No', empty reports will not be sent by mail"), required=True, default=False) keep_empty_reports = Bool(title=_("Keep empty reports history?"), description=_("If 'Yes', empty reports will be kept in task history"), required=True, default=False) history_length = Int(title=_("History length"), description=_("Number of execution reports to keep in history; enter 0 to disable"), required=True, default=100) history = List(title=_("History"), description=_("Task history"), value_type=Object(schema=ISchedulerTaskHistoryInfo)) runnable = Attribute(_("Is the task runnable ?")) internal_id = Attribute(_("Internal ID")) def getTrigger(self): """Get scheduler job trigger""" def getSchedulingInfo(self): """Get scheduling info""" def getNextRun(self): """Get next task execution time""" def run(self, report, **kw): """Launch job execution""" def storeReport(self, report, status): """Store execution report in task's history and send it by mail""" def sendReport(self, report, status, target=None): """Store execution report in task's history and send it by mail""" class ISchedulerTaskWriter(Interface): """Scheduler task writer interface""" def reset(self): """Re-schedule job execution""" def launch(self): """Ask task for immediate execution""" class ISchedulerTask(ISchedulerTaskInfo, ISchedulerTaskWriter): """Scheduler task interface""" class ISchedulerTaskSchedulingMode(Interface): """Scheduler task scheduling mode""" marker_interface = Attribute(_("Class name of scheduling mode marker interface")) schema = Attribute(_("Class name of scheduling mode info interface")) def getTrigger(self, task, scheduler): """Get trigger for the given task""" def schedule(self, task, scheduler): """Add given task to the scheduler""" class ISchedulerTaskSchedulingInfo(Interface): """Base interface for task scheduling info""" active = Bool(title=_("Active task"), description=_("You can disable a task by selecting 'No'"), required=True, default=False) max_runs = Int(title=_("Maximum number of iterations"), description=_("Maximum number of times the job will be executed; keep empty for infinite execution.\n" + "WARNING: Counter is reset when server restarts or if task is re-scheduled."), min=1, required=False) start_date = Datetime(title=_("First execution date"), description=_("Date from which scheduling should start"), required=False) class ISchedulerTaskSchedulingMarker(Interface): """Base interface for task scheduling mode markers""" # Scheduler cron-style tasks interfaces class ISchedulerCronTaskInfo(ISchedulerTaskSchedulingInfo): """Base interface for cron-style scheduled tasks""" year = TextLine(title=_("Years"), description=_("Years for which to schedule the job"), required=False, default=u'*') month = TextLine(title=_("Months"), description=_("Months (1-12) for which to schedule the job"), required=False, default=u'*') day = TextLine(title=_("Month days"), description=_("Days (1-31) for which to schedule the job"), required=False, default=u'*') week = TextLine(title=_("Weeks"), description=_("Year weeks (1-53) for which to schedule the job"), required=False, default=u'*') day_of_week = TextLine(title=_("Week days"), description=_("Week days (0-6, with 0 as monday) for which to schedule the job"), required=False, default=u'*') hour = TextLine(title=_("Hours"), description=_("Hours (0-23) for which to schedule the job"), required=False, default=u'*') minute = TextLine(title=_("Minutes"), description=_("Minutes (0-59) for which to schedule the job"), required=False, default=u'*') second = TextLine(title=_("Seconds"), description=_("Seconds (0-59) for which to schedule the job"), required=False, default=u'0') class ISchedulerCronTask(ISchedulerTaskSchedulingMarker): """Target interface for cron-style scheduled tasks""" # Scheduler dated tasks interfaces class ISchedulerDateTaskInfo(ISchedulerTaskSchedulingInfo): """Base interface for date-based scheduled tasks""" class ISchedulerDateTask(ISchedulerTaskSchedulingMarker): """Marker interface for date-based scheduled tasks""" # Scheduler loop tasks interfaces class ISchedulerLoopTaskInfo(ISchedulerTaskSchedulingInfo): """Base interface for interval-based scheduled tasks""" weeks = Int(title=_("Weeks interval"), description=_("Number of weeks between executions"), required=True, default=0) days = Int(title=_("Days interval"), description=_("Number of days between executions"), required=True, default=0) hours = Int(title=_("Hours interval"), description=_("Number of hours between executions"), required=True, default=0) minutes = Int(title=_("Minutes interval"), description=_("Number of minutes between executions"), required=True, default=1) seconds = Int(title=_("Seconds interval"), description=_("Number of seconds between executions"), required=True, default=0) class ISchedulerLoopTask(ISchedulerTaskSchedulingMarker): """Marker interface for interval-based scheduled tasks""" # ZODB packer task interface class IZODBPackingTaskInfo(Interface): """ZODB packing task info""" zeo_connection = Choice(title=_("ZEO connection name"), description=_("Name of ZEO connection utility pointing to packed database"), required=True, vocabulary="ZEO connections") pack_time = Int(title=_("Maximum transactions age"), description=_("Transactions older than this age, in days, will be removed"), required=True, default=0) class IZODBPackingTask(ISchedulerTask, IZODBPackingTaskInfo): """ZODB packing task interface""" # Scheduler URL caller interface class IURLCallerTaskInfo(Interface): """URL caller task info""" url = URI(title=_("Target URI"), description=_("Full URI of remote service"), required=True) username = TextLine(title=_("User name"), description=_("Target login"), required=False) password = Password(title=_("Password"), description=_("Target password"), required=False) proxy_server = TextLine(title=_("Proxy server"), description=_("Proxy server name"), required=False) proxy_port = Int(title=_("Proxy port"), description=_("Proxy server port"), required=False, default=8080) remote_dns = Bool(title=_("Use remote DNS ?"), description=_("If 'Yes', remote DNS queries will be done by proxy server"), required=True, default=True) proxy_username = TextLine(title=_("Proxy user name"), required=False) proxy_password = Password(title=_("Proxy password"), required=False) connection_timeout = Int(title=_("Connection timeout"), description=_("Connection timeout, in seconds; keep empty to use system's default, which is also none by default"), required=False, default=30) class IURLCallerTask(ISchedulerTask, IURLCallerTaskInfo): """URL caller interface""" # SSH remote execution task interface class ISSHCallerTaskInfo(Interface): """SSH caller task info""" hostname = TextLine(title=_("Target hostname of IP address"), description=_("Enter hostname or address of a remote hots; keep empty for local server host"), required=False) port = Int(title=_("SSH port number"), default=22, required=False) username = TextLine(title=_("User name"), required=False) private_key = TextLine(title=_("Private key filename"), description=_("Enter name of private key file; use '~' to identify running server user home directory, as in ~/.ssh/id_rsa"), required=False) password = Password(title=_("Password"), description=_("If not using private key, you must provider user's password"), required=False) cmdline = TextLine(title=_("Command line"), description=_("Enter command line, using absolute path names"), required=True) @invariant def check_remote_host(self): if self.hostname and (bool(self.private_key) == bool(self.password)): raise Invalid(_("You must provide a private key filename OR a password when defining remote tasks")) class ISSHCallerTask(ISchedulerTask, ISSHCallerTaskInfo): """SSH caller interface""" # # Scheduler locks interfaces # #BBB: Deprecated class IFileLockedScheduler(Interface): """Deprecated marker interface for schedulers using file locking""" deprecated(IFileLockedScheduler, "Scheduler locking interfaces shoudn't be used anymore!") #BBB: Deprecated class IMemcachedLockedScheduler(Interface): """Deprecated marker interface for schedulers using memcached locking""" deprecated(IMemcachedLockedScheduler, "Scheduler locking interfaces shoudn't be used anymore!") # # Scheduler interfaces # class ISchedulerHandler(Interface): """Scheduler management marker interface""" class ISchedulerInfo(II18nAttributesAware): """Scheduler info interface""" title = I18nTextLine(title=_("Title"), description=_("Scheduler title"), required=True) zmq_address = TextLine(title=_("Scheduler process address"), description=_("""Address of scheduler listener, in the 'IPv4:port' format.""" """Keep empty to disable it."""), required=False, default=u'127.0.0.1:5556') zeo_connection = Choice(title=_("ZEO connection name"), description=_("Name of ZEO connection utility defining scheduler connection"), required=True, vocabulary="ZEO connections") internal_id = Attribute(_("Internal ID")) def getTask(self, task_id): """Get task matching given task ID""" def getJobs(self): """Get text output of running jobs""" def getNextRun(self, task): """Get next execution time of given task""" class ISchedulerInnerInfo(Interface): """Scheduler internal info interface""" tasks = List(title=_("Scheduler tasks"), description=_("List of tasks assigned to this scheduler"), required=False) history = List(title=_("History"), description=_("Task history"), value_type=Object(schema=ISchedulerTaskHistoryInfo), readonly=True) class ISchedulerRoles(Interface): """Scheduler roles interface""" managers = PrincipalList(title=_("Scheduler managers"), description=_("List of scheduler's managers, which can define scheduler settings"), required=False) operators = PrincipalList(title=_("Scheduler operators"), description=_("List of scheduler's operators, which can define tasks"), required=False) class IScheduler(ISchedulerInfo, ISchedulerInnerInfo, ISchedulerRoles, IContainer, ILocalRoleManager): """Tasks manager interface""" contains(ISchedulerTask)
ztfy.scheduler
/ztfy.scheduler-0.5.2.tar.gz/ztfy.scheduler-0.5.2/src/ztfy/scheduler/interfaces.py
interfaces.py
__docformat__ = "restructuredtext" # import standard packages import codecs import logging logger = logging.getLogger('ztfy.scheduler') import traceback import transaction import zmq from apscheduler.triggers.cron import CronTrigger from apscheduler.triggers.interval import IntervalTrigger from apscheduler.triggers.simple import SimpleTrigger from cStringIO import StringIO from datetime import datetime, timedelta from persistent import Persistent from persistent.list import PersistentList # import Zope3 interfaces from transaction.interfaces import ITransactionManager from zope.annotation.interfaces import IAnnotations from zope.component.interfaces import ObjectEvent, ISite from zope.dublincore.interfaces import IZopeDublinCore from zope.intid.interfaces import IIntIds from zope.sendmail.interfaces import IMailDelivery # import local interfaces from ztfy.scheduler.interfaces import ISchedulerTask, ISchedulerTaskSchedulingMode, \ ISchedulerCronTask, ISchedulerCronTaskInfo, \ ISchedulerDateTask, ISchedulerDateTaskInfo, \ ISchedulerLoopTask, ISchedulerLoopTaskInfo, \ ISchedulerTaskHistoryInfo, \ IBeforeJobRunEvent, IAfterJobRunEvent, \ IScheduler from ztfy.utils.interfaces import IZEOConnection # import Zope3 packages from zope.app.publication.zopepublication import ZopePublication from zope.component import queryUtility, getUtility, adapter from zope.container.contained import Contained from zope.event import notify from zope.interface import implementer, implements, alsoProvides, noLongerProvides, Interface from zope.location import locate, Location from zope.schema.fieldproperty import FieldProperty from zope.site import hooks from zope.traversing import api as traversing_api # import local packages from ztfy.mail.message import TextMessage from ztfy.utils.date import getDuration from ztfy.utils.property import cached_property from ztfy.utils.timezone import tztime from ztfy.utils.traversing import getParent from ztfy.utils.zodb import ZEOConnectionInfo from ztfy.scheduler import _ class BeforeJobRunEvent(ObjectEvent): implements(IBeforeJobRunEvent) class AfterJobRunEvent(ObjectEvent): implements(IAfterJobRunEvent) def __init__(self, object, status): self.object = object self.status = status class TaskHistoryItem(Persistent, Contained): """Task history item""" implements(ISchedulerTaskHistoryInfo) date = FieldProperty(ISchedulerTaskHistoryInfo['date']) status = FieldProperty(ISchedulerTaskHistoryInfo['status']) report = FieldProperty(ISchedulerTaskHistoryInfo['report']) class TaskHistoryContainer(PersistentList, Location): """Task history container""" class BaseTask(Persistent, Location): """Scheduler base management task""" implements(ISchedulerTask) _title = FieldProperty(ISchedulerTask['title']) _schedule_mode = FieldProperty(ISchedulerTask['schedule_mode']) report_source = FieldProperty(ISchedulerTask['report_source']) report_target = FieldProperty(ISchedulerTask['report_target']) report_mailer = FieldProperty(ISchedulerTask['report_mailer']) report_errors_only = FieldProperty(ISchedulerTask['report_errors_only']) send_empty_reports = FieldProperty(ISchedulerTask['send_empty_reports']) keep_empty_reports = FieldProperty(ISchedulerTask['keep_empty_reports']) _history_length = FieldProperty(ISchedulerTask['history_length']) def __init__(self): history = self.history = TaskHistoryContainer() locate(history, self, '++history++') @property def title(self): return self._title @title.setter def title(self, value): self._title = value IZopeDublinCore(self).title = value @property def schedule_mode(self): return self._schedule_mode @schedule_mode.setter def schedule_mode(self, value): if self._schedule_mode is not None: mode = queryUtility(ISchedulerTaskSchedulingMode, self._schedule_mode) if (mode is not None) and mode.marker_interface.providedBy(self): noLongerProvides(self, mode.marker_interface) self._schedule_mode = value if value: mode = getUtility(ISchedulerTaskSchedulingMode, value) alsoProvides(self, mode.marker_interface) mode.schema(self).active = False self.reset() @property def history_length(self): return self._history_length @history_length.setter def history_length(self, value): self._history_length = value if value < len(self.history): history = self.history while value < len(history): del history[0] self.history = history @cached_property def internal_id(self): intids = queryUtility(IIntIds, context=self) if intids is not None: return intids.register(self) def getTrigger(self): mode = queryUtility(ISchedulerTaskSchedulingMode, self.schedule_mode) if mode is None: return None return mode.getTrigger(self) def getSchedulingInfo(self): mode = queryUtility(ISchedulerTaskSchedulingMode, self.schedule_mode) if mode is None: return None return mode.schema(self, None) def getNextRun(self): trigger = self.getTrigger() if trigger is not None: now = datetime.utcnow() return trigger.get_next_fire_time(now) def reset(self, delete_only=False): scheduler = getParent(self, IScheduler) # Add parent scheduler to hook arguments # Otherwise, deleted tasks can't be reset ! transaction.get().addAfterCommitHook(self._resetAction, kws={ 'scheduler': scheduler }) def _resetAction(self, status, *args, **kw): if not status: return # Contact ZMQ scheduler process to signal task changes scheduler = kw.get('scheduler') if scheduler is None: scheduler = getParent(self, IScheduler) if scheduler is not None: zeo = getUtility(IZEOConnection, scheduler.zeo_connection) context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect('tcp://' + scheduler.zmq_address) socket.send_json(['reset_task', { 'zeo': zeo.getSettings(), 'task_name': traversing_api.getName(self), 'job_id': self.internal_id }]) socket.recv_json() def launch(self): scheduler = getParent(self, IScheduler) # Ask scheduler for immediate execution transaction.get().addAfterCommitHook(self._launchAction, kws={ 'scheduler': scheduler }) def _launchAction(self, status, *args, **kw): if not status: return # Contact ZMQ scheduler process to ask for immediate execution scheduler = kw.get('scheduler') if scheduler is None: scheduler = getParent(self, IScheduler) if scheduler is not None: zeo = getUtility(IZEOConnection, scheduler.zeo_connection) context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect('tcp://' + scheduler.zmq_address) socket.send_json(['run_task', { 'zeo': zeo.getSettings(), 'task_name': traversing_api.getName(self), 'job_id': self.internal_id }]) socket.recv_json() def __call__(self, *args, **kw): report = codecs.getwriter('utf-8')(StringIO()) self._run(report, **kw) @property def runnable(self): mode = queryUtility(ISchedulerTaskSchedulingMode, self.schedule_mode) if mode is None: return False info = mode.schema(self, None) if info is None: return False return info.active def _run(self, report, **kw): """Execute task""" zeo_connection = ZEOConnectionInfo() zeo_connection.update(kw.get('zeo_settings')) with zeo_connection as root: manager = None try: root_folder = root.get(ZopePublication.root_name, None) task = traversing_api.traverse(root_folder, traversing_api.getPath(self)) if not (kw.get('run_immediate') or task.runnable): return manager = ITransactionManager(task) for attempt in manager.attempts(): with attempt as t: start = datetime.utcnow() try: site = getParent(task, ISite) hooks.setSite(site) notify(BeforeJobRunEvent(task)) task.run(report) if report.getvalue(): status = 'OK' else: status = 'Empty' report.write('\n\nTask duration: ' + getDuration(start) + '\n') except: status = 'Error' task._logException(report, "An error occured during execution of task %s" % task.title) notify(AfterJobRunEvent(task, status)) task.storeReport(report, status) task.sendReport(report, status) if t.status == 'Committed': break except: self._logException(None, "Can't execute scheduled job %s" % self.title) # Abort anything writen in our main transaction ITransactionManager(self).abort() def run(self, report): raise NotImplementedError, _("The 'run' method must be implemented by BaseTask subclasses") def _logReport(self, report, message, add_timestamp=True, level=logging.INFO): if add_timestamp: message = '%s - %s' % (tztime(datetime.utcnow()).strftime('%c'), message) if report is not None: report.write(message + '\n') logger.log(level, message) def _logException(self, report, message=None): message = '%s - %s' % (tztime(datetime.utcnow()).strftime('%c'), message or "An error occurred") if report is not None: report.write(message + '\n\n') report.write(traceback.format_exc() + '\n') logger.exception(message) def storeReport(self, report, status): """Store execution report in task's history and send it by mail""" if (status == 'Empty') and not self.keep_empty_reports: return item = TaskHistoryItem() item.date = tztime(datetime.utcnow()) item.status = status item.report = unicode(codecs.decode(report.getvalue(), 'utf-8')) if len(self.history) >= self.history_length: history = self.history while len(history) >= self.history_length: del history[0] self.history = history if self.history_length: self.history.append(item) locate(item, self.history) def sendReport(self, report, status): if self.report_target and \ ((status in ('Error', 'Warning')) or ((status == 'Empty') and self.send_empty_reports) or ((status == 'OK') and not self.report_errors_only)): mailer = queryUtility(IMailDelivery, self.report_mailer) if mailer is not None: if status == 'Error': subject = "[SCHEDULER ERROR] " + self.title else: subject = "[scheduler] " + self.title for target in self.report_target.split(';'): message = TextMessage(subject=subject, fromaddr=self.report_source, toaddr=(target,), text=report.getvalue()) mailer.send(self.report_source, (target,), message.as_string()) # # Cron-style scheduling mode # class CronTaskScheduler(object): """Cron-style task scheduler class""" implements(ISchedulerTaskSchedulingMode) marker_interface = ISchedulerCronTask schema = ISchedulerCronTaskInfo def getTrigger(self, task): if not self.marker_interface.providedBy(task): raise Exception(_("Task is not configured for cron-style scheduling !")) info = self.schema(task) return CronTrigger(year=info.year or u'*', month=info.month or u'*', day=info.day or u'*', week=info.week or u'*', day_of_week=info.day_of_week or u'*', hour=info.hour or u'*', minute=info.minute or u'*', second=info.second or u'0', start_date=info.start_date.replace(tzinfo=None) if info.start_date else None) CronTaskScheduler = CronTaskScheduler() SCHEDULER_TASK_CRON_KEY = 'ztfy.scheduler.mode.cron' @adapter(ISchedulerCronTask) @implementer(ISchedulerCronTaskInfo) def SchedulerTaskCronInfoFactory(context): """Scheduler task cron info adapter factory""" annotations = IAnnotations(context) info = annotations.get(SCHEDULER_TASK_CRON_KEY) if info is None: info = annotations[SCHEDULER_TASK_CRON_KEY] = SchedulerTaskCronInfo() return info class SchedulerTaskCronInfo(Persistent): """Scheduler task cron info""" implements(ISchedulerCronTaskInfo) active = FieldProperty(ISchedulerCronTaskInfo['active']) max_runs = FieldProperty(ISchedulerCronTaskInfo['max_runs']) start_date = FieldProperty(ISchedulerCronTaskInfo['start_date']) year = FieldProperty(ISchedulerCronTaskInfo['year']) month = FieldProperty(ISchedulerCronTaskInfo['month']) day = FieldProperty(ISchedulerCronTaskInfo['day']) week = FieldProperty(ISchedulerCronTaskInfo['week']) day_of_week = FieldProperty(ISchedulerCronTaskInfo['day_of_week']) hour = FieldProperty(ISchedulerCronTaskInfo['hour']) minute = FieldProperty(ISchedulerCronTaskInfo['minute']) second = FieldProperty(ISchedulerCronTaskInfo['second']) # # Date-style scheduling mode # class DateTaskScheduler(object): """Date-style task scheduler class""" implements(ISchedulerTaskSchedulingMode) marker_interface = ISchedulerDateTask schema = ISchedulerDateTaskInfo def getTrigger(self, task): if not self.marker_interface.providedBy(task): raise Exception(_("Task is not configured for date-style scheduling !")) info = self.schema(task) return SimpleTrigger(run_date=info.start_date.replace(tzinfo=None)) DateTaskScheduler = DateTaskScheduler() SCHEDULER_TASK_DATE_KEY = 'ztfy.scheduler.mode.date' @adapter(ISchedulerDateTask) @implementer(ISchedulerDateTaskInfo) def SchedulerTaskDateInfoFactory(context): """Scheduler task date info adapter""" annotations = IAnnotations(context) info = annotations.get(SCHEDULER_TASK_DATE_KEY) if info is None: info = annotations[SCHEDULER_TASK_DATE_KEY] = SchedulerTaskDateInfo() return info class SchedulerTaskDateInfo(Persistent): """Scheduler task date info""" implements(ISchedulerDateTaskInfo) active = FieldProperty(ISchedulerDateTaskInfo['active']) max_runs = FieldProperty(ISchedulerDateTaskInfo['max_runs']) start_date = FieldProperty(ISchedulerDateTaskInfo['start_date']) # # Immediate-style scheduling mode # def ImmediateTaskTrigger(): """Immediate-style task scheduler class""" return SimpleTrigger(run_date=datetime.now().replace(tzinfo=None) + timedelta(seconds=5)) # # Loop-style scheduling mode # class LoopTaskScheduler(object): """Interval-based task scheduler class""" implements(ISchedulerTaskSchedulingMode) marker_interface = ISchedulerLoopTask schema = ISchedulerLoopTaskInfo def getTrigger(self, task): if not self.marker_interface.providedBy(task): raise Exception(_("Task is not configured for loop-style scheduling !")) info = self.schema(task) return IntervalTrigger(timedelta(weeks=info.weeks, days=info.days, hours=info.hours, minutes=info.minutes, seconds=info.seconds), start_date=info.start_date.replace(tzinfo=None) if info.start_date else None) LoopTaskScheduler = LoopTaskScheduler() SCHEDULER_TASK_LOOP_KEY = 'ztfy.scheduler.mode.loop' @adapter(ISchedulerLoopTask) @implementer(ISchedulerLoopTaskInfo) def SchedulerTaskLoopInfoFactory(context): """Scheduler task loop info adapter""" annotations = IAnnotations(context) info = annotations.get(SCHEDULER_TASK_LOOP_KEY) if info is None: info = annotations[SCHEDULER_TASK_LOOP_KEY] = SchedulerTaskLoopInfo() return info class SchedulerTaskLoopInfo(Persistent): """Scheduler task loop info""" implements(ISchedulerLoopTaskInfo) active = FieldProperty(ISchedulerLoopTaskInfo['active']) max_runs = FieldProperty(ISchedulerLoopTaskInfo['max_runs']) start_date = FieldProperty(ISchedulerLoopTaskInfo['start_date']) weeks = FieldProperty(ISchedulerLoopTaskInfo['weeks']) days = FieldProperty(ISchedulerLoopTaskInfo['days']) hours = FieldProperty(ISchedulerLoopTaskInfo['hours']) minutes = FieldProperty(ISchedulerLoopTaskInfo['minutes']) seconds = FieldProperty(ISchedulerLoopTaskInfo['seconds'])
ztfy.scheduler
/ztfy.scheduler-0.5.2.tar.gz/ztfy.scheduler-0.5.2/src/ztfy/scheduler/task.py
task.py
__docformat__ = "restructuredtext" # import standard packages import zmq # import Zope3 interfaces from zope.intid.interfaces import IIntIds # import local interfaces from ztfy.scheduler.interfaces import IScheduler, ISchedulerHandler # import Zope3 packages from zope.component import queryUtility from zope.container.folder import Folder from zope.interface import implements from zope.schema.fieldproperty import FieldProperty from zope.site.site import SiteManagerContainer # import local packages from ztfy.i18n.property import I18nTextProperty from ztfy.security.property import RolePrincipalsProperty from ztfy.utils.property import cached_property class SchedulerHandler(object): """Scheduler handler utility""" implements(ISchedulerHandler) class Scheduler(Folder, SiteManagerContainer): """Scheduler persistent class""" implements(IScheduler) title = I18nTextProperty(IScheduler['title']) zmq_address = FieldProperty(IScheduler['zmq_address']) zeo_connection = FieldProperty(IScheduler['zeo_connection']) managers = RolePrincipalsProperty(IScheduler['managers'], role='ztfy.SchedulerManager') operators = RolePrincipalsProperty(IScheduler['operators'], role='ztfy.SchedulerOperator') @property def tasks(self): return list(self.values()) @property def history(self): result = [] [ result.extend(task.history) for task in self.tasks ] return result @cached_property def internal_id(self): intids = queryUtility(IIntIds, context=self) if intids is not None: return intids.register(self) def getTask(self, task_id, context=None): intids = queryUtility(IIntIds, context=context) return intids.queryObject(task_id) def _getSocket(self): context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect('tcp://' + self.zmq_address) return socket def getJobs(self): socket = self._getSocket() socket.send_json(['get_jobs', {}]) return socket.recv_json()
ztfy.scheduler
/ztfy.scheduler-0.5.2.tar.gz/ztfy.scheduler-0.5.2/src/ztfy/scheduler/manager.py
manager.py
# import standard packages import chardet import codecs import urlparse # import Zope3 interfaces # import local interfaces from ztfy.scheduler.interfaces import IURLCallerTask # import Zope3 packages from zope.interface import implements from zope.schema.fieldproperty import FieldProperty # import local packages from ztfy.scheduler.task import BaseTask from ztfy.utils.html import htmlToText from ztfy.utils.protocol import http class URLCallerTask(BaseTask): """URL caller task""" implements(IURLCallerTask) url = FieldProperty(IURLCallerTask['url']) username = FieldProperty(IURLCallerTask['username']) password = FieldProperty(IURLCallerTask['password']) proxy_server = FieldProperty(IURLCallerTask['proxy_server']) proxy_port = FieldProperty(IURLCallerTask['proxy_port']) remote_dns = FieldProperty(IURLCallerTask['remote_dns']) proxy_username = FieldProperty(IURLCallerTask['proxy_username']) proxy_password = FieldProperty(IURLCallerTask['proxy_password']) connection_timeout = FieldProperty(IURLCallerTask['connection_timeout']) def run(self, report): parser = urlparse.urlparse(self.url) if not parser.netloc: raise Exception, "Missing hostname - Task aborted" if self.proxy_server and not self.proxy_port: raise Exception, "Proxy server defined without proxy port - Task aborted" params = parser.query and dict([part.split('=') for part in parser.query.split('&')]) or {} credentials = (self.username, self.password) if self.username else () proxy = (self.proxy_server, self.proxy_port) if self.proxy_server else () proxy_auth = (self.proxy_username, self.proxy_password) if self.proxy_username else () client = http.HTTPClient('GET', parser.scheme, parser.netloc, parser.path, params=params, credentials=credentials, proxy=proxy, rdns=self.remote_dns, proxy_auth=proxy_auth, timeout=self.connection_timeout) response, content = client.getResponse() if response.status == 200: report.write('\n'.join(['%s=%s' % (k, v) for k, v in response.items()]) + '\n\n') if response.get('content-type', 'text/plain').startswith('text/html'): content = htmlToText(content) charset = chardet.detect(content).get('encoding') or 'utf-8' report.write(codecs.decode(content, charset))
ztfy.scheduler
/ztfy.scheduler-0.5.2.tar.gz/ztfy.scheduler-0.5.2/src/ztfy/scheduler/url.py
url.py
__docformat__ = "restructuredtext" # import standard packages import atexit import logging logger = logging.getLogger('ztfy.scheduler') import time import transaction import zmq # import Zope3 interfaces from transaction.interfaces import ITransactionManager from zope.catalog.interfaces import ICatalog from zope.component.interfaces import ISite, IRegistered, IUnregistered, IComponentRegistry from zope.intid.interfaces import IIntIds from zope.lifecycleevent.interfaces import IObjectRemovedEvent from zope.processlifetime import IDatabaseOpenedWithRoot # import local interfaces from ztfy.scheduler.interfaces import ISchedulerHandler, IScheduler, ISchedulerTask from ztfy.security.interfaces import ILocalRoleIndexer from ztfy.utils.interfaces import INewSiteManagerEvent # import Zope3 packages from zc.catalog.catalogindex import SetIndex from zope.app.publication.zopepublication import ZopePublication from zope.catalog.catalog import Catalog from zope.component import hooks, getUtilitiesFor, queryUtility, adapter from zope.intid import IntIds from zope.location.location import locate from zope.traversing import api as traversing_api # import local packages from ztfy.scheduler.process import SchedulerProcess, SchedulerMessageHandler from ztfy.utils.site import locateAndRegister from ztfy.zmq.process import processExitFunc _schedulers = {} def updateDatabaseIfNeeded(context): """Check for missing utilities at application startup""" try: sm = context.getSiteManager() except: return default = sm['default'] # Check for required IIntIds utility intids = queryUtility(IIntIds) if intids is None: intids = default.get('IntIds') if intids is None: intids = IntIds() locate(intids, default) IComponentRegistry(sm).registerUtility(intids, IIntIds, '') default['IntIds'] = intids # Check for security catalog and indexes catalog = default.get('SecurityCatalog') if catalog is None: catalog = Catalog() locateAndRegister(catalog, default, 'SecurityCatalog', intids) IComponentRegistry(sm).registerUtility(catalog, ICatalog, 'SecurityCatalog') if catalog is not None: if 'ztfy.SchedulerManager' not in catalog: index = SetIndex('ztfy.SchedulerManager', ILocalRoleIndexer, False) locateAndRegister(index, catalog, 'ztfy.SchedulerManager', intids) if 'ztfy.SchedulerOperator' not in catalog: index = SetIndex('ztfy.SchedulerOperator', ILocalRoleIndexer, False) locateAndRegister(index, catalog, 'ztfy.SchedulerOperator', intids) @adapter(IDatabaseOpenedWithRoot) def handleOpenedDatabase(event): """Launch scheduler process""" handler = queryUtility(ISchedulerHandler) if handler is None: return db = event.database connection = db.open() root = connection.root() root_folder = root.get(ZopePublication.root_name, {}) for site in root_folder.values(): if ISite(site, None) is not None: hooks.setSite(site) manager = ITransactionManager(site) for attempt in manager.attempts(): with attempt as t: updateDatabaseIfNeeded(site) if t.status == 'Committed': break for _name, utility in getUtilitiesFor(IScheduler): if utility.zmq_address: try: try: path = traversing_api.getPath(utility) except: # Can't get utility path ? # probably an unregistered deleted utility, go on... continue else: if _schedulers.get(path) is None: process = SchedulerProcess(utility, SchedulerMessageHandler) process.start() time.sleep(2) if process.is_alive(): _schedulers[path] = process atexit.register(processExitFunc, process=process) logger.info("Starting ZMQ process %s listening on %s with PID %d for handler %s" % (process.name, utility.zmq_address, process.pid, str(process.handler))) except zmq.ZMQError, e: logger.warning("Can't start scheduler process: " + e.message) @adapter(INewSiteManagerEvent) def handleNewSiteManager(event): updateDatabaseIfNeeded(event.object) @adapter(IScheduler, IRegistered) def handleRegisteredSchedulerUtility(utility, event): if utility.zmq_address: path = traversing_api.getPath(utility) if _schedulers.get(path) is None: process = SchedulerProcess(utility, SchedulerMessageHandler) process.start() time.sleep(2) if process.is_alive(): _schedulers[path] = process atexit.register(processExitFunc, process=process) logger.info("Starting ZMQ process %s listening on %s with PID %d for handler %s" % (process.name, utility.zmq_address, process.pid, str(process.handler))) @adapter(IScheduler, IUnregistered) def handleUnregisteredSchedulerUtility(utility, event): try: path = traversing_api.getPath(utility) except: # Can't get utility path ? # Probably an already deleted utility, go on as we can't do anything... # System will have to be restarted to restart scheduler process. return else: process = _schedulers.get(path) if process is not None: process.terminate() process.join() logger.info("Stopped unregistered scheduler process %s with PID %d" % (process.name, process.pid)) del _schedulers[path] def _deleteSchedulerHook(*args, **kw): """After commit hook for scheduler deletion""" path = kw.get('scheduler_path') if path is not None: process = _schedulers.get(path) if process is not None: process.terminate() process.join() logger.info("Stopped deleted scheduler process %s with PID %d" % (process.name, process.pid)) del _schedulers[path] @adapter(IScheduler, IObjectRemovedEvent) def handleDeletedScheduler(utility, event): transaction.get().addAfterCommitHook(_deleteSchedulerHook, kws={ 'scheduler_path': traversing_api.getPath(utility) }) @adapter(ISchedulerTask, IObjectRemovedEvent) def handleDeletedTask(task, event): """Reset deleted tasks...""" task.reset()
ztfy.scheduler
/ztfy.scheduler-0.5.2.tar.gz/ztfy.scheduler-0.5.2/src/ztfy/scheduler/events.py
events.py
__docformat__ = "restructuredtext" # import standard packages from apscheduler.scheduler import Scheduler as SchedulerBase from datetime import datetime from threading import Thread from transaction.interfaces import ITransactionManager # import Zope3 interfaces # import local interfaces from ztfy.utils.interfaces import IZEOConnection # import Zope3 packages from zope.app.publication.zopepublication import ZopePublication from zope.component import getUtility from zope.traversing.api import getParent, getPath, traverse # import local packages from ztfy.scheduler.jobstore import ZODBJobsStore from ztfy.scheduler.task import ImmediateTaskTrigger from ztfy.utils.zodb import ZEOConnectionInfo from ztfy.zmq.handler import ZMQMessageHandler from ztfy.zmq.process import ZMQProcess class TaskResettingThread(Thread): """Thread used to reset task scheduling Task reset is made in another thread, so that: - other transactions applied on updated tasks are visible - ZMQ request returns immediately to calling process """ def __init__(self, process, settings): Thread.__init__(self) self.process = process self.settings = settings def _getConnection(self, settings): zeo_settings = settings.get('zeo') connection = ZEOConnectionInfo() connection.update(zeo_settings) return connection def run(self): settings = self.settings job_id = settings.get('job_id') if job_id is None: return with self._getConnection(settings) as root: manager = None try: root_folder = root.get(ZopePublication.root_name, None) scheduler = self.process.scheduler scheduler_util = traverse(root_folder, self.process.scheduler_path) manager = ITransactionManager(scheduler_util) manager.abort() jobs_store = self.process.jobs_store for job in jobs_store.jobs: if job.id == job_id: scheduler.unschedule_job(job) break task = scheduler_util.get(settings.get('task_name')) if task is not None: trigger = task.getTrigger() if trigger is not None: zeo_connection = getUtility(IZEOConnection, name=getParent(task).zeo_connection, context=task) new_job = scheduler.add_job(trigger, task, args=None, kwargs={'zeo_settings': zeo_connection.getSettings()}) new_job.id = task.internal_id jobs_store.update_job(new_job) finally: if manager is not None: manager.abort() class TaskRunnerThread(Thread): """Task immediate runner thread""" def __init__(self, process, settings): Thread.__init__(self) self.process = process self.settings = settings def _getConnection(self, settings): zeo_settings = settings.get('zeo') connection = ZEOConnectionInfo() connection.update(zeo_settings) return connection def run(self): settings = self.settings job_id = settings.get('job_id') if job_id is None: return with self._getConnection(settings) as root: manager = None try: root_folder = root.get(ZopePublication.root_name, None) scheduler = self.process.scheduler scheduler_util = traverse(root_folder, self.process.scheduler_path) manager = ITransactionManager(scheduler_util) manager.abort() task = scheduler_util.get(settings.get('task_name')) if task is not None: trigger = ImmediateTaskTrigger() zeo_connection = getUtility(IZEOConnection, name=getParent(task).zeo_connection, context=task) new_job = scheduler.add_job(trigger, task, args=None, kwargs={ 'zeo_settings': zeo_connection.getSettings(), 'run_immediate': True }) new_job.id = '%s::%s' % (task.internal_id, datetime.utcnow().strftime('%Y%m%d%H%M%S')) finally: if manager is not None: manager.abort() class SchedulerHandler(object): """Scheduler messages handler""" def get_jobs(self, settings): scheduler = self.process.scheduler return [ str(job) for job in scheduler.get_jobs() ] def reset_task(self, settings): TaskResettingThread(self.process, settings).start() return 'OK' def run_task(self, settings): TaskRunnerThread(self.process, settings).start() return 'OK' class SchedulerMessageHandler(ZMQMessageHandler): """ZMQ scheduler messages handler""" handler = SchedulerHandler class SchedulerProcess(ZMQProcess): """ZMQ scheduler process""" scheduler = None scheduler_util = None def __init__(self, scheduler, handler): ZMQProcess.__init__(self, scheduler.zmq_address, handler) self.scheduler_path = getPath(scheduler) self.scheduler = SchedulerBase() if self.scheduler is not None: jobs_store = self.jobs_store = ZODBJobsStore(scheduler, self.scheduler) if jobs_store is not None: self.scheduler.add_jobstore(jobs_store, 'default') def run(self): if self.scheduler is not None: self.scheduler.start() ZMQProcess.run(self) def restart(self): if self.scheduler is not None: self.scheduler.stop()
ztfy.scheduler
/ztfy.scheduler-0.5.2.tar.gz/ztfy.scheduler-0.5.2/src/ztfy/scheduler/process.py
process.py
__docformat__ = "restructuredtext" # import standard packages import os import paramiko from paramiko.ssh_exception import SSHException import subprocess import sys import traceback # import Zope3 interfaces # import local interfaces from ztfy.scheduler.interfaces import ISSHCallerTask # import Zope3 packages from zope.interface import implements from zope.schema.fieldproperty import FieldProperty # import local packages from ztfy.scheduler.task import BaseTask class SSHCallerTask(BaseTask): """SSH caller task""" implements(ISSHCallerTask) hostname = FieldProperty(ISSHCallerTask['hostname']) port = FieldProperty(ISSHCallerTask['port']) username = FieldProperty(ISSHCallerTask['username']) private_key = FieldProperty(ISSHCallerTask['private_key']) password = FieldProperty(ISSHCallerTask['password']) cmdline = FieldProperty(ISSHCallerTask['cmdline']) def run(self, report): if self.hostname: self._runRemote(report) else: self._runLocal(report) def _runRemote(self, report): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(self.hostname, self.port, self.username, self.password, key_filename=os.path.expanduser(self.private_key) if self.private_key else None) try: stdin, stdout, stderr = ssh.exec_command(self.cmdline) stdin.close() report.write(stdout.read()) errors = stderr.read() if errors: report.write('\n\nSome errors occured\n===================\n') report.write(errors) except SSHException: etype, value, tb = sys.exc_info() report.write('\n\nAn error occured\n================\n') report.write(''.join(traceback.format_exception(etype, value, tb))) def _runLocal(self, report): shell = subprocess.Popen(self.cmdline, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = shell.communicate() report.write(stdout) if stderr: report.write('\n\nSome errors occured\n===================\n') report.write(stderr)
ztfy.scheduler
/ztfy.scheduler-0.5.2.tar.gz/ztfy.scheduler-0.5.2/src/ztfy/scheduler/ssh.py
ssh.py
__docformat__ = "restructuredtext" # import standard packages import codecs from cStringIO import StringIO # import Zope3 interfaces from z3c.json.interfaces import IJSONWriter from z3c.language.switch.interfaces import II18n # import local interfaces from ztfy.scheduler.browser.interfaces import ITaskPropertiesTarget, \ ITaskActiveColumn from ztfy.scheduler.interfaces import ISchedulerTask, ISchedulerTaskHistoryInfo, \ ISchedulerCronTaskInfo, ISchedulerDateTaskInfo, \ ISchedulerLoopTaskInfo, ISchedulerTaskInfo from ztfy.skin.interfaces import IDefaultView, IContainedDefaultView, IDialogEditFormButtons from ztfy.skin.layer import IZTFYBackLayer # import Zope3 packages from z3c.form import field, button from z3c.formjs import jsaction, ajax from z3c.table.column import Column, FormatterColumn, GetAttrColumn from zope.component import adapts, queryMultiAdapter, getUtility from zope.i18n import translate from zope.interface import implements, Interface from zope.schema import Bool from zope.schema.fieldproperty import FieldProperty from zope.traversing import namespace from zope.traversing import api as traversing_api from zope.traversing.browser import absoluteURL # import local packages from ztfy.jqueryui import jquery_datetime from ztfy.skin.container import ContainerBaseView from ztfy.skin.form import DialogAddForm, DialogDisplayForm, EditForm, DialogEditForm from ztfy.skin.menu import MenuItem, DialogMenuItem from ztfy.skin.widget import FixedWidthTextAreaFieldWidget from ztfy.utils.catalog import getIntIdUtility from ztfy.utils.property import cached_property from ztfy.utils.timezone import tztime from ztfy.utils.traversing import getParent from ztfy.utils.unicode import translateString from ztfy.scheduler import _ class TaskDefaultViewAdapter(object): adapts(ISchedulerTask, IZTFYBackLayer, Interface) implements(IDefaultView) def __init__(self, context, request, view): self.context = context self.request = request self.view = view @property def viewname(self): return '@@properties.html' def getAbsoluteURL(self): return '%s/%s' % (absoluteURL(self.context, self.request), self.viewname) class BaseTaskAddForm(DialogAddForm): @property def title(self): return II18n(self.context).queryAttribute('title', request=self.request) legend = _("Adding new scheduler task") fields = field.Fields(ISchedulerTaskInfo).omit('__parent__', '__name__', 'history') autocomplete = 'off' task_factory = None def create(self, data): task = self.task_factory() task.title = data.get('title') return task def add(self, task): name = translateString(task.title, forceLower=False, spaces='_') self.context[name] = task def getOutput(self, writer, parent): return writer.write({ 'output': 'RELOAD' }) class SchedulerTaskEditForm(EditForm): implements(ITaskPropertiesTarget) legend = _("Task properties") fields = field.Fields(ISchedulerTaskInfo).omit('__parent__', '__name__', 'history') autocomplete = 'off' def applyChanges(self, data): result = super(SchedulerTaskEditForm, self).applyChanges(data) if result: self.context.reset() return result class SchedulerTaskEditFormMenu(MenuItem): title = _("Connection settings") class ISchedulerTaskExecuteFormButtons(Interface): run = jsaction.JSButton(title=_("Run now !")) cancel = jsaction.JSButton(title=_("Cancel")) class SchedulerTaskExecuteFormMenu(DialogMenuItem): title = _(" :: Execute now...") class SchedulerTaskExecuteForm(DialogEditForm): legend = _("Task immediate run") help = _("You can run this task immediately. Execution log will be available in task's history, if enabled.\n" "WARNING: Task will be run even if it's disabled in it's scheduling settings!") fields = field.Fields(Interface) buttons = button.Buttons(ISchedulerTaskExecuteFormButtons) @jsaction.handler(buttons['run']) def run_handler(self, event, selector): return '$.ZTFY.form.edit(this.form);' @jsaction.handler(buttons['cancel']) def cancel_handler(self, event, selector): return '$.ZTFY.dialog.close();' @ajax.handler def ajaxEdit(self): self.context.launch() writer = getUtility(IJSONWriter) return writer.write({'output': u'OK', 'message': translate(_("Task successfully scheduled. Execution will start in 5 seconds."), context=self.request)}) class BaseTaskScheduleForm(DialogEditForm): legend = _("Schedule selected task") resources = (jquery_datetime,) def applyChanges(self, data): result = super(BaseTaskScheduleForm, self).applyChanges(data) self.context.reset() return result class TaskScheduleFormMenu(DialogMenuItem): title = _(" :: Schedule...") target = BaseTaskScheduleForm class CronTaskScheduleForm(BaseTaskScheduleForm): fields = field.Fields(ISchedulerCronTaskInfo) class DateTaskScheduleForm(BaseTaskScheduleForm): fields = field.Fields(ISchedulerDateTaskInfo) class LoopTaskScheduleForm(BaseTaskScheduleForm): fields = field.Fields(ISchedulerLoopTaskInfo) # Task debug-mode run form class SchedulerTaskDebugModeRunForm(DialogEditForm): """Scheduler task run form in debug mode""" help = _("Running a task in debug mode can to useful during development, as you can apply breakpoints.") fields = field.Fields(Interface) buttons = button.Buttons(ISchedulerTaskExecuteFormButtons) def getContent(self): return object() @jsaction.handler(buttons['run']) def run_handler(self, event, selector): return '$.ZTFY.form.edit(this.form);' @jsaction.handler(buttons['cancel']) def cancel_handler(self, event, selector): return '$.ZTFY.dialog.close();' def updateActions(self): super(SchedulerTaskDebugModeRunForm, self).updateActions() if 'run' in self.actions: self.actions['run'].title = _("Run task") def applyChanges(self, data): report = codecs.getwriter('utf-8')(StringIO()) self.context.run(report) return report.getvalue() def getOutput(self, writer, parent, changes=()): if changes: return writer.write({'output': u'MESSAGE', 'message': changes}) else: return writer.write({'output': self.changes_output}) class SchedulerTaskDebugModeRunFormMenu(DialogMenuItem): """Scheduler task debug-mode run menu item""" title = _(" :: Run task (debug mode)...") target = SchedulerTaskDebugModeRunForm # # Task tables columns # class TaskTitleColumn(Column): header = _("Title") weight = 10 cssClasses = {'td': 'title'} def renderCell(self, item): title = item.title if not title: title = traversing_api.getName(item) url = self.getURL(item) if url: title = '<a href="%s">%s</a>' % (url, title) return title def getURL(self, item): adapter = queryMultiAdapter((item, self.request, self.table), IContainedDefaultView) if adapter is None: adapter = queryMultiAdapter((item, self.request, self.table), IDefaultView) if adapter is not None: return adapter.getAbsoluteURL() class TaskHistoryTitleColumn(TaskTitleColumn): def renderCell(self, item): task = getParent(item, ISchedulerTask) title = task.title if not title: title = traversing_api.getName(task) url = self.getURL(item) if url: title = '<a href="%s">%s</a>' % (url, title) return title def getURL(self, item): task = getParent(item, ISchedulerTask) return "javascript:$.ZTFY.dialog.open('%s/++history++%d/@@properties.html');" % \ (absoluteURL(task, self.request), task.history.index(item)) class TaskActiveColumn(Column): implements(ITaskActiveColumn) header = _("Active ?") weight = 50 cssClasses = {'td': 'centered'} def renderCell(self, item): if item.runnable: return translate(_("Yes"), context=self.request) else: return translate(_("No"), context=self.request) class TaskDeleteColumn(Column): header = u"" weight = 80 cssClasses = {'td': 'actions'} def renderCell(self, item): klass = 'ui-workflow ui-icon ui-icon-trash' intids = getIntIdUtility() return '''<span title="%s" class="%s" onclick="$.ZTFY.container.remove(%s,this);"></span>''' % (translate(_("Delete task"), context=self.request), klass, intids.register(item)) class TaskHistoryDateColumn(FormatterColumn, GetAttrColumn): """Task history date column""" header = _("Execution date") weight = 20 formatterCategory = u'dateTime' formatterLength = u'short' attrName = 'date' def renderCell(self, item): formatter = self.getFormatter() value = self.getValue(item) if value: value = formatter.format(tztime(value)) return '''<a href="javascript:$.ZTFY.dialog.open('%s/++history++%d/@@properties.html');">%s</a>''' % \ (absoluteURL(self.context, self.request), self.context.history.index(item), value) class TaskHistoryStatusColumn(GetAttrColumn): """Task history status column""" header = _("Status") weight = 30 attrName = 'status' cssClasses = {'td': 'centered'} # Task history view class TaskHistoryViewMenu(MenuItem): title = _("History") class TaskHistoryView(ContainerBaseView): """Task history view""" legend = _("Task execution history") cssClasses = {'table': 'history'} sortOn = None @property def values(self): return sorted(ISchedulerTask(self.context).history, key=lambda x: tztime(x.date), reverse=True) def renderRow(self, row, cssClass=None): item, _col, _span = row[0] status = item.status cssClass = cssClass and ('%s %s' % (cssClass, status)) or status return super(TaskHistoryView, self).renderRow(row, cssClass) class TaskHistoryInfoNamespaceTraverser(namespace.view): """Task ++history++ namespace""" def traverse(self, name, ignored): index = int(name) return ISchedulerTask(self.context).history[index] class TaskHistoryInfoDisplayDialog(DialogDisplayForm): """Task history info display dialog""" legend = _("Execution log") fields = field.Fields(ISchedulerTaskHistoryInfo) fields['report'].widgetFactory = FixedWidthTextAreaFieldWidget @property def title(self): return self.task.title @cached_property def task(self): return getParent(self.context, ISchedulerTask)
ztfy.scheduler
/ztfy.scheduler-0.5.2.tar.gz/ztfy.scheduler-0.5.2/src/ztfy/scheduler/browser/task.py
task.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces # import local interfaces from ztfy.scheduler.browser.interfaces import ITaskAddFormMenuTarget from ztfy.scheduler.interfaces import IScheduler, ISchedulerInfo, ISchedulerRoles from ztfy.skin.interfaces import IDefaultView, IPropertiesMenuTarget from ztfy.skin.layer import IZTFYBackLayer # import Zope3 packages from z3c.form import field from z3c.template.template import getLayoutTemplate from zope.component import adapts from zope.interface import implements, Interface from zope.security.proxy import removeSecurityProxy from zope.traversing.browser import absoluteURL # import local packages from ztfy.security.browser.roles import RolesEditForm from ztfy.skin.container import ContainerBaseView from ztfy.skin.form import EditForm, DisplayForm from ztfy.skin.menu import MenuItem, DialogMenuItem from ztfy.utils.timezone import tztime from ztfy.scheduler import _ class SchedulerDefaultViewAdapter(object): """Scheduler default view adapter""" adapts(IScheduler, IZTFYBackLayer, Interface) implements(IDefaultView) def __init__(self, context, request, view): self.context = context self.request = request self.view = view @property def viewname(self): return '@@properties.html' def getAbsoluteURL(self): return '%s/%s' % (absoluteURL(self.context, self.request), self.viewname) class SchedulerEditForm(EditForm): """Scheduler properties edit form""" implements(IPropertiesMenuTarget) fields = field.Fields(ISchedulerInfo) legend = _("Edit scheduler properties") help = _("""If the scheduler is already registered, you should unregister it to stop it, """ """change it's properties and register it again.""") successMessage = _("""Data successfully updated.\n""" """WARNING: you should restart application process if scheduler """ """address has been changed without being unregistered!""") class SchedulerRolesEditForm(RolesEditForm): """Scheduler roles edit form""" interfaces = (ISchedulerRoles,) layout = getLayoutTemplate() parent_interface = IScheduler class SchedulerRolesMenuItem(DialogMenuItem): """Scheduler roles menu item""" title = _(":: Roles...") target = SchedulerRolesEditForm class SchedulerHistoryView(ContainerBaseView): """Scheduler history view""" legend = _("Scheduler tasks execution history") cssClasses = { 'table': 'history' } sortOn = None @property def values(self): return sorted(IScheduler(self.context).history, key=lambda x: tztime(x.date), reverse=True) def renderRow(self, row, cssClass=None): item, _col, _span = row[0] status = item.status cssClass = cssClass and ('%s %s' % (cssClass, status)) or status return super(SchedulerHistoryView, self).renderRow(row, cssClass) class SchedulerHistoryViewMenu(MenuItem): """Scheduler history view menu""" title = _("Tasks run history") class SchedulerTasksView(ContainerBaseView): """Scheduler tasks view""" implements(ITaskAddFormMenuTarget) legend = _("Scheduler's tasks") @property def values(self): return IScheduler(self.context).tasks class SchedulerTasksViewMenu(MenuItem): """Scheduler tasks view menu""" title = _("Tasks") class SchedulerJobsView(DisplayForm): """Scheduler jobs view""" title = _("Scheduler jobs") legend = _("List of currently scheduled jobs") @property def jobs(self): return removeSecurityProxy(self.context.getJobs()) class SchedulerJobsViewMenu(MenuItem): """Scheduler jobs view menu""" title = _("Jobs")
ztfy.scheduler
/ztfy.scheduler-0.5.2.tar.gz/ztfy.scheduler-0.5.2/src/ztfy/scheduler/browser/manager.py
manager.py
====================== ztfy.scheduler package ====================== .. contents:: What is ztfy.scheduler ? ======================== ztfy.scheduler is a base package for those which need to build scheduled tasks which can run inside a ZTK/ZopeApp based environment (ZEO is required !). These tasks can be scheduled: - on a cron-style base, - at a given date/time (like the "at" command) - or at a given interval. Scheduling is done through the APScheduler (http://packages.python.org/APScheduler/) package and so all these kinds of tasks can be scheduled with the same sets of settings. But tasks management is made through a simple web interface and tasks running history is stored in the ZODB. On application start, the scheduler is run in a dedicated ZeroMQ process, which is also used to handle synchronization between tasks settings and scheduler jobs. Tasks logs can be stored in the ZODB for a variable duration (based on a number of iterations). These log reports can also be sent by mail, on each run or only when errors are detected. How to use ztfy.scheduler ? =========================== A set of ztfy.scheduler usages are given as doctests in ztfy/scheduler/doctests/README.txt
ztfy.scheduler
/ztfy.scheduler-0.5.2.tar.gz/ztfy.scheduler-0.5.2/docs/README.txt
README.txt
===================== ztfy.security package ===================== You may find documentation in: - Global README.txt: ztfy/security/docs/README.txt - General: ztfy/security/docs - Technical: ztfy/security/doctests More informations can be found on ZTFY.org_ web site ; a decicated Trac environment is available on ZTFY.security_. This package is created and maintained by Thierry Florac_. .. _Thierry Florac: mailto:[email protected] .. _ZTFY.org: http://www.ztfy.org .. _ZTFY.security: http://trac.ztfy.org/ztfy.security
ztfy.security
/ztfy.security-0.4.3.tar.gz/ztfy.security-0.4.3/README.txt
README.txt
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) options, args = parser.parse_args() ###################################################################### # load/install setuptools try: if options.allow_site_packages: import setuptools import pkg_resources from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
ztfy.security
/ztfy.security-0.4.3.tar.gz/ztfy.security-0.4.3/bootstrap.py
bootstrap.py
# import Zope3 interfaces from zope.annotation.interfaces import IAnnotatable from zope.security.interfaces import IPermission, IPrincipal from zope.securitypolicy.interfaces import IRole, IPrincipalRoleManager, IPrincipalPermissionManager # import local interfaces from ztfy.security.interfaces import ILocalRoleManager, ISecurityManager, ISecurityManagerRoleChecker, \ IBaseRoleEvent, IGrantedRoleEvent, IRevokedRoleEvent # import Zope3 packages from zope.component import adapts import zope.event from zope.interface import implements from zope.lifecycleevent import ObjectModifiedEvent from zope.security.management import checkPermission from zope.traversing.api import getParent # import local packages from ztfy.security.interfaces import SecurityManagerException from ztfy.utils import request from ztfy.security import _ class BaseRoleEvent(ObjectModifiedEvent): implements(IBaseRoleEvent) def __init__(self, object, principal, role): super(BaseRoleEvent, self).__init__(object) self.principal = principal self.role = role class GrantedRoleEvent(BaseRoleEvent): implements(IGrantedRoleEvent) class RevokedRoleEvent(BaseRoleEvent): implements(IRevokedRoleEvent) class SecurityManagerAdapter(object): adapts(IAnnotatable) implements(ISecurityManager) def __init__(self, context): self.context = context # ISecurityManagerBase methods def canUsePermission(self, permission): if IPermission.providedBy(permission): permission = IPermission(permission).id try: return checkPermission(permission, self.context) except: return False def canView(self): return self.canUsePermission('zope.View') # ISecurityManagerReader methods def getLocalRoles(self, principal=None): if principal is None: principal = request.getPrincipal() if not principal: return None if IPrincipal.providedBy(principal): principal = IPrincipal(principal).id manager = IPrincipalRoleManager(self.context) roles = manager.getRolesForPrincipal(principal) return { 'allow': set((role[0] for role in roles if role[1].getName() == 'Allow')), 'deny': set((role[0] for role in roles if role[1].getName() == 'Deny')) } def getLocalAllowedRoles(self, principal=None): roles = self.getLocalRoles(principal) if not roles: return None return roles['allow'] def getLocalDeniedRoles(self, principal=None): roles = self.getLocalRoles(principal) if not roles: return None return roles['deny'] def getRoles(self, principal=None): result = { 'allow': set(), 'deny': set() } context = self.context while context is not None: roles = ISecurityManager(context).getLocalRoles(principal) if roles: for role in roles['allow']: if role not in result['deny']: result['allow'].add(role) for role in roles['deny']: if role not in result['allow']: result['deny'].add(role) context = getParent(context) return result def getAllowedRoles(self, principal=None): return self.getRoles(principal)['allow'] def getDeniedRoles(self, principal=None): return self.getRoles(principal)['deny'] def getLocalPrincipals(self, role): if IRole.providedBy(role): role = IRole(role).id manager = IPrincipalRoleManager(self.context) principals = manager.getPrincipalsForRole(role) return { 'allow': set((principal[0] for principal in principals if principal[1].getName() == 'Allow')), 'deny': set((principal[0] for principal in principals if principal[1].getName() == 'Deny')) } def getLocalAllowedPrincipals(self, role): return self.getLocalPrincipals(role)['allow'] def getLocalDeniedPrincipals(self, role): return self.getLocalPrincipals(role)['deny'] def getPrincipals(self, role): result = { 'allow': set(), 'deny': set() } context = self.context while context is not None: principals = ISecurityManager(context).getLocalPrincipals(role) for principal in principals['allow']: if principal not in result['deny']: result['allow'].add(principal) for principal in principals['deny']: if principal not in result['allow']: result['deny'].add(principal) context = getParent(context) return result def getAllowedPrincipals(self, role): return self.getPrincipals(role)['allow'] def getDeniedPrincipals(self, role): return self.getPrincipals(role)['deny'] def canUseRole(self, role, principal=None): if IRole.providedBy(role): role = IRole(role).id if principal is None: principal = request.getPrincipal() if IPrincipal.providedBy(principal): principal = principal.id if principal == 'zope.manager': return True return role in self.getAllowedRoles(principal) # ISecurityManagerWriter methods def _getLocalRoles(self): manager = ILocalRoleManager(self.context, None) if manager is None: return None return manager.__roles__ def grantPermission(self, permission, principal): if IPermission.providedBy(permission): permission = IPermission(permission).id if IPrincipal.providedBy(principal): principal = IPrincipal(principal).id ppm = IPrincipalPermissionManager(self.context) ppm.grantPermissionToPrincipal(permission, principal) def grantRole(self, role, principal, notify=True): if IRole.providedBy(role): role = IRole(role).id if IPrincipal.providedBy(principal): principal = IPrincipal(principal).id roles = self._getLocalRoles() if roles and (role not in roles): raise SecurityManagerException, _("The role %s is not handled by this object's class") % role checker = ISecurityManagerRoleChecker(self.context, None) if (checker is not None) and (not checker.canGrantRole(role, principal)): raise SecurityManagerException, _("You are not authorized to grant role %s to principal %s") % (role, principal) prm = IPrincipalRoleManager(self.context) prm.assignRoleToPrincipal(role, principal) if notify: zope.event.notify(GrantedRoleEvent(self.context, principal, role)) def unsetPermission(self, permission, principal): if IPermission.providedBy(permission): permission = IPermission(permission).id if IPrincipal.providedBy(principal): principal = IPrincipal(principal).id ppm = IPrincipalPermissionManager(self.context) ppm.unsetPermissionForPrincipal(permission, principal) def unsetRole(self, role, principal, notify=True): if IRole.providedBy(role): role = IRole(role).id if IPrincipal.providedBy(principal): principal = IPrincipal(principal).id roles = self._getLocalRoles() if roles and (role not in roles): raise SecurityManagerException, _("The role %s is not handled by this object's class") % role checker = ISecurityManagerRoleChecker(self.context, None) if (checker is not None) and (not checker.canRevokeRole(role, principal)): raise SecurityManagerException, _("You are not authorized to revoke role %s for principal %s") % (role, principal) prm = IPrincipalRoleManager(self.context) prm.unsetRoleForPrincipal(role, principal) if notify: zope.event.notify(RevokedRoleEvent(self.context, principal, role)) def denyPermission(self, permission, principal): if IPermission.providedBy(permission): permission = IPermission(permission).id if IPrincipal.providedBy(principal): principal = IPrincipal(principal).id ppm = IPrincipalPermissionManager(self.context) ppm.denyPermissionToPrincipal(permission, principal) def revokeRole(self, role, principal, notify=True): if IRole.providedBy(role): role = IRole(role).id if IPrincipal.providedBy(principal): principal = IPrincipal(principal).id roles = self._getLocalRoles() if roles and (role not in roles): raise SecurityManagerException, _("The role %s is not handled by this object's class") % role checker = ISecurityManagerRoleChecker(self.context, None) if (checker is not None) and (not checker.canRevokeRole(role, principal)): raise SecurityManagerException, _("You are not authorized to revoke role %s for principal %s") % (role, principal) prm = IPrincipalRoleManager(self.context) prm.removeRoleFromPrincipal(role, principal) if notify: zope.event.notify(RevokedRoleEvent(self.context, principal, role)) def getSecurityManager(context): while context is not None: sm = ISecurityManager(context, None) if sm is not None: return sm context = getParent(context) return None
ztfy.security
/ztfy.security-0.4.3.tar.gz/ztfy.security-0.4.3/src/ztfy/security/security.py
security.py