!function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)}(function(x){"use strict";var t,e,i,n,W,C,o,s,r,l,a,h,u;function E(t,e,i){return[parseFloat(t[0])*(a.test(t[0])?e/100:1),parseFloat(t[1])*(a.test(t[1])?i/100:1)]}function L(t,e){return parseInt(x.css(t,e),10)||0}function N(t){return null!=t&&t===t.window}x.ui=x.ui||{},x.ui.version="1.13.3",
x.extend(x.expr.pseudos,{data:x.expr.createPseudo?x.expr.createPseudo(function(e){return function(t){return!!x.data(t,e)}}):function(t,e,i){return!!x.data(t,i[3])}}),
x.fn.extend({disableSelection:(t="onselectstart"in document.createElement("div")?"selectstart":"mousedown",function(){return this.on(t+".ui-disableSelection",function(t){t.preventDefault()})}),enableSelection:function(){return this.off(".ui-disableSelection")}}),
x.ui.focusable=function(t,e){var i,n,o,s=t.nodeName.toLowerCase();return"area"===s?(o=(i=t.parentNode).name,!(!t.href||!o||"map"!==i.nodeName.toLowerCase())&&0<(i=x("img[usemap='#"+o+"']")).length&&i.is(":visible")):(/^(input|select|textarea|button|object)$/.test(s)?(n=!t.disabled)&&(o=x(t).closest("fieldset")[0])&&(n=!o.disabled):n="a"===s&&t.href||e,n&&x(t).is(":visible")&&function(t){var e=t.css("visibility");for(;"inherit"===e;)t=t.parent(),e=t.css("visibility");return"visible"===e}(x(t)))},x.extend(x.expr.pseudos,{focusable:function(t){return x.ui.focusable(t,null!=x.attr(t,"tabindex"))}}),x.fn._form=function(){return"string"==typeof this[0].form?this.closest("form"):x(this[0].form)},
x.ui.formResetMixin={_formResetHandler:function(){var e=x(this);setTimeout(function(){var t=e.data("ui-form-reset-instances");x.each(t,function(){this.refresh()})})},_bindFormResetHandler:function(){var t;this.form=this.element._form(),this.form.length&&((t=this.form.data("ui-form-reset-instances")||[]).length||this.form.on("reset.ui-form-reset",this._formResetHandler),t.push(this),this.form.data("ui-form-reset-instances",t))},_unbindFormResetHandler:function(){var t;this.form.length&&((t=this.form.data("ui-form-reset-instances")).splice(x.inArray(this,t),1),t.length?this.form.data("ui-form-reset-instances",t):this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset"))}},x.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),
x.expr.pseudos||(x.expr.pseudos=x.expr[":"]),x.uniqueSort||(x.uniqueSort=x.unique),x.escapeSelector||(e=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g,i=function(t,e){return e?"\0"===t?"�":t.slice(0,-1)+"\\"+t.charCodeAt(t.length-1).toString(16)+" ":"\\"+t},x.escapeSelector=function(t){return(t+"").replace(e,i)}),x.fn.even&&x.fn.odd||x.fn.extend({even:function(){return this.filter(function(t){return t%2==0})},odd:function(){return this.filter(function(t){return t%2==1})}}),
x.ui.keyCode={BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38},
x.fn.labels=function(){var t,e,i;return this.length?this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(e=this.eq(0).parents("label"),(t=this.attr("id"))&&(i=(i=this.eq(0).parents().last()).add((i.length?i:this).siblings()),t="label[for='"+x.escapeSelector(t)+"']",e=e.add(i.find(t).addBack(t))),this.pushStack(e)):this.pushStack([])},x.ui.plugin={add:function(t,e,i){var n,o=x.ui[t].prototype;for(n in i)o.plugins[n]=o.plugins[n]||[],o.plugins[n].push([e,i[n]])},call:function(t,e,i,n){var o,s=t.plugins[e];if(s&&(n||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(o=0;o<s.length;o++)t.options[s[o][0]]&&s[o][1].apply(t.element,i)}},
W=Math.max,C=Math.abs,o=/left|center|right/,s=/top|center|bottom/,r=/[\+\-]\d+(\.[\d]+)?%?/,l=/^\w+/,a=/%$/,h=x.fn.position,x.position={scrollbarWidth:function(){var t,e,i;return void 0!==n?n:(i=(e=x("<div style='display:block;position:absolute;width:200px;height:200px;overflow:hidden;'><div style='height:300px;width:auto;'></div></div>")).children()[0],x("body").append(e),t=i.offsetWidth,e.css("overflow","scroll"),t===(i=i.offsetWidth)&&(i=e[0].clientWidth),e.remove(),n=t-i)},getScrollInfo:function(t){var e=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),i=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),e="scroll"===e||"auto"===e&&t.width<t.element[0].scrollWidth;return{width:"scroll"===i||"auto"===i&&t.height<t.element[0].scrollHeight?x.position.scrollbarWidth():0,height:e?x.position.scrollbarWidth():0}},getWithinInfo:function(t){var e=x(t||window),i=N(e[0]),n=!!e[0]&&9===e[0].nodeType;return{element:e,isWindow:i,isDocument:n,offset:!i&&!n?x(t).offset():{left:0,top:0},scrollLeft:e.scrollLeft(),scrollTop:e.scrollTop(),width:e.outerWidth(),height:e.outerHeight()}}},x.fn.position=function(f){var c,d,p,g,m,v,y,w,b,_,t,e;return f&&f.of?(v="string"==typeof(f=x.extend({},f)).of?x(document).find(f.of):x(f.of),y=x.position.getWithinInfo(f.within),w=x.position.getScrollInfo(y),b=(f.collision||"flip").split(" "),_={},e=9===(e=(t=v)[0]).nodeType?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:N(e)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:e.preventDefault?{width:0,height:0,offset:{top:e.pageY,left:e.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()},v[0].preventDefault&&(f.at="left top"),d=e.width,p=e.height,m=x.extend({},g=e.offset),x.each(["my","at"],function(){var t,e,i=(f[this]||"").split(" ");(i=1===i.length?o.test(i[0])?i.concat(["center"]):s.test(i[0])?["center"].concat(i):["center","center"]:i)[0]=o.test(i[0])?i[0]:"center",i[1]=s.test(i[1])?i[1]:"center",t=r.exec(i[0]),e=r.exec(i[1]),_[this]=[t?t[0]:0,e?e[0]:0],f[this]=[l.exec(i[0])[0],l.exec(i[1])[0]]}),1===b.length&&(b[1]=b[0]),"right"===f.at[0]?m.left+=d:"center"===f.at[0]&&(m.left+=d/2),"bottom"===f.at[1]?m.top+=p:"center"===f.at[1]&&(m.top+=p/2),c=E(_.at,d,p),m.left+=c[0],m.top+=c[1],this.each(function(){var i,t,r=x(this),l=r.outerWidth(),a=r.outerHeight(),e=L(this,"marginLeft"),n=L(this,"marginTop"),o=l+e+L(this,"marginRight")+w.width,s=a+n+L(this,"marginBottom")+w.height,h=x.extend({},m),u=E(_.my,r.outerWidth(),r.outerHeight());"right"===f.my[0]?h.left-=l:"center"===f.my[0]&&(h.left-=l/2),"bottom"===f.my[1]?h.top-=a:"center"===f.my[1]&&(h.top-=a/2),h.left+=u[0],h.top+=u[1],i={marginLeft:e,marginTop:n},x.each(["left","top"],function(t,e){x.ui.position[b[t]]&&x.ui.position[b[t]][e](h,{targetWidth:d,targetHeight:p,elemWidth:l,elemHeight:a,collisionPosition:i,collisionWidth:o,collisionHeight:s,offset:[c[0]+u[0],c[1]+u[1]],my:f.my,at:f.at,within:y,elem:r})}),f.using&&(t=function(t){var e=g.left-h.left,i=e+d-l,n=g.top-h.top,o=n+p-a,s={target:{element:v,left:g.left,top:g.top,width:d,height:p},element:{element:r,left:h.left,top:h.top,width:l,height:a},horizontal:i<0?"left":0<e?"right":"center",vertical:o<0?"top":0<n?"bottom":"middle"};d<l&&C(e+i)<d&&(s.horizontal="center"),p<a&&C(n+o)<p&&(s.vertical="middle"),W(C(e),C(i))>W(C(n),C(o))?s.important="horizontal":s.important="vertical",f.using.call(this,t,s)}),r.offset(x.extend(h,{using:t}))})):h.apply(this,arguments)},x.ui.position={fit:{left:function(t,e){var i,n=e.within,o=n.isWindow?n.scrollLeft:n.offset.left,n=n.width,s=t.left-e.collisionPosition.marginLeft,r=o-s,l=s+e.collisionWidth-n-o;n<e.collisionWidth?0<r&&l<=0?(i=t.left+r+e.collisionWidth-n-o,t.left+=r-i):t.left=!(0<l&&r<=0)&&l<r?o+n-e.collisionWidth:o:0<r?t.left+=r:0<l?t.left-=l:t.left=W(t.left-s,t.left)},top:function(t,e){var i,n=e.within,n=n.isWindow?n.scrollTop:n.offset.top,o=e.within.height,s=t.top-e.collisionPosition.marginTop,r=n-s,l=s+e.collisionHeight-o-n;o<e.collisionHeight?0<r&&l<=0?(i=t.top+r+e.collisionHeight-o-n,t.top+=r-i):t.top=!(0<l&&r<=0)&&l<r?n+o-e.collisionHeight:n:0<r?t.top+=r:0<l?t.top-=l:t.top=W(t.top-s,t.top)}},flip:{left:function(t,e){var i=e.within,n=i.offset.left+i.scrollLeft,o=i.width,i=i.isWindow?i.scrollLeft:i.offset.left,s=t.left-e.collisionPosition.marginLeft,r=s-i,s=s+e.collisionWidth-o-i,l="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,a="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,h=-2*e.offset[0];r<0?((o=t.left+l+a+h+e.collisionWidth-o-n)<0||o<C(r))&&(t.left+=l+a+h):0<s&&(0<(n=t.left-e.collisionPosition.marginLeft+l+a+h-i)||C(n)<s)&&(t.left+=l+a+h)},top:function(t,e){var i=e.within,n=i.offset.top+i.scrollTop,o=i.height,i=i.isWindow?i.scrollTop:i.offset.top,s=t.top-e.collisionPosition.marginTop,r=s-i,s=s+e.collisionHeight-o-i,l="top"===e.my[1]?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,a="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,h=-2*e.offset[1];r<0?((o=t.top+l+a+h+e.collisionHeight-o-n)<0||o<C(r))&&(t.top+=l+a+h):0<s&&(0<(n=t.top-e.collisionPosition.marginTop+l+a+h-i)||C(n)<s)&&(t.top+=l+a+h)}},flipfit:{left:function(){x.ui.position.flip.left.apply(this,arguments),x.ui.position.fit.left.apply(this,arguments)},top:function(){x.ui.position.flip.top.apply(this,arguments),x.ui.position.fit.top.apply(this,arguments)}}},x.ui.safeActiveElement=function(e){var i;try{i=e.activeElement}catch(t){i=e.body}return i=(i=i||e.body).nodeName?i:e.body},x.ui.safeBlur=function(t){t&&"body"!==t.nodeName.toLowerCase()&&x(t).trigger("blur")},
x.fn.scrollParent=function(t){var e=this.css("position"),i="absolute"===e,n=t?/(auto|scroll|hidden)/:/(auto|scroll)/,t=this.parents().filter(function(){var t=x(this);return(!i||"static"!==t.css("position"))&&n.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return"fixed"!==e&&t.length?t:x(this[0].ownerDocument||document)},
x.extend(x.expr.pseudos,{tabbable:function(t){var e=x.attr(t,"tabindex"),i=null!=e;return(!i||0<=e)&&x.ui.focusable(t,i)}}),
x.fn.extend({uniqueId:(u=0,function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++u)})}),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&x(this).removeAttr("id")})}});
var f,c=0,d=Array.prototype.hasOwnProperty,p=Array.prototype.slice;x.cleanData=(f=x.cleanData,function(t){for(var e,i,n=0;null!=(i=t[n]);n++)(e=x._data(i,"events"))&&e.remove&&x(i).triggerHandler("remove");f(t)}),x.widget=function(t,i,e){var n,o,s,r={},l=t.split(".")[0],a=l+"-"+(t=t.split(".")[1]);return e||(e=i,i=x.Widget),Array.isArray(e)&&(e=x.extend.apply(null,[{}].concat(e))),x.expr.pseudos[a.toLowerCase()]=function(t){return!!x.data(t,a)},x[l]=x[l]||{},n=x[l][t],o=x[l][t]=function(t,e){if(!this||!this._createWidget)return new o(t,e);arguments.length&&this._createWidget(t,e)},x.extend(o,n,{version:e.version,_proto:x.extend({},e),_childConstructors:[]}),(s=new i).options=x.widget.extend({},s.options),x.each(e,function(e,n){function o(){return i.prototype[e].apply(this,arguments)}function s(t){return i.prototype[e].apply(this,t)}r[e]="function"!=typeof n?n:function(){var t,e=this._super,i=this._superApply;return this._super=o,this._superApply=s,t=n.apply(this,arguments),this._super=e,this._superApply=i,t}}),o.prototype=x.widget.extend(s,{widgetEventPrefix:n&&s.widgetEventPrefix||t},r,{constructor:o,namespace:l,widgetName:t,widgetFullName:a}),n?(x.each(n._childConstructors,function(t,e){var i=e.prototype;x.widget(i.namespace+"."+i.widgetName,o,e._proto)}),delete n._childConstructors):i._childConstructors.push(o),x.widget.bridge(t,o),o},x.widget.extend=function(t){for(var e,i,n=p.call(arguments,1),o=0,s=n.length;o<s;o++)for(e in n[o])i=n[o][e],d.call(n[o],e)&&void 0!==i&&(x.isPlainObject(i)?t[e]=x.isPlainObject(t[e])?x.widget.extend({},t[e],i):x.widget.extend({},i):t[e]=i);return t},x.widget.bridge=function(s,e){var r=e.prototype.widgetFullName||s;x.fn[s]=function(i){var t="string"==typeof i,n=p.call(arguments,1),o=this;return t?this.length||"instance"!==i?this.each(function(){var t,e=x.data(this,r);return"instance"===i?(o=e,!1):e?"function"!=typeof e[i]||"_"===i.charAt(0)?x.error("no such method '"+i+"' for "+s+" widget instance"):(t=e[i].apply(e,n))!==e&&void 0!==t?(o=t&&t.jquery?o.pushStack(t.get()):t,!1):void 0:x.error("cannot call methods on "+s+" prior to initialization; attempted to call method '"+i+"'")}):o=void 0:(n.length&&(i=x.widget.extend.apply(null,[i].concat(n))),this.each(function(){var t=x.data(this,r);t?(t.option(i||{}),t._init&&t._init()):x.data(this,r,new e(i,this))})),o}},x.Widget=function(){},x.Widget._childConstructors=[],x.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{classes:{},disabled:!1,create:null},_createWidget:function(t,e){e=x(e||this.defaultElement||this)[0],this.element=x(e),this.uuid=c++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=x(),this.hoverable=x(),this.focusable=x(),this.classesElementLookup={},e!==this&&(x.data(e,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===e&&this.destroy()}}),this.document=x(e.style?e.ownerDocument:e.document||e),this.window=x(this.document[0].defaultView||this.document[0].parentWindow)),this.options=x.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:x.noop,_create:x.noop,_init:x.noop,destroy:function(){var i=this;this._destroy(),x.each(this.classesElementLookup,function(t,e){i._removeClass(e,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:x.noop,widget:function(){return this.element},option:function(t,e){var i,n,o,s=t;if(0===arguments.length)return x.widget.extend({},this.options);if("string"==typeof t)if(s={},t=(i=t.split(".")).shift(),i.length){for(n=s[t]=x.widget.extend({},this.options[t]),o=0;o<i.length-1;o++)n[i[o]]=n[i[o]]||{},n=n[i[o]];if(t=i.pop(),1===arguments.length)return void 0===n[t]?null:n[t];n[t]=e}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];s[t]=e}return this._setOptions(s),this},_setOptions:function(t){for(var e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return"classes"===t&&this._setOptionClasses(e),this.options[t]=e,"disabled"===t&&this._setOptionDisabled(e),this},_setOptionClasses:function(t){var e,i,n;for(e in t)n=this.classesElementLookup[e],t[e]!==this.options.classes[e]&&n&&n.length&&(i=x(n.get()),this._removeClass(n,e),i.addClass(this._classes({element:i,keys:e,classes:t,add:!0})))},_setOptionDisabled:function(t){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!t),t&&(this._removeClass(this.hoverable,null,"ui-state-hover"),this._removeClass(this.focusable,null,"ui-state-focus"))},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_classes:function(o){var s=[],r=this;function t(t,e){for(var i,n=0;n<t.length;n++)i=r.classesElementLookup[t[n]]||x(),i=o.add?(function(){var i=[];o.element.each(function(t,e){x.map(r.classesElementLookup,function(t){return t}).some(function(t){return t.is(e)})||i.push(e)}),r._on(x(i),{remove:"_untrackClassesElement"})}(),x(x.uniqueSort(i.get().concat(o.element.get())))):x(i.not(o.element).get()),r.classesElementLookup[t[n]]=i,s.push(t[n]),e&&o.classes[t[n]]&&s.push(o.classes[t[n]])}return(o=x.extend({element:this.element,classes:this.options.classes||{}},o)).keys&&t(o.keys.match(/\S+/g)||[],!0),o.extra&&t(o.extra.match(/\S+/g)||[]),s.join(" ")},_untrackClassesElement:function(i){var n=this;x.each(n.classesElementLookup,function(t,e){-1!==x.inArray(i.target,e)&&(n.classesElementLookup[t]=x(e.not(i.target).get()))}),this._off(x(i.target))},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,n){var o="string"==typeof t||null===t,e={extra:o?e:i,keys:o?t:e,element:o?this.element:t,add:n="boolean"==typeof n?n:i};return e.element.toggleClass(this._classes(e),n),this},_on:function(o,s,t){var r,l=this;"boolean"!=typeof o&&(t=s,s=o,o=!1),t?(s=r=x(s),this.bindings=this.bindings.add(s)):(t=s,s=this.element,r=this.widget()),x.each(t,function(t,e){function i(){if(o||!0!==l.options.disabled&&!x(this).hasClass("ui-state-disabled"))return("string"==typeof e?l[e]:e).apply(l,arguments)}"string"!=typeof e&&(i.guid=e.guid=e.guid||i.guid||x.guid++);var t=t.match(/^([\w:-]*)\s*(.*)$/),n=t[1]+l.eventNamespace,t=t[2];t?r.on(n,t,i):s.on(n,i)})},_off:function(t,e){e=(e||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.off(e),this.bindings=x(this.bindings.not(t).get()),this.focusable=x(this.focusable.not(t).get()),this.hoverable=x(this.hoverable.not(t).get())},_delay:function(t,e){var i=this;return setTimeout(function(){return("string"==typeof t?i[t]:t).apply(i,arguments)},e||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){this._addClass(x(t.currentTarget),null,"ui-state-hover")},mouseleave:function(t){this._removeClass(x(t.currentTarget),null,"ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){this._addClass(x(t.currentTarget),null,"ui-state-focus")},focusout:function(t){this._removeClass(x(t.currentTarget),null,"ui-state-focus")}})},_trigger:function(t,e,i){var n,o,s=this.options[t];if(i=i||{},(e=x.Event(e)).type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),e.target=this.element[0],o=e.originalEvent)for(n in o)n in e||(e[n]=o[n]);return this.element.trigger(e,i),!("function"==typeof s&&!1===s.apply(this.element[0],[e].concat(i))||e.isDefaultPrevented())}},x.each({show:"fadeIn",hide:"fadeOut"},function(s,r){x.Widget.prototype["_"+s]=function(e,t,i){var n,o=(t="string"==typeof t?{effect:t}:t)?!0!==t&&"number"!=typeof t&&t.effect||r:s;"number"==typeof(t=t||{})?t={duration:t}:!0===t&&(t={}),n=!x.isEmptyObject(t),t.complete=i,t.delay&&e.delay(t.delay),n&&x.effects&&x.effects.effect[o]?e[s](t):o!==s&&e[o]?e[o](t.duration,t.easing,i):e.queue(function(t){x(this)[s](),i&&i.call(e[0]),t()})}})});
!function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery","../ie","../version","../widget"],e):e(jQuery)}(function(o){"use strict";var n=!1;return o(document).on("mouseup",function(){n=!1}),o.widget("ui.mouse",{version:"1.13.3",options:{cancel:"input, textarea, button, select, option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.on("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).on("click."+this.widgetName,function(e){if(!0===o.data(e.target,t.widgetName+".preventClickEvent"))return o.removeData(e.target,t.widgetName+".preventClickEvent"),e.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.off("."+this.widgetName),this._mouseMoveDelegate&&this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(e){var t,i,s;if(!n)return this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(e),i=1===(this._mouseDownEvent=e).which,s=!("string"!=typeof(t=this).options.cancel||!e.target.nodeName)&&o(e.target).closest(this.options.cancel).length,i&&!s&&this._mouseCapture(e)&&(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){t.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=!1!==this._mouseStart(e),!this._mouseStarted)?e.preventDefault():(!0===o.data(e.target,this.widgetName+".preventClickEvent")&&o.removeData(e.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return t._mouseMove(e)},this._mouseUpDelegate=function(e){return t._mouseUp(e)},this.document.on("mousemove."+this.widgetName,this._mouseMoveDelegate).on("mouseup."+this.widgetName,this._mouseUpDelegate),e.preventDefault(),n=!0)),!0},_mouseMove:function(e){if(this._mouseMoved){if(o.ui.ie&&(!document.documentMode||document.documentMode<9)&&!e.button)return this._mouseUp(e);if(!e.which)if(e.originalEvent.altKey||e.originalEvent.ctrlKey||e.originalEvent.metaKey||e.originalEvent.shiftKey)this.ignoreMissingWhich=!0;else if(!this.ignoreMissingWhich)return this._mouseUp(e)}return(e.which||e.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(e),e.preventDefault()):(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=!1!==this._mouseStart(this._mouseDownEvent,e),this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)),!this._mouseStarted)},_mouseUp:function(e){this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,e.target===this._mouseDownEvent.target&&o.data(e.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(e)),this._mouseDelayTimer&&(clearTimeout(this._mouseDelayTimer),delete this._mouseDelayTimer),this.ignoreMissingWhich=!1,n=!1,e.preventDefault()},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})});
!function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery","./mouse","../keycode","../version","../widget"],e):e(jQuery)}(function(o){"use strict";return o.widget("ui.slider",o.ui.mouse,{version:"1.13.3",widgetEventPrefix:"slide",options:{animate:!1,classes:{"ui-slider":"ui-corner-all","ui-slider-handle":"ui-corner-all","ui-slider-range":"ui-corner-all ui-widget-header"},distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},numPages:5,_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this._calculateNewMax(),this._addClass("ui-slider ui-slider-"+this.orientation,"ui-widget ui-widget-content"),this._refresh(),this._animateOff=!1},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var e,t=this.options,i=this.element.find(".ui-slider-handle"),s=[],a=t.values&&t.values.length||1;for(i.length>a&&(i.slice(a).remove(),i=i.slice(0,a)),e=i.length;e<a;e++)s.push("<span tabindex='0'></span>");this.handles=i.add(o(s.join("")).appendTo(this.element)),this._addClass(this.handles,"ui-slider-handle","ui-state-default"),this.handle=this.handles.eq(0),this.handles.each(function(e){o(this).data("ui-slider-handle-index",e).attr("tabIndex",0)})},_createRange:function(){var e=this.options;e.range?(!0===e.range&&(e.values?e.values.length&&2!==e.values.length?e.values=[e.values[0],e.values[0]]:Array.isArray(e.values)&&(e.values=e.values.slice(0)):e.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?(this._removeClass(this.range,"ui-slider-range-min ui-slider-range-max"),this.range.css({left:"",bottom:""})):(this.range=o("<div>").appendTo(this.element),this._addClass(this.range,"ui-slider-range")),"min"!==e.range&&"max"!==e.range||this._addClass(this.range,"ui-slider-range-"+e.range)):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){this._off(this.handles),this._on(this.handles,this._handleEvents),this._hoverable(this.handles),this._focusable(this.handles)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this._mouseDestroy()},_mouseCapture:function(e){var i,s,a,n,t,h,l=this,u=this.options;return!u.disabled&&(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),t={x:e.pageX,y:e.pageY},i=this._normValueFromMouse(t),s=this._valueMax()-this._valueMin()+1,this.handles.each(function(e){var t=Math.abs(i-l.values(e));(t<s||s===t&&(e===l._lastChangedValue||l.values(e)===u.min))&&(s=t,a=o(this),n=e)}),!1!==this._start(e,n))&&(this._mouseSliding=!0,this._handleIndex=n,this._addClass(a,null,"ui-state-active"),a.trigger("focus"),t=a.offset(),h=!o(e.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=h?{left:0,top:0}:{left:e.pageX-t.left-a.width()/2,top:e.pageY-t.top-a.height()/2-(parseInt(a.css("borderTopWidth"),10)||0)-(parseInt(a.css("borderBottomWidth"),10)||0)+(parseInt(a.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(e,n,i),this._animateOff=!0)},_mouseStart:function(){return!0},_mouseDrag:function(e){var t={x:e.pageX,y:e.pageY},t=this._normValueFromMouse(t);return this._slide(e,this._handleIndex,t),!1},_mouseStop:function(e){return this._removeClass(this.handles,null,"ui-state-active"),this._mouseSliding=!1,this._stop(e,this._handleIndex),this._change(e,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(e){var t,e="horizontal"===this.orientation?(t=this.elementSize.width,e.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(t=this.elementSize.height,e.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),e=e/t;return(e=1<e?1:e)<0&&(e=0),"vertical"===this.orientation&&(e=1-e),t=this._valueMax()-this._valueMin(),e=this._valueMin()+e*t,this._trimAlignValue(e)},_uiHash:function(e,t,i){var s={handle:this.handles[e],handleIndex:e,value:void 0!==t?t:this.value()};return this._hasMultipleValues()&&(s.value=void 0!==t?t:this.values(e),s.values=i||this.values()),s},_hasMultipleValues:function(){return this.options.values&&this.options.values.length},_start:function(e,t){return this._trigger("start",e,this._uiHash(t))},_slide:function(e,t,i){var s,a=this.value(),n=this.values();this._hasMultipleValues()&&(s=this.values(t?0:1),a=this.values(t),2===this.options.values.length&&!0===this.options.range&&(i=0===t?Math.min(s,i):Math.max(s,i)),n[t]=i),i!==a&&!1!==this._trigger("slide",e,this._uiHash(t,i,n))&&(this._hasMultipleValues()?this.values(t,i):this.value(i))},_stop:function(e,t){this._trigger("stop",e,this._uiHash(t))},_change:function(e,t){this._keySliding||this._mouseSliding||(this._lastChangedValue=t,this._trigger("change",e,this._uiHash(t)))},value:function(e){if(!arguments.length)return this._value();this.options.value=this._trimAlignValue(e),this._refreshValue(),this._change(null,0)},values:function(e,t){var i,s,a;if(1<arguments.length)this.options.values[e]=this._trimAlignValue(t),this._refreshValue(),this._change(null,e);else{if(!arguments.length)return this._values();if(!Array.isArray(e))return this._hasMultipleValues()?this._values(e):this.value();for(i=this.options.values,s=e,a=0;a<i.length;a+=1)i[a]=this._trimAlignValue(s[a]),this._change(null,a);this._refreshValue()}},_setOption:function(e,t){var i,s=0;switch("range"===e&&!0===this.options.range&&("min"===t?(this.options.value=this._values(0),this.options.values=null):"max"===t&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),Array.isArray(this.options.values)&&(s=this.options.values.length),this._super(e,t),e){case"orientation":this._detectOrientation(),this._removeClass("ui-slider-horizontal ui-slider-vertical")._addClass("ui-slider-"+this.orientation),this._refreshValue(),this.options.range&&this._refreshRange(t),this.handles.css("horizontal"===t?"bottom":"left","");break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),i=s-1;0<=i;i--)this._change(null,i);this._animateOff=!1;break;case"step":case"min":case"max":this._animateOff=!0,this._calculateNewMax(),this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_setOptionDisabled:function(e){this._super(e),this._toggleClass(null,"ui-state-disabled",!!e)},_value:function(){var e=this.options.value;return this._trimAlignValue(e)},_values:function(e){var t,i;if(arguments.length)return e=this.options.values[e],this._trimAlignValue(e);if(this._hasMultipleValues()){for(t=this.options.values.slice(),i=0;i<t.length;i+=1)t[i]=this._trimAlignValue(t[i]);return t}return[]},_trimAlignValue:function(e){var t,i;return e<=this._valueMin()?this._valueMin():e>=this._valueMax()?this._valueMax():(t=0<this.options.step?this.options.step:1,i=e-(e=(e-this._valueMin())%t),2*Math.abs(e)>=t&&(i+=0<e?t:-t),parseFloat(i.toFixed(5)))},_calculateNewMax:function(){var e=this.options.max,t=this._valueMin(),i=this.options.step;(e=Math.round((e-t)/i)*i+t)>this.options.max&&(e-=i),this.max=parseFloat(e.toFixed(this._precision()))},_precision:function(){var e=this._precisionOf(this.options.step);return e=null!==this.options.min?Math.max(e,this._precisionOf(this.options.min)):e},_precisionOf:function(e){var e=e.toString(),t=e.indexOf(".");return-1===t?0:e.length-t-1},_valueMin:function(){return this.options.min},_valueMax:function(){return this.max},_refreshRange:function(e){"vertical"===e&&this.range.css({width:"",left:""}),"horizontal"===e&&this.range.css({height:"",bottom:""})},_refreshValue:function(){var t,i,e,s,a,n=this.options.range,h=this.options,l=this,u=!this._animateOff&&h.animate,r={};this._hasMultipleValues()?this.handles.each(function(e){i=(l.values(e)-l._valueMin())/(l._valueMax()-l._valueMin())*100,r["horizontal"===l.orientation?"left":"bottom"]=i+"%",o(this).stop(1,1)[u?"animate":"css"](r,h.animate),!0===l.options.range&&("horizontal"===l.orientation?(0===e&&l.range.stop(1,1)[u?"animate":"css"]({left:i+"%"},h.animate),1===e&&l.range[u?"animate":"css"]({width:i-t+"%"},{queue:!1,duration:h.animate})):(0===e&&l.range.stop(1,1)[u?"animate":"css"]({bottom:i+"%"},h.animate),1===e&&l.range[u?"animate":"css"]({height:i-t+"%"},{queue:!1,duration:h.animate}))),t=i}):(e=this.value(),s=this._valueMin(),a=this._valueMax(),i=a!==s?(e-s)/(a-s)*100:0,r["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[u?"animate":"css"](r,h.animate),"min"===n&&"horizontal"===this.orientation&&this.range.stop(1,1)[u?"animate":"css"]({width:i+"%"},h.animate),"max"===n&&"horizontal"===this.orientation&&this.range.stop(1,1)[u?"animate":"css"]({width:100-i+"%"},h.animate),"min"===n&&"vertical"===this.orientation&&this.range.stop(1,1)[u?"animate":"css"]({height:i+"%"},h.animate),"max"===n&&"vertical"===this.orientation&&this.range.stop(1,1)[u?"animate":"css"]({height:100-i+"%"},h.animate))},_handleEvents:{keydown:function(e){var t,i,s,a=o(e.target).data("ui-slider-handle-index");switch(e.keyCode){case o.ui.keyCode.HOME:case o.ui.keyCode.END:case o.ui.keyCode.PAGE_UP:case o.ui.keyCode.PAGE_DOWN:case o.ui.keyCode.UP:case o.ui.keyCode.RIGHT:case o.ui.keyCode.DOWN:case o.ui.keyCode.LEFT:if(e.preventDefault(),this._keySliding||(this._keySliding=!0,this._addClass(o(e.target),null,"ui-state-active"),!1!==this._start(e,a)))break;return}switch(s=this.options.step,t=i=this._hasMultipleValues()?this.values(a):this.value(),e.keyCode){case o.ui.keyCode.HOME:i=this._valueMin();break;case o.ui.keyCode.END:i=this._valueMax();break;case o.ui.keyCode.PAGE_UP:i=this._trimAlignValue(t+(this._valueMax()-this._valueMin())/this.numPages);break;case o.ui.keyCode.PAGE_DOWN:i=this._trimAlignValue(t-(this._valueMax()-this._valueMin())/this.numPages);break;case o.ui.keyCode.UP:case o.ui.keyCode.RIGHT:if(t===this._valueMax())return;i=this._trimAlignValue(t+s);break;case o.ui.keyCode.DOWN:case o.ui.keyCode.LEFT:if(t===this._valueMin())return;i=this._trimAlignValue(t-s)}this._slide(e,a,i)},keyup:function(e){var t=o(e.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(e,t),this._change(e,t),this._removeClass(o(e.target),null,"ui-state-active"))}}})});
!function(t){if(t.support.touch="ontouchend"in document,t.support.touch){var o,e=t.ui.mouse.prototype,u=e._mouseInit,n=e._mouseDestroy;e._touchStart=function(t){!o&&this._mouseCapture(t.originalEvent.changedTouches[0])&&(o=!0,this._touchMoved=!1,c(t,"mouseover"),c(t,"mousemove"),c(t,"mousedown"))},e._touchMove=function(t){o&&(this._touchMoved=!0,c(t,"mousemove"))},e._touchEnd=function(t){o&&(c(t,"mouseup"),c(t,"mouseout"),this._touchMoved||c(t,"click"),o=!1)},e._mouseInit=function(){this.element.on({touchstart:t.proxy(this,"_touchStart"),touchmove:t.proxy(this,"_touchMove"),touchend:t.proxy(this,"_touchEnd")}),u.call(this)},e._mouseDestroy=function(){this.element.off({touchstart:t.proxy(this,"_touchStart"),touchmove:t.proxy(this,"_touchMove"),touchend:t.proxy(this,"_touchEnd")}),n.call(this)}}function c(t,o){if(!(t.originalEvent.touches.length>1)){t.preventDefault();var e=t.originalEvent.changedTouches[0],u=document.createEvent("MouseEvents");u.initMouseEvent(o,!0,!0,window,1,e.screenX,e.screenY,e.clientX,e.clientY,!1,!1,!1,!1,0,null),t.target.dispatchEvent(u)}}}(jQuery);
(function(){
'use strict';
if(! String.prototype.isNumeric){
Object.defineProperty(String.prototype, 'isNumeric', {
value: function(){
return ! isNaN(parseFloat(this))&&isFinite(this);
}});
}}());
window.jQuery.jMaskGlobals={
maskElements: '.tc-extra-product-options input'
};
(function($){
'use strict';
$.epoAPI={};
$.epoAPI.error=false;
$.epoAPI.math={};
$.epoAPI.dom={};
$.epoAPI.util={};
$.epoAPI.locale={};
$.epoAPI.template={};
$.epoAPI.math.toFloat=function(s, d){
var n;
if(!(typeof s==='string'||typeof s==='number')||isNaN(s)){
return 0;
}
n=parseFloat(s);
if(isNaN(n)){
if(d!==undefined){
return d;
}
return s;
}
return n;
};
$.epoAPI.math.toInt=function(s, d){
var n;
if(!(typeof s==='string'||typeof s==='number')||isNaN(s)||s===''){
return 0;
}
n=parseInt(s, 10);
if(isNaN(n)){
if(d!==undefined){
return d;
}
return s;
}
return n;
};
$.epoAPI.math.round=function(value, precision, mode){
var m;
var f;
var isHalf;
var n;
var sgn;
precision=parseInt(precision, 10);
if(! Number.isFinite(precision)){
precision=0;
}
m=Math.pow(10, precision);
value=value * m;
if(typeof value==='number'){
if(value){
if(value < 0){
sgn=-1;
}else{
sgn=1;
}}else{
sgn=0;
}}else{
sgn=0;
}
isHalf=value % 1===0.5 * sgn;
f=Math.floor(value);
if(isHalf){
switch(mode){
case 'PHP_ROUND_HALF_DOWN':
if(sgn < 0){
n=1;
}else{
n=0;
}
value=f + n;
break;
case 'PHP_ROUND_HALF_EVEN':
value=f +(( f % 2) * sgn);
break;
case 'PHP_ROUND_HALF_ODD':
n=f % 2;
if(n){
n=0;
}else{
n=1;
}
value=f + n;
break;
default:
if(sgn > 0){
n=1;
}else{
n=0;
}
value=f + n;
}}
if(! isHalf){
value=Math.round(value);
}
return value / m;
};
$.epoAPI.math.uniqueid=function(prefix, moreEntropy){
var retId;
var _formatSeed=function(seed, reqWidth){
seed=parseInt(seed, 10).toString(16);
if(reqWidth < seed.length){
return seed.slice(seed.length - reqWidth);
}
if(reqWidth > seed.length){
return new Array(1 +(reqWidth - seed.length)).join('0') + seed;
}
return seed;
};
var radom;
if(prefix===undefined){
prefix='';
}
$.epoAPI.php=$.epoAPI.php||{};
if(! $.epoAPI.php.uniqidSeed){
$.epoAPI.php.uniqidSeed=Math.floor(Math.random() * 0x75bcd15);
}
$.epoAPI.php.uniqidSeed +=1;
retId=prefix;
retId +=_formatSeed(parseInt(Date.now() / 1000, 10), 8);
retId +=_formatSeed($.epoAPI.php.uniqidSeed, 5);
if(moreEntropy){
radom=Math.random() * 10;
retId +=radom.toFixed(8).toString();
}
return retId;
};
$.epoAPI.dom.id=function(id){
if(typeof id==='undefined'){
return id;
}
if(!(typeof id==='string'||typeof id==='number')||(typeof id==='number'&&isNaN(id))){
return id.toString();
}
return id.toString().replace(/(%|:|\.|\[|\]|,|=)/g, '\\$1');
};
$.epoAPI.dom.scroll=function(){
var scrollLeft;
var scrollTop;
if(window.pageYOffset){
scrollTop=window.pageYOffset;
scrollLeft=window.pageXOffset;
}else if(document.documentElement&&document.documentElement.scrollTop){
scrollTop=document.documentElement.scrollTop;
scrollLeft=document.documentElement.scrollLeft;
}else if(document.body){
scrollTop=document.body.scrollTop;
scrollLeft=document.body.scrollLeft;
}
return { left: scrollLeft, top: scrollTop };};
$.epoAPI.dom.size=function(){
var totalDocumentHeight;
var totalDocumentWidth;
var fullHeight;
var fullWidth;
var visibleWidth;
var visibleHeight;
if(window.innerHeight&&window.scrollMaxY){
totalDocumentWidth=window.innerWidth + window.scrollMaxX;
totalDocumentHeight=window.innerHeight + window.scrollMaxY;
}else if(document.body.scrollHeight > document.body.offsetHeight){
totalDocumentWidth=document.body.scrollWidth;
totalDocumentHeight=document.body.scrollHeight;
}else{
totalDocumentWidth=document.body.offsetWidth;
totalDocumentHeight=document.body.offsetHeight;
}
if(window.innerHeight){
if(document.documentElement.clientWidth){
visibleWidth=document.documentElement.clientWidth;
}else{
visibleWidth=window.innerWidth;
}
visibleHeight=window.innerHeight;
}else if(document.documentElement&&document.documentElement.clientHeight){
visibleWidth=document.documentElement.clientWidth;
visibleHeight=document.documentElement.clientHeight;
}else if(document.body){
visibleWidth=document.body.clientWidth;
visibleHeight=document.body.clientHeight;
}
if(totalDocumentHeight < visibleHeight){
fullHeight=visibleHeight;
}else{
fullHeight=totalDocumentHeight;
}
if(totalDocumentWidth < visibleWidth){
fullWidth=visibleWidth;
}else{
fullWidth=totalDocumentWidth;
}
return {
fullWidth: fullWidth,
fullHeight: fullHeight,
visibleWidth: visibleWidth,
visibleHeight: visibleHeight,
totalWidth: totalDocumentWidth,
totalHeight: totalDocumentHeight
};};
$.epoAPI.util.trim=function(str){
if(typeof str==='string'){
return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
}
return str;
};
$.epoAPI.util.parseJSON=function(s){
var parsedjson;
var JSON=window.JSON;
try {
parsedjson=JSON.parse(s + '');
if(parsedjson&&typeof parsedjson==='object'&&parsedjson!==null){
return parsedjson;
}} catch(err){
$.epoAPI.error=err;
return false;
}
return false;
};
$.epoAPI.util.decodeHTML=function(html){
var txt=document.createElement('textarea');
txt.innerHTML=html;
return txt.value;
};
$.epoAPI.util.getStorage=function(type){
var storage;
var x;
try {
storage=window[ type ];
x='__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return storage;
} catch(e){
return false;
}};
$.epoAPI.util.basename=function(path){
return path.replace(/.*\//, '');
};
$.epoAPI.util.deepCopyArray=function(inObject){
var outObject;
var value;
if(window.structuredClone!==undefined){
return window.structuredClone(inObject);
}
if(typeof inObject!=='object'||inObject===null){
return inObject;
}
outObject=Array.isArray(inObject) ? []:{};
Object.keys(inObject).forEach(function(key){
if(inObject){
value=inObject[ key ];
outObject[ key ]=typeof value==='object'&&value!==null ? $.epoAPI.util.deepCopyArray(value):value;
}});
return outObject;
};
$.epoAPI.locale.getSystemDecimalSeparator=function(){
var n=1.1;
n=/^1(.+)1$/.exec(n.toLocaleString());
if(n){
n=n[ 1 ];
}else{
n=',';
}
return n;
};
$.epoAPI.template.html=function(template, obj){
var $template_html=template(obj);
$template_html=$template_html.replace('', '');
$template_html=$template_html.replace('/*]]>*/', '');
return $template_html;
};
$.epoAPI.filters={};
$.epoAPI.addFilter=function($tag, $function_to_add, $priority, $accepted_args){
var $idx;
$priority=parseInt($priority, 10);
if(isNaN($priority)){
$priority=10;
}
$accepted_args=parseInt($accepted_args, 10);
if(isNaN($accepted_args)){
$accepted_args=1;
}
$idx=$function_to_add + '_' + $priority;
if(! $.epoAPI.filters[ $tag ]){
$.epoAPI.filters[ $tag ]={};}
if(! $.epoAPI.filters[ $tag ][ $priority ]){
$.epoAPI.filters[ $tag ][ $priority ]={};}
$.epoAPI.filters[ $tag ][ $priority ][ $idx ]={
func: $function_to_add,
accepted_args: $accepted_args
};
return true;
};
$.epoAPI.removeFilter=function($tag, $function_to_remove, $priority){
var $idx;
$priority=parseInt($priority, 10);
if(isNaN($priority)){
$priority=10;
}
$idx=$function_to_remove + '_' + $priority;
if($.epoAPI.filters[ $tag ]&&$.epoAPI.filters[ $tag ][ $priority ]&&$.epoAPI.filters[ $tag ][ $priority ][ $idx ]){
delete $.epoAPI.filters[ $tag ][ $priority ][ $idx ];
return true;
}
return false;
};
$.epoAPI.applyFilter=function($tag, $value){
var $args=$.makeArray(arguments);
var priorities;
$args.splice(0, 1);
if(! $.epoAPI.filters[ $tag ]){
return $value;
}
priorities=$.epoAPI.filters[ $tag ];
$.each(priorities, function(i, el){
$.each(el, function(i2, el2){
var func=el2.func;
if(func instanceof Function){
$value=func.apply(null, $args);
}else if(window[ func ]&&window[ func ] instanceof Function){
$value=window[ func ].apply(null, $args);
}});
});
return $value;
};
$.tc_add_filter=$.epoAPI.addFilter;
$.tc_remove_filter=$.epoAPI.removeFilter;
$.tc_apply_filters=$.epoAPI.applyFilter;
}(window.jQuery));
(function($){
'use strict';
function checkPrecision(val, base){
val=Math.round(Math.abs(val));
return isNaN(val) ? base:val;
}
function unformat(value, decimal){
var regex;
var unformatted;
if(Array.isArray(value)){
return value.map(value, function(val){
return unformat(val, decimal);
});
}
value=value||0;
if(typeof value==='number'){
return value;
}
decimal=decimal||'.';
regex=new RegExp('[^0-9-' + decimal + ']', [ 'g' ]);
unformatted=parseFloat(
('' + value)
.replace(regex, '')
.replace(decimal, '.')
);
return ! isNaN(unformatted) ? unformatted:0;
}
function toFixed(value, precision){
var exponentialForm;
var rounded;
var finalResult;
if(! Number.isFinite(value)){
return '-';
}
precision=checkPrecision(precision, 2);
exponentialForm=Number(unformat(value) * Math.pow(10, precision));
rounded=Math.round(exponentialForm);
finalResult=Number(rounded / Math.pow(10, precision)).toFixed(precision);
return finalResult;
}
function format(number, opts){
var formats;
var useFormat;
var negative;
var base;
var mod;
if(Array.isArray(number)){
return number.map(number, function(val){
return format(val, opts);
});
}
number=unformat(number);
if(! opts){
return number;
}
opts.precision=checkPrecision(opts.precision);
if(opts.format&&opts.symbol){
formats={
pos: opts.format,
neg: opts.format.replace('-', '').replace('%v', '-%v'),
zero: opts.format
};
useFormat=number > 0 ? formats.pos:number < 0 ? formats.neg:formats.zero;
opts.opts={
precision: opts.precision,
thousand: opts.thousand,
decimal: opts.decimal
};
number=useFormat.replace('%s', opts.symbol).replace('%v', format(Math.abs(number), opts.opts));
}else{
if(! Number.isFinite(number)){
return '-';
}
negative=number < 0 ? '-':'';
base=parseInt(toFixed(Math.abs(number||0), opts.precision), 10) + '';
mod=base.length > 3 ? base.length % 3:0;
number=negative +(mod ? base.substring(0, mod) + opts.thousand:'') + base.substring(mod).replace(/(\d{3})(?=\d)/g, '$1' + opts.thousand) +(opts.precision ? opts.decimal + toFixed(Math.abs(number), opts.precision).split('.')[ 1 ]:'');
}
return number;
}
$.epoAPI.math.unformat=unformat;
$.epoAPI.math.format=format;
$.epoAPI.math.toFixed=toFixed;
}(window.jQuery));
(function($){
'use strict';
var expo;
var rCRLF=/\r?\n/g;
var rcheckableType=/^(?:checkbox|radio)$/i;
var rsubmitterTypes=/^(?:submit|button|image|reset|file)$/i;
var rsubmittable=/^(?:input|select|textarea|keygen)/i;
if(! $.easing.easeInExpo){
expo=function(p){
return Math.pow(p, 6);
};
$.easing.easeInExpo=expo;
$.easing.easeOutExpo=function(p){
return 1 - expo(1 - p);
};
$.easing.easeInOutExpo=function(p){
return p < 0.5 ? expo(p * 2) / 2:1 -(expo(( p * -2) + 2) / 2);
};}
$.fn.extend({
tmcheckboxes: function(){
var tm_settings_wrap_checkbox=this.find(":checkbox:not('.tm-default-checkbox')").not('.wp-tab-panel :checkbox, .tm-weekdays-picker-wrap :checkbox, .tm-months-picker-wrap :checkbox');
tm_settings_wrap_checkbox.wrap('<label class="tm-epo-switch-wrapper-label"></label>');
tm_settings_wrap_checkbox.wrap('<span class="tm-epo-switch-wrapper tc"></span>');
tm_settings_wrap_checkbox.after('<span class="tc-label tm-epo-switch tc"></span>');
return this;
},
tcSerializeArray: function(){
return this.find(':input')
.filter(function(){
var type=this.type;
return this.name&&! $(this).is(':disabled')&&rsubmittable.test(this.nodeName)&&! rsubmitterTypes.test(type)&&(this.checked||! rcheckableType.test(type));
})
.map(function(i, elem){
var val=$(this).val();
if(val===null){
return null;
}
if(Array.isArray(val)){
return $.map(val, function(thisval){
return { name: elem.name, value: thisval.replace(rCRLF, '\r\n') };});
}
return { name: elem.name, value: val.replace(rCRLF, '\r\n') };})
.get();
},
tcSerializeObject: function(){
var o={};
var a=this.tcSerializeArray();
$.each(a, function(){
if(o[ this.name ]!==undefined){
if(this.name.endsWith('[]')){
if(! o[ this.name ].push){
o[ this.name ]=[ o[ this.name ] ];
}
o[ this.name ].push(this.value||'');
}else{
o[ this.name ]=this.value||'';
}}else{
o[ this.name ]=this.value||'';
}});
return o;
},
tcScrollTo: function(obj, duration, offset){
var element=this;
obj=$(obj);
if(obj.length===0){
return this;
}
if(! duration){
duration=0;
}
if(! offset){
offset=0;
}
if(element[ 0 ].self===window){
element=$('html, body');
}else{
if(element.find('.woodmart-scroll-content').length){
element=element.find('.woodmart-scroll-content');
}
if(! element.offset()){
element=$('html, body');
}else{
offset=offset +(element.scrollTop() - element.offset().top);
}}
return element.animate({
scrollTop: $(obj).offset().top + offset
},
duration
);
},
tcClone: function(){
var i;
var l;
var j;
var m;
var result=$.fn.clone.apply(this, arguments);
var textareas=this.find('textarea').add(this.filter('textarea'));
var resultTextareas=result.find('textarea').add(result.filter('textarea'));
var selects=this.find('select').add(this.filter('select'));
var resultSelects=result.find('select').add(result.filter('select'));
for(i=0, l=textareas.length; i < l; i +=1){
$(resultTextareas[ i ]).val($(textareas[ i ]).val());
}
for(i=0, l=selects.length; i < l; i +=1){
for(j=0, m=selects[ i ].options.length; j < m; j +=1){
if(selects[ i ].options[ j ].selected===true){
resultSelects[ i ].options[ j ].selected=true;
}}
}
return result;
}});
}(window.jQuery));
(function($){
'use strict';
var FloatBox=function(dom, options){
this.element=$(dom);
this.settings=$.extend({}, $.fn.tcFloatBox.defaults, options);
this.settings.type='<' + this.settings.type + '>';
this.top=0;
this.left=0;
this.ticking=false;
if(this.element.length===1){
this.init();
return this;
}
return false;
};
FloatBox.prototype={
constructor: FloatBox,
destroy: function(){
var settings=this.settings;
if(this.instance!==undefined){
$.fn.tcFloatBox.instances.splice(this.instance, 1);
delete this.instance;
if(settings.hideelements){
$('embed, object, select').css({
visibility: 'visible'
});
}
if(settings._ovl){
settings._ovl.off();
settings._ovl.remove();
delete settings._ovl;
}
$(settings.floatboxID).remove();
this.element.removeData('tcfloatbox');
$(window).off('scroll.tcfloatbox' + this.instance);
$(window).off('resize.tcfloatbox' + this.instance);
}
return this;
},
hide: function(){
var settings=this.settings;
if(settings.hideelements){
$('embed, object, select').css({
visibility: 'visible'
});
}
if(settings.showoverlay===true){
if(settings._ovl){
settings._ovl.hide();
}}
$(settings.floatboxID)
.addClass('tc-closing')
.removeClass(settings.animateIn)
.addClass(settings.animateOut);
$(settings.floatboxID).animate({
opacity: 0
},
settings.closefadeouttime,
function(){
$(settings.floatboxID).hide();
$(settings.floatboxID)
.removeClass('tc-closing')
.addClass('tc-closed');
}
);
$(window).off('scroll.tcfloatbox' + this.instance);
$(window).off('resize.tcfloatbox' + this.instance);
},
requestTick: function(){
var settings=this.settings;
if(! this.ticking){
if(settings.refresh){
setTimeout(
this.requestAnimationFrame.bind(this),
settings.refresh
);
}else{
requestAnimationFrame(this.update);
}
this.ticking=true;
}},
requestAnimationFrame: function(){
requestAnimationFrame(this.update.bind(this));
},
update: function(){
this.render();
this.ticking=false;
},
doit: function(){
this.requestTick();
},
render: function(){
var settings=this.settings;
var size=$.epoAPI.dom.size();
var scroll;
var top;
var left;
if(settings.refresh==='fixed'){
scroll={ top: 0, left: 0 };}else{
scroll=$.epoAPI.dom.scroll();
}
top=parseInt(
scroll.top +
(( size.visibleHeight - $(settings.floatboxID).height()) / 2),
10
);
left=parseInt(
scroll.left +
(( size.visibleWidth - $(settings.floatboxID).width()) / 2),
10
);
top=parseInt(( top - this.top) / settings.fps, 10);
left=parseInt(( left - this.left) / settings.fps, 10);
this.top +=top;
this.left +=left;
$(settings.floatboxID).css({
top: this.top + 'px',
left: this.left + 'px',
opacity: 1
});
},
show: function(){
var settings=this.settings;
var top;
var size;
if(this.element.length===1){
if(this.instance===undefined){
this.init();
}
if(settings.hideelements){
$('embed, object, select').css({
visibility: 'hidden'
});
}
size=$.epoAPI.dom.size();
if(settings.showoverlay===true){
if(! settings._ovl){
settings._ovl=$('<div class="fl-overlay"></div>').css({
zIndex: parseInt(settings.zIndex, 10) - 1,
opacity: settings.overlayopacity
}
);
settings._ovl.appendTo('body');
if(! settings.ismodal){
if(settings.cancelEvent||settings.unique){
settings._ovl.on('click',
this.applyCancelEvent.bind(this)
);
}else{
settings._ovl.on('click',
settings.cancelfunc.bind(this)
);
}}
}else{
settings._ovl.show();
}}
if(settings.showfunc){
settings.showfunc.call();
}
$(settings.floatboxID)
.removeClass('tc-closing')
.addClass(settings.animationBaseClass + ' ' + settings.animateIn
);
if(settings.refresh==='fixed'){
if(settings.top!==false){
top=settings.top;
}else{
top=parseInt(
(size.visibleHeight -
$(settings.floatboxID).height()) /
2,
10
);
top=top + 'px';
}
$(settings.floatboxID).css({
position: 'fixed',
top: top
});
if(settings.left!==false){
$(settings.floatboxID).css({
left: settings.left
});
}}else{
this.render();
}}
},
applyCancelEvent: function(){
var settings=this.settings;
if(settings.cancelEvent===true){
this.destroy();
}else if(typeof settings.cancelEvent==='function'){
settings.cancelEvent.call(this, this);
}},
applyCancelEventFromKey: function(e){
if(e.which===27){
this.applyCancelEvent();
}},
applyUpdateEvent: function(){
var settings=this.settings;
if(typeof settings.updateEvent==='function'){
settings.updateEvent.call(this, this);
}},
applyUpdateEventFromKey: function(e){
if(e.which===13){
this.applyUpdateEvent();
}},
init: function(){
var settings=this.settings;
var size;
var scroll;
var l=0;
var h;
if(this.element.length===1){
if($.fn.tcFloatBox.instances.length > 0){
settings.zIndex =
parseInt(
$.fn.tcFloatBox.instances[
$.fn.tcFloatBox.instances.length - 1
].zIndex,
10
) + 100;
}
this.instance=$.fn.tcFloatBox.instances.length;
$.fn.tcFloatBox.instances.push(settings);
settings.id=settings.id + this.instance;
settings.floatboxID='#' + $.epoAPI.dom.id(settings.id);
this.hide();
size=$.epoAPI.dom.size();
scroll=$.epoAPI.dom.scroll();
$(settings.type)
.attr('id', settings.id)
.addClass(settings.classname)
.html(settings.data)
.appendTo(this.element);
$(settings.floatboxID).css({
width: settings.width,
height: settings.height
});
if(settings.minWidth){
$(settings.floatboxID).css({
'min-width': settings.minWidth
});
}
if(settings.minHeight){
$(settings.floatboxID).css({
'min-height': settings.minHeight
});
}
h=parseInt(
scroll.left +
(( size.visibleWidth - $(settings.floatboxID).width()) / 2),
10
);
$(settings.floatboxID).css({
top: l + 'px',
left: h + 'px',
'z-index': settings.zIndex
});
this.top=l;
this.left=h;
this.cancelfunc=settings.cancelfunc;
if(settings.cancelEvent&&settings.cancelClass){
$(settings.floatboxID)
.find(settings.cancelClass)
.on('click', this.applyCancelEvent.bind(this));
if(settings.isconfirm){
$(document)
.off('keyup.escape-' + settings.floatboxID)
.on('keyup.escape-' + settings.floatboxID,
this.applyCancelEventFromKey.bind(this)
);
}}
if(settings.updateEvent&&settings.updateClass){
$(settings.floatboxID)
.find(settings.updateClass)
.on('click', this.applyUpdateEvent.bind(this));
if(settings.isconfirm){
$(document)
.off('keyup.enter-' + settings.floatboxID)
.on('keyup.enter-' + settings.floatboxID,
this.applyUpdateEventFromKey.bind(this)
);
}}
this.show();
if(settings.refresh!=='fixed'){
$(window).on('scroll.tcfloatbox' + this.instance,
this.doit.bind(this)
);
}
$(window).on('resize.tcfloatbox' + this.instance,
this.doit.bind(this)
);
}}
};
$.fn.tcFloatBox=function(option){
var methodReturn;
var targets=$(this);
var data=targets.data('tcfloatbox');
var options;
var ret;
if(typeof option==='object'){
options=option;
}else{
options={};}
if(! data){
data=new FloatBox(this, options);
targets.data('tcfloatbox', data);
}
if(typeof option==='string'){
methodReturn=data[ option ].apply(data, []);
}
if(methodReturn===undefined){
ret=targets;
}else{
ret=methodReturn;
}
return ret;
};
$.fn.tcFloatBox.defaults={
id: 'flasho',
classname: 'flasho',
type: 'div',
data: '',
width: '500px',
height: 'auto',
minWidth: 0,
minHeight: 0,
closefadeouttime: 1000,
animationBaseClass: 'tm-animated',
animateIn: 'fadein',
animateOut: 'fadeout',
top: false,
left: false,
refresh: false,
fps: 4,
hideelements: false,
showoverlay: true,
zIndex: 100100,
ismodal: false,
cancelfunc: FloatBox.prototype.hide,
showfunc: null,
cancelEvent: true,
cancelClass: '.floatbox-cancel',
updateEvent: false,
updateClass: false,
unique: true,
overlayopacity: 0.5,
isconfirm: false
};
$.fn.tcFloatBox.instances=[];
$.fn.tcFloatBox.Constructor=FloatBox;
$.tcFloatBox=function(options){
var targets=$('body');
var data=false;
var hasAtLeastOneNonToolTip=targets
.map(function(){
return $(this).data('tcfloatbox')||'';
})
.get()
.some(function(value){
return value==='';
});
if(hasAtLeastOneNonToolTip||options.unique){
data=new FloatBox(targets, options);
targets.data('tcfloatbox', data);
}else{
data=targets.data('tcfloatbox');
data.init();
}
return data;
};}(window.jQuery));
(function(window, $){
'use strict';
var ToolTip=function(dom, options){
this.targets=$(dom);
this.settings=$.extend({}, $.fn.tcToolTip.defaults, options);
if(this.targets.length > 0){
this.init();
return this;
}
return false;
};
var TMEPOJS;
$(function(){
TMEPOJS=window.TMEPOJS||{ tm_epo_global_tooltip_max_width: '340px' };});
ToolTip.prototype={
constructor: ToolTip,
removeTooltip: function(target, tooltip){
var settings=this.settings;
if(target.data('is_moving')){
return;
}
tooltip.removeClass(settings.fadin).addClass(settings.fadeout);
tooltip.animate({
opacity: 0
},
settings.speed,
function(){
$(this).remove();
}
);
if(target.data('tmtip-title')&&target.data('tm-tip-html')===undefined&&! target.attr('data-tm-tooltip-html')){
target.attr('title', target.data('tmtip-title'));
}
$(window).off('scroll.tcToolTip resize.tcToolTip');
if(settings.onetime){
this.destroy();
}},
initTooltip: function(target, tooltip, nofx){
var settings=this.settings;
var tip;
var scroll;
var pos_left;
var pos_top;
var pos_from_top;
var original_pos_left;
if(target&&tooltip&&target.length===1&&tooltip.length===1&&target.data('tm-has-tm-tip')===1){
if(nofx===1){
if(target.data('tm-tip-html')!==undefined){
tip=target.data('tm-tip-html');
}else if(target.attr('data-tm-tooltip-html')){
tip=target.attr('data-tm-tooltip-html');
}else{
tip=target.attr('title');
}
tooltip.html(tip);
target.data('is_moving', true);
}
tooltip.find('aside').hide();
if(TMEPOJS.tm_epo_global_tooltip_max_width===''){
if($(window).width() <=tooltip.outerWidth() * 1.2){
tooltip.css('max-width',($(window).width() / 1.2) + 'px');
}else{
tooltip.css('max-width', '340px');
}}else{
if(TMEPOJS.tm_epo_global_tooltip_max_width.isNumeric()){
TMEPOJS.tm_epo_global_tooltip_max_width=TMEPOJS.tm_epo_global_tooltip_max_width + 'px';
}
tooltip.css('max-width', TMEPOJS.tm_epo_global_tooltip_max_width);
}
tooltip.find('aside').show();
tooltip.css({
left: '',
right: '',
top: ''
});
scroll=$.epoAPI.dom.scroll();
pos_left=target.offset().left +(target.outerWidth() / 2) -(tooltip.outerWidth() / 2);
original_pos_left=pos_left;
if(pos_left < 0){
pos_left=target.offset().left +(target.outerWidth() / 2) - 20;
tooltip.addClass('left');
}else{
tooltip.removeClass('left');
}
if(original_pos_left >=0&&pos_left + tooltip.outerWidth() > $(window).width()){
pos_left=target.offset().left - tooltip.outerWidth() +(target.outerWidth() / 2) + 20;
if(pos_left < 0){
pos_left=pos_left - 10;
tooltip.css('max-width', 'calc(' + tooltip.css('max-width') + ' - ' + Math.abs(pos_left) + 'px)');
pos_left=10;
}
tooltip.addClass('right');
}else{
tooltip.removeClass('right');
}
tooltip.css({
left: pos_left,
right: 'auto',
top: pos_top
});
pos_top=target.offset().top - tooltip.outerHeight() - 10;
pos_from_top=target.offset().top - scroll.top - tooltip.outerHeight() - 10;
if(pos_top < 0||pos_from_top < 0){
pos_top=target.offset().top + target.outerHeight() + 10;
tooltip.addClass('top');
tooltip.removeClass('bottom');
}else{
tooltip.removeClass('top');
tooltip.addClass('bottom');
}
$(window).trigger('tm_tooltip_show');
if(nofx){
tooltip.css({
left: pos_left,
top: pos_top
});
target.data('is_moving', false);
}else{
tooltip
.css({
left: pos_left,
top: pos_top
})
.removeClass(settings.fadeout)
.addClass(settings.fadin);
}}
},
show: function(target){
var tooltip;
var tip;
var img;
var settings=this.settings;
if(target.data('is_moving')){
return;
}
if(target.data('tm-has-tm-tip')===1){
if(target.data('tm-tip-html')!==undefined){
tip=target.data('tm-tip-html');
if(target.attr('title')){
target.data('tmtip-title', target.attr('title'));
}
target.removeAttr('title');
}else if(target.attr('data-tm-tooltip-html')){
tip=target.attr('data-tm-tooltip-html');
if(target.attr('title')){
target.data('tmtip-title', target.attr('title'));
}
target.removeAttr('title');
}else{
tip=target.attr('title');
}
if(tip!==undefined){
$('#tm-tooltip').remove();
if(! settings.tipclass){
settings.tipclass='';
}else{
settings.tipclass=' ' + settings.tipclass;
}
tooltip=$('<div id="tm-tooltip" class="tm-tip tm-animated' + settings.tipclass + '"></div>');
tooltip.css('opacity', 0).html(tip).appendTo('body');
img=tooltip.find('img');
if(img.length > 0){
img.on('load', this.initTooltip.bind(this, target, tooltip));
}
this.initTooltip(target, tooltip);
$(window).on('scroll.tcToolTip resize.tcToolTip', this.initTooltip.bind(this, target, tooltip));
target.data('is_moving', false);
target.on('tmmovetooltip', this.initTooltip.bind(this, target, tooltip, 1));
target.on('mouseleave.tc tmhidetooltip', this.removeTooltip.bind(this, target, tooltip));
target.closest('label').on('mouseleave.tc tmhidetooltip', this.removeTooltip.bind(this, target, tooltip));
tooltip.on('click', this.removeTooltip.bind(this, target, tooltip));
}}
return false;
},
destroy: function(){
if(this.targets.length > 0){
this.targets.toArray().forEach(function(element){
var target=$(element);
target.closest('off').on('mouseleave.tc tmhidetooltip');
target.off('tc-tooltip-html-changed tmmovetooltip tmhidetooltip mouseenter.tc mouseleave.tc tmshowtooltip.tc');
target.removeData('tmtip-title');
target.removeData('tm-tip-html');
});
this.targets.removeData('tctooltip tm-has-tm-tip is_moving');
}},
init: function(){
var that=this;
var settings=this.settings;
if(this.targets.length > 0){
this.targets.toArray().forEach(function(element){
var target;
var is_swatch;
var is_swatch_desc;
var is_swatch_lbl_desc;
var is_swatch_img;
var is_swatch_img_lbl;
var is_swatch_img_desc;
var is_swatch_img_lbl_desc;
var tip;
var label;
var desc;
var descHTML;
var get_img_src;
var findlabel;
var is_hide_label;
var findlabelText;
target=$(element);
tip=settings.tip||undefined;
if(target.data('tm-has-tm-tip')===undefined){
is_swatch=target.attr('data-tm-tooltip-swatch');
is_swatch_desc=target.attr('data-tm-tooltip-swatch-desc');
is_swatch_lbl_desc=target.attr('data-tm-tooltip-swatch-lbl-desc');
is_swatch_img=target.attr('data-tm-tooltip-swatch-img');
is_swatch_img_lbl=target.attr('data-tm-tooltip-swatch-img-lbl');
is_swatch_img_desc=target.attr('data-tm-tooltip-swatch-img-desc');
is_swatch_img_lbl_desc=target.attr('data-tm-tooltip-swatch-img-lbl-desc');
target.data('tm-has-tm-tip', 1);
if(target.attr('data-original')!==undefined){
get_img_src=target.attr('data-original');
}else if(target.attr('src')!==undefined){
if(target.attr('data-src')!==undefined){
get_img_src=target.attr('data-src');
}else{
get_img_src=target.attr('src');
}}else{
get_img_src=target[ 0 ].src;
}
label=target.closest('.tmcp-field-wrap');
if(label.is('.tc-epo-element-product-holder')){
label=target.closest('.cpf-element');
}
if(label.length===0){
label=target.closest('.cpf-element');
}
if(label.length===0){
label=target.closest('.cpf-section').find('.tc-section-inner-wrap .tm-section-description.tm-description');
}
findlabel=label.find('.tm-tip-html');
if(findlabel.length===0){
findlabel=label.find('.checkbox-image-label,.checkbox-image-label-inline,.radio-image-label,.radio-image-label-inline');
}
if(findlabel.length===0){
findlabel=label.next('.checkbox-image-label,.checkbox-image-label-inline,.radio-image-label,.radio-image-label-inline,.tm-tip-html');
}
if(findlabel.length===0&&label.is('.tm-description')){
findlabel=label;
}
label=findlabel;
findlabel=$(label);
findlabelText=findlabel.find('.tc-label-text');
if(! findlabelText.length){
findlabelText=findlabel;
}
is_hide_label=target.attr('data-tm-hide-label')==='yes'||target.attr('data-tm-hide-label')===undefined||findlabel.is('.tm-tip-html');
descHTML='';
desc=target.closest('.tmcp-field-wrap');
desc=desc.find('[data-tm-tooltip-html]');
if(desc.length===0){
desc=target.closest('.tmcp-field-wrap').find('.tc-inline-description');
if(desc.length > 0){
descHTML=desc.html();
}}else{
descHTML=desc.attr('data-tm-tooltip-html');
}
if(tip===undefined){
if(is_swatch){
tip=findlabelText.html();
}else if(is_swatch_desc&&descHTML!==''){
tip='<aside>' + descHTML + '</aside>';
}else if(is_swatch_lbl_desc&&(findlabelText.html()!==''||descHTML!=='')){
tip='<aside>' + findlabelText.html() + '</aside><aside>' + descHTML + '</aside>';
}else if(is_swatch_img&&get_img_src!==''){
tip='<img src="' + get_img_src + '">';
}else if(is_swatch_img_lbl&&(findlabelText.html()!==''||get_img_src!=='')){
tip='<img src="' + get_img_src + '"><aside>' + findlabelText.html() + '</aside>';
}else if(is_swatch_img_desc&&(get_img_src!==''||descHTML!=='')){
tip='<img src="' + get_img_src + '"><aside>' + descHTML + '</aside>';
}else if(is_swatch_img_lbl_desc&&(findlabelText.html()!==''||get_img_src!==''||descHTML!=='')){
tip='<img src="' + get_img_src + '"><aside>' + findlabelText.html() + '</aside><aside>' + descHTML + '</aside>';
}
if(tip!==undefined){
target.data('tm-tip-html', tip);
if(is_hide_label){
findlabel.find('.tm-tooltip').remove();
findlabelText.hide();
}}
if(tip===undefined){
if(target.attr('data-tm-tooltip-html')){
tip=target.attr('data-tm-tooltip-html');
}else{
tip=target.attr('title');
}}
}else{
target.data('tm-tip-html', tip);
}
target.on('tc-tooltip-html-changed', function(){
if(target.attr('data-tm-tooltip-html')){
target.show();
}else{
target.hide();
}});
if(target.is('img')){
target.closest('label').on('mouseenter tmshowtooltip', that.show.bind(that, target));
}
target.on('mouseenter.tc tmshowtooltip.tc', that.show.bind(that, target));
if(settings.trigger){
that.show(target);
}}
});
}}
};
$.fn.tcToolTip=function(option){
var methodReturn;
var targets=$(this);
var data;
var options;
var ret;
var hasAtLeastOneNonToolTip=targets
.map(function(){
return $(this).data('tctooltip')||'';
})
.get()
.some(function(value){
return value==='';
});
if(typeof option==='object'){
options=option;
}else{
options={};}
if(hasAtLeastOneNonToolTip){
data=new ToolTip(this, options);
targets.data('tctooltip', data);
}
if(typeof option==='string'){
data=targets.data('tctooltip');
methodReturn=data[ option ].apply(data, []);
}
if(methodReturn===undefined){
ret=targets;
}else{
ret=methodReturn;
}
return ret;
};
$.fn.tcToolTip.defaults={
fadin: 'fadein',
fadeout: 'fadeout',
speed: 1500
};
$.fn.tcToolTip.instances=[];
$.fn.tcToolTip.Constructor=ToolTip;
$.tcToolTip=function(targets, options){
var data=false;
var hasAtLeastOneNonToolTip;
targets=targets||$('.tm-tooltip');
hasAtLeastOneNonToolTip=targets
.map(function(){
return $(this).data('tctooltip')||'';
})
.get()
.some(function(value){
return value==='';
});
if(hasAtLeastOneNonToolTip){
data=new ToolTip(targets, options);
targets.data('tctooltip', data);
}
return data;
};}(window, window.jQuery));
(function(factory){
'use strict';
if(typeof window.define==='function'&&window.define.amd){
window.define([ 'jquery' ], factory);
}else if(typeof window.module==='object'&&window.module.exports){
window.module.exports=factory(window.require('jquery'));
}else{
factory(window.jQuery);
}}(function($){
'use strict';
var pendingRequests={};
var ajax;
var trim;
$.extend($.fn, {
tc_validate: function(options){
var tc_validator;
if(! this.length){
return;
}
tc_validator=$.data(this[ 0 ], 'tc_validator');
if(tc_validator){
return tc_validator;
}
this.attr('novalidate', 'novalidate');
tc_validator=new $.tc_validator(options, this[ 0 ]);
$.data(this[ 0 ], 'tc_validator', tc_validator);
if(tc_validator.settings.onsubmit){
this.on('click.tc_validate', ':submit', function(event){
tc_validator.submitButton=event.currentTarget;
if($(this).hasClass('cancel')){
tc_validator.cancelSubmit=true;
}
if($(this).attr('formnovalidate')!==undefined){
tc_validator.cancelSubmit=true;
}});
this.on('submit.tc_validate', function(event){
if(tc_validator.settings.debug){
event.preventDefault();
}
function handle(){
var hidden;
var result;
if(tc_validator.submitButton&&(tc_validator.settings.submitHandler||tc_validator.formSubmitted)){
hidden=$("<input type='hidden'>").attr('name', tc_validator.submitButton.name).val($(tc_validator.submitButton).val()).appendTo(tc_validator.currentForm);
}
if(tc_validator.settings.submitHandler&&! tc_validator.settings.debug){
result=tc_validator.settings.submitHandler.call(tc_validator, tc_validator.currentForm, event);
if(hidden){
hidden.remove();
}
if(result!==undefined){
return result;
}
return false;
}
return true;
}
if(tc_validator.cancelSubmit){
tc_validator.cancelSubmit=false;
return handle();
}
if(tc_validator.form()){
if(tc_validator.pendingRequest){
tc_validator.formSubmitted=true;
return false;
}
return handle();
}
tc_validator.focusInvalid();
return false;
});
}
return tc_validator;
},
tc_valid: function(){
var valid;
var tc_validator;
var errorList;
if($(this[ 0 ]).is('form')){
valid=this.tc_validate().form();
}else{
errorList=[];
valid=true;
tc_validator=$(this[ 0 ].form).tc_validate();
this.each(function(){
valid=tc_validator.element(this)&&valid;
if(! valid){
errorList=errorList.concat(tc_validator.errorList);
}});
tc_validator.errorList=errorList;
}
return valid;
},
tc_rules: function(command, argument){
var element=this[ 0 ];
var isContentEditable=typeof this.attr('contenteditable')!=='undefined'&&this.attr('contenteditable')!=='false';
var settings;
var staticRules;
var existingRules;
var data;
var param;
var filtered;
if(element===null){
return;
}
if(! element.form&&isContentEditable){
element.form=this.closest('form')[ 0 ];
element.name=this.attr('name');
}
if(element.form===null){
return;
}
if(command){
settings=$.data(element.form, 'tc_validator').settings;
staticRules=settings.rules;
existingRules=$.tc_validator.staticRules(element);
switch(command){
case 'add':
$.extend(existingRules, $.tc_validator.normalizeRule(argument));
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;
}
filtered={};
$.each(argument.split(/\s/), function(index, method){
filtered[ method ]=existingRules[ method ];
delete existingRules[ method ];
});
return filtered;
}}
data=$.tc_validator.normalizeRules($.extend({}, $.tc_validator.classRules(element), $.tc_validator.attributeRules(element), $.tc_validator.dataRules(element), $.tc_validator.staticRules(element)), element);
if(data.required){
param=data.required;
delete data.required;
data=$.extend({ required: param }, data);
}
if(data.remote){
param=data.remote;
delete data.remote;
data=$.extend(data, { remote: param });
}
return data;
}});
trim=function(str){
return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
$.extend($.expr.pseudos||$.expr[ ':' ], {
blank: function(a){
return ! trim('' + $(a).val());
},
filled: function(a){
var val=$(a).val();
return val!==null&&!! trim('' + val);
},
unchecked: function(a){
return ! $(a).prop('checked');
}});
$.tc_validator=function(options, form){
this.settings=$.extend(true, {}, $.tc_validator.defaults, options);
this.currentForm=form;
this.init();
};
$.tc_validator.format=function(source, params){
if(arguments.length===1){
return function(){
var args=$.makeArray(arguments);
args.unshift(source);
return $.tc_validator.format.apply(this, args);
};}
if(params===undefined){
return source;
}
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($.tc_validator, {
defaults: {
messages: {},
groups: {},
rules: {},
errorClass: 'error',
pendingClass: 'pending',
validClass: 'valid',
errorElement: 'label',
focusCleanup: false,
focusInvalid: true,
errorContainer: $([]),
errorLabelContainer: $([]),
onsubmit: true,
ignore: ':hidden',
ignoreTitle: false,
onfocusin: function(element){
this.lastActive=element;
if(this.settings.focusCleanup){
if(this.settings.unhighlight){
this.settings.unhighlight.call(this, element, this.settings.errorClass, this.settings.validClass);
}
this.hideThese(this.errorsFor(element));
}},
onfocusout: function(element){
if(! this.checkable(element)&&(element.name in this.submitted||! this.optional(element))){
this.element(element);
}},
onkeyup: function(element, event){
var excludedKeys=[ 16, 17, 18, 20, 35, 36, 37, 38, 39, 40, 45, 144, 225 ];
if(( event.which===9&&this.elementValue(element)==='')||$.inArray(event.keyCode, excludedKeys)!==-1){
}else if(element.name in this.submitted||element.name in this.invalid){
this.element(element);
}},
onclick: function(element){
if(element.name in this.submitted){
this.element(element);
}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);
}}
},
setDefaults: function(settings){
$.extend($.tc_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.',
equalTo: 'Please enter the same value again.',
maxlength: $.tc_validator.format('Please enter no more than {0} characters.'),
maxlengthsingle: $.tc_validator.format('Please enter no more than {0} character.'),
minlength: $.tc_validator.format('Please enter at least {0} characters.'),
minlengthsingle: $.tc_validator.format('Please enter at least {0} character.'),
rangelength: $.tc_validator.format('Please enter a value between {0} and {1} characters long.'),
range: $.tc_validator.format('Please enter a value between {0} and {1}.'),
max: $.tc_validator.format('Please enter a value less than or equal to {0}.'),
min: $.tc_validator.format('Please enter a value greater than or equal to {0}.'),
step: $.tc_validator.format('Please enter a multiple of {0}.')
},
autoCreateRanges: false,
prototype: {
init: function(){
var currentForm=this.currentForm;
var groups={};
var rules;
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();
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;
});
});
rules=this.settings.rules;
$.each(rules, function(key, value){
rules[ key ]=$.tc_validator.normalizeRule(value);
});
function delegate(event){
var isContentEditable=typeof $(event.data.that).attr('contenteditable')!=='undefined'&&$(event.data.that).attr('contenteditable')!=='false';
var tc_validator;
var eventType;
var settings;
if(! event.data.that.form&&isContentEditable){
event.data.that.form=$(event.data.that).closest('form')[ 0 ];
event.data.that.name=$(event.data.that).attr('name');
}
if(currentForm!==event.data.that.form){
return;
}
tc_validator=$.data(event.data.that.form, 'tc_validator');
eventType='on' + event.type.replace(/^validate/, '');
settings=tc_validator.settings;
if(settings[ eventType ]&&! $(event.data.that).is(settings.ignore)){
settings[ eventType ].call(tc_validator, event.data.that, event);
}}
$(this.currentForm)
.on('focusin.tc_validate focusout.tc_validate keyup.tc_validate',
":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'], " +
"[type='radio'], [type='checkbox'], [contenteditable], [type='button']",
{ that: this },
delegate
)
.on('click.tc_validate', "select, option, [type='radio'], [type='checkbox']", { that: this }, delegate);
if(this.settings.invalidHandler){
$(this.currentForm).on('invalid-form.tc_validate', this.settings.invalidHandler);
}},
form: function(){
this.checkForm();
$.extend(this.submitted, this.errorMap);
this.invalid=$.extend({}, this.errorMap);
if(! this.tc_valid()){
$(this.currentForm).triggerHandler('invalid-form', [ this ]);
}
this.showErrors();
return this.tc_valid();
},
checkForm: function(){
var i;
var elements;
this.prepareForm();
for(i=0, elements=this.elements(); elements[ i ]; i +=1){
this.currentElements=elements;
this.check(elements[ i ]);
}
return this.tc_valid();
},
element: function(element){
var cleanElement=this.clean(element),
checkElement=this.validationTargetFor(cleanElement),
v=this,
result=true,
rs,
group;
if(checkElement===undefined){
delete this.invalid[ cleanElement.name ];
}else{
this.prepareElement(checkElement);
this.currentElements=$(checkElement);
group=this.groups[ checkElement.name ];
if(group){
$.each(this.groups, function(name, testgroup){
if(testgroup===group&&name!==checkElement.name){
cleanElement=v.validationTargetFor(v.clean(v.findByName(name)));
if(cleanElement&&cleanElement.name in v.invalid){
v.currentElements.push(cleanElement);
result=v.check(cleanElement)&&result;
}}
});
}
rs=this.check(checkElement)!==false;
result=result&&rs;
if(rs){
this.invalid[ checkElement.name ]=false;
}else{
this.invalid[ checkElement.name ]=true;
}
if(! this.numberOfInvalids()){
this.toHide=this.toHide.add(this.containers);
}
this.showErrors();
$(element).attr('aria-invalid', ! rs);
}
return result;
},
showErrors: function(errors){
var tc_validator;
if(errors){
tc_validator=this;
$.extend(this.errorMap, errors);
this.errorList=$.map(this.errorMap, function(message, name){
return {
message: message,
element: tc_validator.findByName(name)[ 0 ]
};});
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();
}},
resetForm: function(){
var elements;
if($.fn.resetForm){
$(this.currentForm).resetForm();
}
this.invalid={};
this.submitted={};
this.prepareForm();
this.hideErrors();
elements=this.elements().removeData('previousValue').removeAttr('aria-invalid');
this.resetElements(elements);
},
resetElements: function(elements){
var i;
if(this.settings.unhighlight){
for(i=0; elements[ i ]; i +=1){
this.settings.unhighlight.call(this, elements[ i ], this.settings.errorClass, '');
this.findByName(elements[ i ].name).removeClass(this.settings.validClass);
}}else{
elements.removeClass(this.settings.errorClass).removeClass(this.settings.validClass);
}},
numberOfInvalids: function(){
return this.objectLength(this.invalid);
},
objectLength: function(obj){
var count=0,
i;
for(i in obj){
if(obj[ i ]!==undefined&&obj[ i ]!==null&&obj[ i ]!==false){
count +=1;
}}
return count;
},
hideErrors: function(){
this.hideThese(this.toHide);
},
hideThese: function(errors){
errors.not(this.containers).text('');
this.addWrapper(errors).hide();
},
tc_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')
.trigger('focus')
.trigger('focusin');
} catch(e){
}}
},
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 tc_validator=this,
rulesCache={};
return $(this.currentForm)
.find('input, select, textarea, [contenteditable]')
.not(':submit, :reset, :image, :disabled')
.not(this.settings.ignore)
.filter(function(){
var name=this.name||$(this).attr('name');
var isContentEditable=typeof $(this).attr('contenteditable')!=='undefined'&&$(this).attr('contenteditable')!=='false';
if(isContentEditable){
this.form=$(this).closest('form')[ 0 ];
this.name=name;
}
if(this.form!==tc_validator.currentForm){
return false;
}
if(name in rulesCache||! tc_validator.objectLength($(this).tc_rules())){
return false;
}
rulesCache[ name ]=true;
return true;
});
},
clean: function(selector){
return $(selector)[ 0 ];
},
errors: function(){
var errorClass=this.settings.errorClass.split(' ').join('.');
return $(this.settings.errorElement + '.' + errorClass, this.errorContext);
},
resetInternals: function(){
this.successList=[];
this.errorList=[];
this.errorMap={};
this.toShow=$([]);
this.toHide=$([]);
},
reset: function(){
this.resetInternals();
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 $element=$(element),
type=element.type,
isContentEditable=typeof $element.attr('contenteditable')!=='undefined'&&$element.attr('contenteditable')!=='false',
val,
idx;
if(type==='radio'||type==='checkbox'){
return this.findByName(element.name).filter(':checked').val();
}else if(type==='number'&&typeof element.validity!=='undefined'){
return element.validity.badInput ? 'NaN':$element.val();
}
if(isContentEditable){
val=$element.text();
}else{
val=$element.val();
}
if(type==='file'){
if(val.substring(0, 12)==='C:\\fakepath\\'){
return val.substring(12);
}
idx=val.lastIndexOf('/');
if(idx >=0){
return val.substring(idx + 1);
}
idx=val.lastIndexOf('\\');
if(idx >=0){
return val.substring(idx + 1);
}
return val;
}
if(typeof val==='string'){
return val.replace(/\r/g, '');
}
return val;
},
check: function(element){
var rules;
var rulesCount;
var dependencyMismatch;
var val;
var result;
var method;
var rule;
var normalizer;
element=this.validationTargetFor(this.clean(element));
rules=$(element).tc_rules();
rulesCount=$.map(rules, function(n, i){
return i;
}).length;
dependencyMismatch=false;
val=this.elementValue(element);
if(typeof rules.normalizer==='function'){
normalizer=rules.normalizer;
}else if(typeof this.settings.normalizer==='function'){
normalizer=this.settings.normalizer;
}
if(normalizer){
val=normalizer.call(element, val);
delete rules.normalizer;
}
for(method in rules){
if(method){
rule={ method: method, parameters: rules[ method ] };
try {
result=$.tc_validator.methods[ method ].call(this, val, element, rule.parameters);
if(result==='dependency-mismatch'&&rulesCount===1){
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(e instanceof TypeError){
e.message +='.  Exception occurred when checking element ' + element.id + ", check the '" + rule.method + "' method.";
}
throw e;
}}
}
if(dependencyMismatch){
return;
}
if(this.objectLength(rules)){
this.successList.push(element);
}
return true;
},
customDataMessage: function(element, method){
return $(element).data('msg' + method.charAt(0).toUpperCase() + method.substring(1).toLowerCase())||$(element).data('msg');
},
customMessage: function(name, method){
var m=this.settings.messages[ name ];
return m&&(m.constructor===String ? m:m[ method ]);
},
findDefined: function(){
var i;
for(i=0; i < arguments.length; i +=1){
if(arguments[ i ]!==undefined){
return arguments[ i ];
}}
return undefined;
},
defaultMessage: function(element, rule){
var message;
var theregex;
var singleCheck='';
if(typeof rule==='string'){
rule={ method: rule };}
if(rule.method==='minlength'||rule.method==='maxlength'){
if(rule.parameters===1||rule.parameters==='1'){
singleCheck='single';
}}
message=this.findDefined(this.customMessage(element.name, rule.method + singleCheck),
this.customDataMessage(element, rule.method + singleCheck),
(! this.settings.ignoreTitle&&element.title)||undefined,
$.tc_validator.messages[ rule.method + singleCheck ],
'<strong>Warning: No message defined for ' + element.name + '</strong>'
);
theregex=/\$?\{(\d+)\}/g;
if(typeof message==='function'){
message=message.call(this, rule.parameters, element);
}else if(theregex.test(message)){
message=$.tc_validator.format(message.replace(theregex, '{$1}'), rule.parameters);
}
return message;
},
formatAndAdd: function(element, rule){
var message=this.defaultMessage(element, rule);
this.errorList.push({
message: message,
element: element,
method: rule.method
});
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, error;
for(i=0; this.errorList[ i ]; i +=1){
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 +=1){
this.showLabel(this.successList[ i ]);
}}
if(this.settings.unhighlight){
for(i=0, elements=this.validElements(); elements[ i ]; i +=1){
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 place,
group,
errorID,
v,
error=this.errorsFor(element),
elementID=this.idOrName(element),
describedBy=$(element).attr('aria-describedby');
if(error.length){
error.removeClass(this.settings.validClass).addClass(this.settings.errorClass);
error.html(message);
}else{
error=$('<' + this.settings.errorElement + '>')
.attr('id', elementID + '-error')
.addClass(this.settings.errorClass)
.html(message||'');
place=error;
if(this.settings.wrapper){
place=error
.hide()
.show()
.wrap('<' + this.settings.wrapper + '/>')
.parent();
}
if(this.labelContainer.length){
this.labelContainer.append(place);
}else if(this.settings.errorPlacement){
this.settings.errorPlacement.call(this, place, $(element));
}else{
place.insertAfter(element);
}
if(error.is('label')){
error.attr('for', elementID);
}else if(error.parents("label[for='" + this.escapeCssMeta(elementID) + "']").length===0){
errorID=error.attr('id');
if(! describedBy){
describedBy=errorID;
}else if(! describedBy.match(new RegExp('\\b' + this.escapeCssMeta(errorID) + '\\b'))){
describedBy +=' ' + errorID;
}
$(element).attr('aria-describedby', describedBy);
group=this.groups[ element.name ];
if(group){
v=this;
$.each(v.groups, function(name, testgroup){
if(testgroup===group){
$("[name='" + v.escapeCssMeta(name) + "']", v.currentForm).attr('aria-describedby', error.attr('id'));
}});
}}
}
if(! message&&this.settings.success){
error.text('');
if(typeof this.settings.success==='string'){
error.addClass(this.settings.success);
}else{
this.settings.success(error, element);
}}
this.toShow=this.toShow.add(error);
},
errorsFor: function(element){
var name=this.escapeCssMeta(this.idOrName(element)),
describer=$(element).attr('aria-describedby'),
selector="label[for='" + name + "'], label[for='" + name + "'] *";
if(describer){
selector=selector + ', #' + this.escapeCssMeta(describer).replace(/\s+/g, ', #');
}
return this.errors().filter(selector);
},
escapeCssMeta: function(string){
return string.replace(/([\\!"#$%&'()*+,.\/:;<=>?@\[\]\^`{|}~])/g, '\\$1');
},
idOrName: function(element){
return this.groups[ element.name ]||(this.checkable(element) ? element.name:element.id||element.name);
},
validationTargetFor: function(element){
if(this.checkable(element)){
element=this.findByName(element.name);
}
return $(element).not(this.settings.ignore)[ 0 ];
},
checkable: function(element){
return /radio|checkbox/i.test(element.type);
},
findByName: function(name){
return $(this.currentForm).find("[name='" + this.escapeCssMeta(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){
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 ! $.tc_validator.methods.required.call(this, val, element)&&'dependency-mismatch';
},
startRequest: function(element){
if(! this.pending[ element.name ]){
this.pendingRequest +=1;
$(element).addClass(this.settings.pendingClass);
this.pending[ element.name ]=true;
}},
stopRequest: function(element, valid){
this.pendingRequest -=1;
if(this.pendingRequest < 0){
this.pendingRequest=0;
}
delete this.pending[ element.name ];
$(element).removeClass(this.settings.pendingClass);
if(valid&&this.pendingRequest===0&&this.formSubmitted&&this.form()){
$(this.currentForm).trigger('submit');
if(this.submitButton){
$("input:hidden[name='" + this.submitButton.name + "']", this.currentForm).remove();
}
this.formSubmitted=false;
}else if(! valid&&this.pendingRequest===0&&this.formSubmitted){
$(this.currentForm).triggerHandler('invalid-form', [ this ]);
this.formSubmitted=false;
}},
previousValue: function(element, method){
method=(typeof method==='string'&&method)||'remote';
return (
$.data(element, 'previousValue') ||
$.data(element, 'previousValue', {
old: null,
valid: true,
message: this.defaultMessage(element, { method: method })
})
);
},
destroy: function(){
this.resetForm();
$(this.currentForm)
.off('.tc_validate')
.removeData('tc_validator')
.find('.tc_validate-equalTo-blur')
.off('.tc_validate-equalTo')
.removeClass('validate-equalTo-blur')
.find('.tc_validate-lessThan-blur')
.off('.tc_validate-lessThan')
.removeClass('validate-lessThan-blur')
.find('.tc_validate-lessThanEqual-blur')
.off('.tc_validate-lessThanEqual')
.removeClass('validate-lessThanEqual-blur')
.find('.tc_validate-greaterThanEqual-blur')
.off('.tc_validate-greaterThanEqual')
.removeClass('validate-greaterThanEqual-blur')
.find('.tc_validate-greaterThan-blur')
.off('.tc_validate-greaterThan')
.removeClass('validate-greaterThan-blur');
}},
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={},
classes=$(element).attr('class');
if(classes){
$.each(classes.split(' '), function(){
if(this in $.tc_validator.classRuleSettings){
$.extend(rules, $.tc_validator.classRuleSettings[ this ]);
}});
}
return rules;
},
normalizeAttributeRule: function(rules, type, method, value){
if(/min|max|step/.test(method)&&(type===null||/number|range|text/.test(type))){
value=Number(value);
if(isNaN(value)){
value=undefined;
}}
if(value||value===0){
rules[ method ]=value;
}else if(type===method&&type!=='range'){
rules[ method ]=true;
}},
attributeRules: function(element){
var rules={},
$element=$(element),
type=element.getAttribute('type'),
method,
value;
for(method in $.tc_validator.methods){
if(method){
if(method==='required'){
value=element.getAttribute(method);
if(value===''){
value=true;
}
value = !! value;
}else{
value=$element.attr(method);
}
this.normalizeAttributeRule(rules, type, method, value);
}}
if(rules.maxlength&&/-1|2147483647|524288/.test(rules.maxlength)){
delete rules.maxlength;
}
return rules;
},
dataRules: function(element){
var rules={},
$element=$(element),
type=element.getAttribute('type'),
method,
value;
for(method in $.tc_validator.methods){
if(method){
value=$element.data('rule' + method.charAt(0).toUpperCase() + method.substring(1).toLowerCase());
if(value===''){
value=true;
}
this.normalizeAttributeRule(rules, type, method, value);
}}
return rules;
},
staticRules: function(element){
var rules={},
tc_validator=$.data(element.form, 'tc_validator');
if(tc_validator.settings.rules){
rules=$.tc_validator.normalizeRule(tc_validator.settings.rules[ element.name ])||{};}
return rules;
},
normalizeRules: function(rules, element){
var keepRule;
$.each(rules, function(prop, val){
if(val===false){
delete rules[ prop ];
return;
}
if(val.param||val.depends){
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{
$.data(element.form, 'tc_validator').resetElements($(element));
delete rules[ prop ];
}}
});
$.each(rules, function(rule, parameter){
rules[ rule ]=typeof parameter==='function'&&rule!=='normalizer' ? parameter(element):parameter;
});
$.each([ 'minlength', 'maxlength' ], function(){
if(rules[ this ]){
rules[ this ]=Number(rules[ this ]);
}});
$.each([ 'rangelength', 'range' ], function(){
var parts;
if(rules[ this ]){
if(Array.isArray(rules[ this ])){
rules[ this ]=[ Number(rules[ this ][ 0 ]), Number(rules[ this ][ 1 ]) ];
}else if(typeof rules[ this ]==='string'){
parts=rules[ this ].replace(/[[\]]/g, '').split(/[\s,]+/);
rules[ this ]=[ Number(parts[ 0 ]), Number(parts[ 1 ]) ];
}}
});
if($.tc_validator.autoCreateRanges){
if(rules.min!==null&&rules.max!==null){
rules.range=[ rules.min, rules.max ];
delete rules.min;
delete rules.max;
}
if(rules.minlength!==null&&rules.maxlength!==null){
rules.rangelength=[ rules.minlength, rules.maxlength ];
delete rules.minlength;
delete rules.maxlength;
}}
return rules;
},
normalizeRule: function(data){
var transformed;
if(typeof data==='string'){
transformed={};
$.each(data.split(/\s/), function(){
transformed[ this ]=true;
});
data=transformed;
}
return data;
},
addMethod: function(name, method, message){
$.tc_validator.methods[ name ]=method;
$.tc_validator.messages[ name ]=message!==undefined ? message:$.tc_validator.messages[ name ];
if(method.length < 3){
$.tc_validator.addClassRules(name, $.tc_validator.normalizeRule(name));
}},
methods: {
required: function(value, element, param){
var val;
if(! this.depend(param, element)){
return 'dependency-mismatch';
}
if(element.nodeName.toLowerCase()==='select'){
val=$(element).val();
return val&&val.length > 0;
}
if(this.checkable(element)){
return this.getLength(value, element) > 0;
}
return value!==undefined&&value!==null&&value.length > 0;
},
email: function(value, element){
return this.optional(element)||/^[a-zA-Z0-9.!#$%&'*+\/=?\^_`{|}~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$/.test(value);
},
url: function(value, element){
return (
this.optional(element) ||
/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(value
)
);
},
date: function(value, element){
return this.optional(element)||! /Invalid|NaN/.test(new Date(value).toString());
},
dateISO: function(value, element){
return this.optional(element)||/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(value);
},
number: function(value, element){
return this.optional(element)||/^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value);
},
digits: function(value, element){
return this.optional(element)||/^\d+$/.test(value);
},
minlength: function(value, element, param){
var length=Array.isArray(value) ? value.length:this.getLength(value, element);
return this.optional(element)||length >=param;
},
maxlength: function(value, element, param){
var length=Array.isArray(value) ? value.length:this.getLength(value, element);
return this.optional(element)||length <=param;
},
rangelength: function(value, element, param){
var length=Array.isArray(value) ? value.length:this.getLength(value, element);
return this.optional(element)||(length >=param[ 0 ]&&length <=param[ 1 ]);
},
min: function(value, element, param){
return this.optional(element)||value >=param;
},
max: function(value, element, param){
return this.optional(element)||value <=param;
},
range: function(value, element, param){
return this.optional(element)||(value >=param[ 0 ]&&value <=param[ 1 ]);
},
step: function(value, element, param){
var type=$(element).attr('type'),
errorMessage='Step attribute on input type ' + type + ' is not supported.',
supportedTypes=[ 'text', 'number', 'range' ],
re=new RegExp('\\b' + type + '\\b'),
notSupported=type&&! re.test(supportedTypes.join()),
decimalPlaces=function(num){
var match=('' + num).match(/(?:\.(\d+))?$/);
if(! match){
return 0;
}
return match[ 1 ] ? match[ 1 ].length:0;
},
decimals,
toInt=function(num){
return Math.round(num * Math.pow(10, decimals));
},
valid=true;
if(notSupported){
throw new Error(errorMessage);
}
decimals=decimalPlaces(param);
if(decimalPlaces(value) > decimals||toInt(value) % toInt(param)!==0){
valid=false;
}
return this.optional(element)||valid;
},
equalTo: function(value, element, param){
var target=$(param);
if(this.settings.onfocusout&&target.not('.tc_validate-equalTo-blur').length){
target.addClass('validate-equalTo-blur').on('blur.tc_validate-equalTo', function(){
$(element).tc_valid();
});
}
return value===target.val();
},
remote: function(value, element, param, method){
var previous;
var tc_validator;
var data;
var optionDataString;
if(this.optional(element)){
return 'dependency-mismatch';
}
method=(typeof method==='string'&&method)||'remote';
previous=this.previousValue(element, method);
if(! this.settings.messages[ element.name ]){
this.settings.messages[ element.name ]={};}
previous.originalMessage=previous.originalMessage||this.settings.messages[ element.name ][ method ];
this.settings.messages[ element.name ][ method ]=previous.message;
param=(typeof param==='string'&&{ url: param })||param;
optionDataString=$.param($.extend({ data: value }, param.data));
if(previous.old===optionDataString){
return previous.valid;
}
previous.old=optionDataString;
tc_validator=this;
this.startRequest(element);
data={};
data[ element.name ]=value;
$.ajax($.extend(true,
{
mode: 'abort',
port: 'validate' + element.name,
dataType: 'json',
data: data,
context: tc_validator.currentForm,
success: function(response){
var valid=response===true||response==='true',
errors,
message,
submitted;
tc_validator.settings.messages[ element.name ][ method ]=previous.originalMessage;
if(valid){
submitted=tc_validator.formSubmitted;
tc_validator.resetInternals();
tc_validator.toHide=tc_validator.errorsFor(element);
tc_validator.formSubmitted=submitted;
tc_validator.successList.push(element);
tc_validator.invalid[ element.name ]=false;
tc_validator.showErrors();
}else{
errors={};
message=response||tc_validator.defaultMessage(element, { method: method, parameters: value });
previous.message=message;
errors[ element.name ]=message;
tc_validator.invalid[ element.name ]=true;
tc_validator.showErrors(errors);
}
previous.valid=valid;
tc_validator.stopRequest(element, valid);
}},
param
)
);
return 'pending';
}}
});
if($.ajaxPrefilter){
$.ajaxPrefilter(function(settings, _, xhr){
var port=settings.port;
if(settings.mode==='abort'){
if(pendingRequests[ port ]){
pendingRequests[ port ].abort();
}
pendingRequests[ port ]=xhr;
}});
}else{
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);
};}
return $;
}));
(function($, window, document){
'use strict';
var lazyLoadXT='lazyLoadXT',
dataLazied='lazied',
loadError='load error',
classLazyHidden='lazy-hidden',
docElement=document.documentElement||document.body,
forceLoad =
window.onscroll===undefined ||
!! window.operamini ||
! docElement.getBoundingClientRect,
options={
autoInit: true,
selector: 'img[data-src]',
blankImage: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
throttle: 99,
forceLoad: forceLoad,
loadEvent: 'pageshow',
updateEvent: 'load orientationchange resize scroll touchmove focus',
forceEvent: 'lazyloadall',
oninit: { removeClass: 'lazy' },
onshow: { addClass: classLazyHidden },
onload: { removeClass: classLazyHidden, addClass: 'lazy-loaded' },
onerror: { removeClass: classLazyHidden },
checkDuplicates: true
},
elementOptions={
srcAttr: 'data-src',
edgeX: 0,
edgeY: 0,
visibleOnly: true
},
$window=$(window),
$isFunction=function(f){
return typeof f==='function';
},
$extend=$.extend,
$data =
$.data ||
function(el, name){
return $(el).data(name);
},
elements=[],
topLazy=0,
waitingMode=0;
$[ lazyLoadXT ]=$extend(options, elementOptions, $[ lazyLoadXT ]);
function getOrDef(obj, prop){
return obj[ prop ]===undefined ? options[ prop ]:obj[ prop ];
}
function scrollTop(){
var scroll=window.pageYOffset;
return scroll===undefined ? docElement.scrollTop:scroll;
}
function timeoutLazyElements(){
if(waitingMode > 1){
waitingMode=1;
checkLazyElements();
setTimeout(timeoutLazyElements, options.throttle);
}else{
waitingMode=0;
}}
function queueCheckLazyElements(e){
if(! elements.length){
return;
}
if(e&&e.type==='scroll'&&e.currentTarget===window){
if(topLazy >=scrollTop()){
return;
}}
if(! waitingMode){
setTimeout(timeoutLazyElements, 0);
}
waitingMode=2;
}
function triggerEvent(event, $el){
var handler=options[ 'on' + event ];
if(handler){
if($isFunction(handler)){
handler.call($el[ 0 ]);
}else{
if(handler.addClass){
$el.addClass(handler.addClass);
}
if(handler.removeClass){
$el.removeClass(handler.removeClass);
}}
}
$el.trigger('lazy' + event, [ $el ]);
queueCheckLazyElements();
}
function triggerLoadOrError(e){
triggerEvent(e.type, $(e.currentTarget).off(loadError, triggerLoadOrError));
}
function checkLazyElements(force){
var viewportTop, viewportHeight, viewportWidth, i, length;
var $el, el, objData, removeNode, visible, topEdge;
var elPos, edgeX, edgeY;
var srcAttr, src;
if(! elements.length){
return;
}
force=force||options.forceLoad;
topLazy=Infinity;
viewportTop=scrollTop();
viewportHeight=window.innerHeight||docElement.clientHeight;
viewportWidth=window.innerWidth||docElement.clientWidth;
for(i=0, length=elements.length; i < length; i +=1){
$el=elements[ i ];
el=$el[ 0 ];
objData=$el[ lazyLoadXT ];
removeNode=false;
visible=force||$data(el, dataLazied) < 0;
if(! $.contains(docElement, el)){
removeNode=true;
}else if(force||! objData.visibleOnly||el.offsetWidth||el.offsetHeight){
if(! visible){
elPos=el.getBoundingClientRect();
edgeX=objData.edgeX;
edgeY=objData.edgeY;
topEdge=elPos.top + viewportTop - edgeY - viewportHeight;
visible=topEdge <=viewportTop&&elPos.bottom > -edgeY&&elPos.left <=viewportWidth + edgeX&&elPos.right > -edgeX;
}
if(visible){
$el.on(loadError, triggerLoadOrError);
triggerEvent('show', $el);
srcAttr=objData.srcAttr;
src=$isFunction(srcAttr) ? srcAttr($el):el.getAttribute(srcAttr);
if(src){
el.src=src;
}
removeNode=true;
}else if(topEdge < topLazy){
topLazy=topEdge;
}}
if(removeNode){
$data(el, dataLazied, 0);
elements.splice(i, 1);
i=i - 1;
length=length - 1;
}}
if(! length){
triggerEvent('complete', $(docElement));
}}
$.fn[ lazyLoadXT ]=function(overrides){
var blankImage;
var checkDuplicates;
var scrollContainer;
var forceShow;
var elementOptionsOverrides={};
overrides=overrides||{};
blankImage=getOrDef(overrides, 'blankImage');
checkDuplicates=getOrDef(overrides, 'checkDuplicates');
scrollContainer=getOrDef(overrides, 'scrollContainer');
forceShow=getOrDef(overrides, 'show');
$(scrollContainer).on('scroll', queueCheckLazyElements);
Object.keys(elementOptions).forEach(function(prop){
elementOptionsOverrides[ prop ]=getOrDef(overrides, prop);
});
return this.each(function(index, el){
var duplicate;
var $el;
if(el===window){
$(options.selector).lazyLoadXT(overrides);
}else{
duplicate=checkDuplicates&&$data(el, dataLazied);
$el=$(el).data(dataLazied, forceShow ? -1:1);
if(duplicate){
queueCheckLazyElements();
return;
}
if(blankImage&&el.tagName==='IMG'&&! el.src){
el.src=blankImage;
}
$el[ lazyLoadXT ]=$extend({}, elementOptionsOverrides);
triggerEvent('init', $el);
elements.push($el);
queueCheckLazyElements();
}});
};
function initLazyElements(){
$window.lazyLoadXT();
}
function forceLoadAll(){
checkLazyElements(true);
}
$(function(){
triggerEvent('start', $window);
$window.on(options.updateEvent, queueCheckLazyElements).on(options.forceEvent, forceLoadAll);
$(document).on(options.updateEvent, queueCheckLazyElements);
if(options.autoInit){
$window.on(options.loadEvent, initLazyElements);
initLazyElements();
}});
}(window.jQuery||window.Zepto||window.$, window, document));
(function($){
'use strict';
var options=$.lazyLoadXT;
options.selector +=',video,iframe[data-src]';
options.videoPoster='data-poster';
$(document).on('lazyshow', 'video', function(e, $el){
var srcAttr=$el.lazyLoadXT.srcAttr,
isFuncSrcAttr=typeof srcAttr==='function',
changed=false;
$el.attr('poster', $el.attr(options.videoPoster));
$el.children('source,track').each(function(index, el){
var $child=$(el),
src=isFuncSrcAttr ? srcAttr($child):$child.attr(srcAttr);
if(src){
$child.attr('src', src);
changed=true;
}});
if(changed){
this.load();
}});
}(window.jQuery||window.Zepto||window.$));
(function(global, factory){
'use strict';
factory(global.noUiSlider={});
}(this,(function(exports){
'use strict';
var nouislider;
var defaultFormatter={
to: function(value){
return value===undefined ? '':value.toFixed(2);
},
from: Number
};
var cssClasses={
target: 'target',
base: 'base',
origin: 'origin',
handle: 'handle',
handleLower: 'handle-lower',
handleUpper: 'handle-upper',
touchArea: 'touch-area',
horizontal: 'horizontal',
vertical: 'vertical',
background: 'background',
connect: 'connect',
connects: 'connects',
ltr: 'ltr',
rtl: 'rtl',
textDirectionLtr: 'txt-dir-ltr',
textDirectionRtl: 'txt-dir-rtl',
draggable: 'draggable',
drag: 'state-drag',
tap: 'state-tap',
active: 'active',
tooltip: 'tooltip',
pips: 'pips',
pipsHorizontal: 'pips-horizontal',
pipsVertical: 'pips-vertical',
marker: 'marker',
markerHorizontal: 'marker-horizontal',
markerVertical: 'marker-vertical',
markerNormal: 'marker-normal',
markerLarge: 'marker-large',
markerSub: 'marker-sub',
value: 'value',
valueHorizontal: 'value-horizontal',
valueVertical: 'value-vertical',
valueNormal: 'value-normal',
valueLarge: 'value-large',
valueSub: 'value-sub'
};
var INTERNAL_EVENT_NS={
tooltips: '.__tooltips',
aria: '.__aria'
};
var Spectrum=(function(){
function Spectrumc(entry, snap, singleStep){
var index;
var ordered=[];
this.xPct=[];
this.xVal=[];
this.xSteps=[];
this.xNumSteps=[];
this.xHighestCompleteStep=[];
this.xSteps=[ singleStep||false ];
this.xNumSteps=[ false ];
this.snap=snap;
Object.keys(entry).forEach(function(iindex){
ordered.push([ asArray(entry[ iindex ]), iindex ]);
});
ordered.sort(function(a, b){
return a[ 0 ][ 0 ] - b[ 0 ][ 0 ];
});
for(index=0; index < ordered.length; index++){
this.handleEntryPoint(ordered[ index ][ 1 ], ordered[ index ][ 0 ]);
}
this.xNumSteps=this.xSteps.slice(0);
for(index=0; index < this.xNumSteps.length; index++){
this.handleStepPoint(index, this.xNumSteps[ index ]);
}}
Spectrumc.prototype.getDistance=function(value){
var index;
var distances=[];
for(index=0; index < this.xNumSteps.length - 1; index++){
distances[ index ]=fromPercentage(this.xVal, value, index);
}
return distances;
};
Spectrumc.prototype.getAbsoluteDistance=function(value, distances, direction){
var xPct_index=0;
var start_factor;
var rest_factor=1;
var rest_rel_distance;
var range_pct=0;
var rel_range_distance=0;
var abs_distance_counter=0;
var range_counter=0;
if(value < this.xPct[ this.xPct.length - 1 ]){
while(value > this.xPct[ xPct_index + 1 ]){
xPct_index++;
}}else if(value===this.xPct[ this.xPct.length - 1 ]){
xPct_index=this.xPct.length - 2;
}
if(! direction&&value===this.xPct[ xPct_index + 1 ]){
xPct_index++;
}
if(distances===null){
distances=[];
}
rest_rel_distance=distances[ xPct_index ];
if(direction){
start_factor=(value - this.xPct[ xPct_index ]) /(this.xPct[ xPct_index + 1 ] - this.xPct[ xPct_index ]);
}else{
start_factor=(this.xPct[ xPct_index + 1 ] - value) /(this.xPct[ xPct_index + 1 ] - this.xPct[ xPct_index ]);
}
while(rest_rel_distance > 0){
range_pct=this.xPct[ xPct_index + 1 + range_counter ] - this.xPct[ xPct_index + range_counter ];
if(( distances[ xPct_index + range_counter ] * rest_factor) + 100 -(start_factor * 100) > 100){
rel_range_distance=range_pct * start_factor;
rest_factor=(rest_rel_distance -(100 * start_factor)) / distances[ xPct_index + range_counter ];
start_factor=1;
}else{
rel_range_distance=(( distances[ xPct_index + range_counter ] * range_pct) / 100) * rest_factor;
rest_factor=0;
}
if(direction){
abs_distance_counter=abs_distance_counter - rel_range_distance;
if(this.xPct.length + range_counter >=1){
range_counter--;
}}else{
abs_distance_counter=abs_distance_counter + rel_range_distance;
if(this.xPct.length - range_counter >=1){
range_counter++;
}}
rest_rel_distance=distances[ xPct_index + range_counter ] * rest_factor;
}
return value + abs_distance_counter;
};
Spectrumc.prototype.toStepping=function(value){
value=toStepping(this.xVal, this.xPct, value);
return value;
};
Spectrumc.prototype.fromStepping=function(value){
return fromStepping(this.xVal, this.xPct, value);
};
Spectrumc.prototype.getStep=function(value){
value=getStep(this.xPct, this.xSteps, this.snap, value);
return value;
};
Spectrumc.prototype.getDefaultStep=function(value, isDown, size){
var j=getJ(value, this.xPct);
if(value===100||(isDown&&value===this.xPct[ j - 1 ])){
j=Math.max(j - 1, 1);
}
return(this.xVal[ j ] - this.xVal[ j - 1 ]) / size;
};
Spectrumc.prototype.getNearbySteps=function(value){
var j=getJ(value, this.xPct);
return {
stepBefore: {
startValue: this.xVal[ j - 2 ],
step: this.xNumSteps[ j - 2 ],
highestStep: this.xHighestCompleteStep[ j - 2 ]
},
thisStep: {
startValue: this.xVal[ j - 1 ],
step: this.xNumSteps[ j - 1 ],
highestStep: this.xHighestCompleteStep[ j - 1 ]
},
stepAfter: {
startValue: this.xVal[ j ],
step: this.xNumSteps[ j ],
highestStep: this.xHighestCompleteStep[ j ]
}};};
Spectrumc.prototype.countStepDecimals=function(){
var stepDecimals=this.xNumSteps.map(countDecimals);
return Math.max.apply(null, stepDecimals);
};
Spectrumc.prototype.hasNoSize=function(){
return this.xVal[ 0 ]===this.xVal[ this.xVal.length - 1 ];
};
Spectrumc.prototype.convert=function(value){
return this.getStep(this.toStepping(value));
};
Spectrumc.prototype.handleEntryPoint=function(index, value){
var percentage;
var value1;
if(index==='min'){
percentage=0;
}else if(index==='max'){
percentage=100;
}else{
percentage=parseFloat(index);
}
if(! isNumeric(percentage)||! isNumeric(value[ 0 ])){
throw new Error("noUiSlider: 'range' value isn't numeric.");
}
this.xPct.push(percentage);
this.xVal.push(value[ 0 ]);
value1=Number(value[ 1 ]);
if(! percentage){
if(! isNaN(value1)){
this.xSteps[ 0 ]=value1;
}}else{
this.xSteps.push(isNaN(value1) ? false:value1);
}
this.xHighestCompleteStep.push(0);
};
Spectrumc.prototype.handleStepPoint=function(i, n){
var totalSteps;
var highestStep;
var step;
if(! n){
return;
}
if(this.xVal[ i ]===this.xVal[ i + 1 ]){
this.xSteps[ i ]=this.xHighestCompleteStep[ i ]=this.xVal[ i ];
return;
}
this.xSteps[ i ] =
fromPercentage([ this.xVal[ i ], this.xVal[ i + 1 ] ], n, 0) / subRangeRatio(this.xPct[ i ], this.xPct[ i + 1 ]);
totalSteps=(this.xVal[ i + 1 ] - this.xVal[ i ]) / this.xNumSteps[ i ];
highestStep=Math.ceil(Number(totalSteps.toFixed(3)) - 1);
step=this.xVal[ i ] +(this.xNumSteps[ i ] * highestStep);
this.xHighestCompleteStep[ i ]=step;
};
return Spectrumc;
}());
exports.PipsMode=void 0;
(function(PipsMode){
PipsMode.Range='range';
PipsMode.Steps='steps';
PipsMode.Positions='positions';
PipsMode.Count='count';
PipsMode.Values='values';
}(exports.PipsMode||(exports.PipsMode={})));
exports.PipsType=void 0;
(function(PipsType){
PipsType[ PipsType.None=-1 ]='None';
PipsType[ PipsType.NoValue=0 ]='NoValue';
PipsType[ PipsType.LargeValue=1 ]='LargeValue';
PipsType[ PipsType.SmallValue=2 ]='SmallValue';
}(exports.PipsType||(exports.PipsType={})));
function isValidFormatter(entry){
return isValidPartialFormatter(entry)&&typeof entry.from==='function';
}
function isValidPartialFormatter(entry){
return typeof entry==='object'&&typeof entry.to==='function';
}
function removeElement(el){
el.parentElement.removeChild(el);
}
function isSet(value){
return value!==null&&value!==undefined;
}
function preventDefault(e){
e.preventDefault();
}
function unique(array){
return array.filter(function(a){
return ! this[ a ] ?(this[ a ]=true):false;
}, {});
}
function closest(value, to){
return Math.round(value / to) * to;
}
function offset(elem, orientation){
var rect=elem.getBoundingClientRect();
var doc=elem.ownerDocument;
var docElem=doc.documentElement;
var pageOffset=getPageOffset(doc);
if(/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)){
pageOffset.x=0;
}
return orientation ? rect.top + pageOffset.y - docElem.clientTop:rect.left + pageOffset.x - docElem.clientLeft;
}
function isNumeric(a){
return typeof a==='number'&&! isNaN(a)&&isFinite(a);
}
function addClassFor(element, className, duration){
if(duration > 0){
addClass(element, className);
setTimeout(function(){
removeClass(element, className);
}, duration);
}}
function limit(a){
return Math.max(Math.min(a, 100), 0);
}
function asArray(a){
return Array.isArray(a) ? a:[ a ];
}
function countDecimals(numStr){
var pieces;
numStr=String(numStr);
pieces=numStr.split('.');
return pieces.length > 1 ? pieces[ 1 ].length:0;
}
function addClass(el, className){
if(el.classList&&! /\s/.test(className)){
el.classList.add(className);
}else{
el.className +=' ' + className;
}}
function removeClass(el, className){
if(el.classList&&! /\s/.test(className)){
el.classList.remove(className);
}else{
el.className=el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}}
function hasClass(el, className){
return el.classList ? el.classList.contains(className):new RegExp('\\b' + className + '\\b').test(el.className);
}
function getPageOffset(doc){
var supportPageOffset=window.pageXOffset!==undefined;
var isCSS1Compat=(doc.compatMode||'')==='CSS1Compat';
var x=supportPageOffset ? window.pageXOffset:isCSS1Compat ? doc.documentElement.scrollLeft:doc.body.scrollLeft;
var y=supportPageOffset ? window.pageYOffset:isCSS1Compat ? doc.documentElement.scrollTop:doc.body.scrollTop;
return {
x: x,
y: y
};}
function getActions(){
return window.navigator.pointerEnabled ? {
start: 'pointerdown',
move: 'pointermove',
end: 'pointerup'
}:window.navigator.msPointerEnabled ? {
start: 'MSPointerDown',
move: 'MSPointerMove',
end: 'MSPointerUp'
}:{
start: 'mousedown touchstart',
move: 'mousemove touchmove',
end: 'mouseup touchend'
};}
function getSupportsPassive(){
var supportsPassive=false;
try {
var opts=Object.defineProperty({}, "passive", {
get: function (){
supportsPassive=true;
},
});
window.addEventListener("test", null, opts);
}
catch (e){ }
return supportsPassive;
}
function getSupportsTouchActionNone(){
return window.CSS&&CSS.supports&&CSS.supports('touch-action', 'none');
}
function subRangeRatio(pa, pb){
return 100 /(pb - pa);
}
function fromPercentage(range, value, startRange){
return(value * 100) /(range[ startRange + 1 ] - range[ startRange ]);
}
function toPercentage(range, value){
return fromPercentage(range, range[ 0 ] < 0 ? value + Math.abs(range[ 0 ]):value - range[ 0 ], 0);
}
function isPercentage(range, value){
return(( value *(range[ 1 ] - range[ 0 ])) / 100) + range[ 0 ];
}
function getJ(value, arr){
var j=1;
while(value >=arr[ j ]){
j +=1;
}
return j;
}
function toStepping(xVal, xPct, value){
var j;
var va;
var vb;
var pa;
var pb;
if(value >=xVal.slice(-1)[ 0 ]){
return 100;
}
j=getJ(value, xVal);
va=xVal[ j - 1 ];
vb=xVal[ j ];
pa=xPct[ j - 1 ];
pb=xPct[ j ];
return pa +(toPercentage([ va, vb ], value) / subRangeRatio(pa, pb));
}
function fromStepping(xVal, xPct, value){
var j;
var va;
var vb;
var pa;
var pb;
if(value >=100){
return xVal.slice(-1)[ 0 ];
}
j=getJ(value, xPct);
va=xVal[ j - 1 ];
vb=xVal[ j ];
pa=xPct[ j - 1 ];
pb=xPct[ j ];
return isPercentage([ va, vb ],(value - pa) * subRangeRatio(pa, pb));
}
function getStep(xPct, xSteps, snap, value){
var j;
var a;
var b;
if(value===100){
return value;
}
j=getJ(value, xPct);
a=xPct[ j - 1 ];
b=xPct[ j ];
if(snap){
if(value - a >(b - a) / 2){
return b;
}
return a;
}
if(! xSteps[ j - 1 ]){
return value;
}
return xPct[ j - 1 ] + closest(value - xPct[ j - 1 ], xSteps[ j - 1 ]);
}
function testStep(parsed, entry){
if(! isNumeric(entry)){
throw new Error("noUiSlider: 'step' is not numeric.");
}
parsed.singleStep=entry;
}
function testKeyboardPageMultiplier(parsed, entry){
if(! isNumeric(entry)){
throw new Error("noUiSlider: 'keyboardPageMultiplier' is not numeric.");
}
parsed.keyboardPageMultiplier=entry;
}
function testKeyboardMultiplier(parsed, entry){
if(! isNumeric(entry)){
throw new Error("noUiSlider: 'keyboardMultiplier' is not numeric.");
}
parsed.keyboardMultiplier=entry;
}
function testKeyboardDefaultStep(parsed, entry){
if(! isNumeric(entry)){
throw new Error("noUiSlider: 'keyboardDefaultStep' is not numeric.");
}
parsed.keyboardDefaultStep=entry;
}
function testRange(parsed, entry){
if(typeof entry!=='object'||Array.isArray(entry)){
throw new Error("noUiSlider: 'range' is not an object.");
}
if(entry.min===undefined||entry.max===undefined){
throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");
}
parsed.spectrum=new Spectrum(entry, parsed.snap||false, parsed.singleStep);
}
function testStart(parsed, entry){
entry=asArray(entry);
if(! Array.isArray(entry)||! entry.length){
throw new Error("noUiSlider: 'start' option is incorrect.");
}
parsed.handles=entry.length;
parsed.start=entry;
}
function testSnap(parsed, entry){
if(typeof entry!=='boolean'){
throw new Error("noUiSlider: 'snap' option must be a boolean.");
}
parsed.snap=entry;
}
function testAnimate(parsed, entry){
if(typeof entry!=='boolean'){
throw new Error("noUiSlider: 'animate' option must be a boolean.");
}
parsed.animate=entry;
}
function testAnimationDuration(parsed, entry){
if(typeof entry!=='number'){
throw new Error("noUiSlider: 'animationDuration' option must be a number.");
}
parsed.animationDuration=entry;
}
function testConnect(parsed, entry){
var connect=[ false ];
var i;
if(entry==='lower'){
entry=[ true, false ];
}else if(entry==='upper'){
entry=[ false, true ];
}
if(entry===true||entry===false){
for(i=1; i < parsed.handles; i++){
connect.push(entry);
}
connect.push(false);
}else if(! Array.isArray(entry)||! entry.length||entry.length!==parsed.handles + 1){
throw new Error("noUiSlider: 'connect' option doesn't match handle count.");
}else{
connect=entry;
}
parsed.connect=connect;
}
function testOrientation(parsed, entry){
switch(entry){
case 'horizontal':
parsed.ort=0;
break;
case 'vertical':
parsed.ort=1;
break;
default:
throw new Error("noUiSlider: 'orientation' option is invalid.");
}}
function testMargin(parsed, entry){
if(! isNumeric(entry)){
throw new Error("noUiSlider: 'margin' option must be numeric.");
}
if(entry===0){
return;
}
parsed.margin=parsed.spectrum.getDistance(entry);
}
function testLimit(parsed, entry){
if(! isNumeric(entry)){
throw new Error("noUiSlider: 'limit' option must be numeric.");
}
parsed.limit=parsed.spectrum.getDistance(entry);
if(! parsed.limit||parsed.handles < 2){
throw new Error("noUiSlider: 'limit' option is only supported on linear sliders with 2 or more handles.");
}}
function testPadding(parsed, entry){
var index;
var totalPadding;
var firstValue;
var lastValue;
if(! isNumeric(entry)&&! Array.isArray(entry)){
throw new Error("noUiSlider: 'padding' option must be numeric or array of exactly 2 numbers.");
}
if(Array.isArray(entry)&&!(entry.length===2||isNumeric(entry[ 0 ])||isNumeric(entry[ 1 ]))){
throw new Error("noUiSlider: 'padding' option must be numeric or array of exactly 2 numbers.");
}
if(entry===0){
return;
}
if(! Array.isArray(entry)){
entry=[ entry, entry ];
}
parsed.padding=[ parsed.spectrum.getDistance(entry[ 0 ]), parsed.spectrum.getDistance(entry[ 1 ]) ];
for(index=0; index < parsed.spectrum.xNumSteps.length - 1; index++){
if(parsed.padding[ 0 ][ index ] < 0||parsed.padding[ 1 ][ index ] < 0){
throw new Error("noUiSlider: 'padding' option must be a positive number(s).");
}}
totalPadding=entry[ 0 ] + entry[ 1 ];
firstValue=parsed.spectrum.xVal[ 0 ];
lastValue=parsed.spectrum.xVal[ parsed.spectrum.xVal.length - 1 ];
if(totalPadding /(lastValue - firstValue) > 1){
throw new Error("noUiSlider: 'padding' option must not exceed 100% of the range.");
}}
function testDirection(parsed, entry){
switch(entry){
case 'ltr':
parsed.dir=0;
break;
case 'rtl':
parsed.dir=1;
break;
default:
throw new Error("noUiSlider: 'direction' option was not recognized.");
}}
function testBehaviour(parsed, entry){
var tap;
var drag;
var fixed;
var snap;
var hover;
var unconstrained;
var dragAll;
var smoothSteps;
if(typeof entry!=='string'){
throw new Error("noUiSlider: 'behaviour' must be a string containing options.");
}
tap=entry.indexOf('tap') >=0;
drag=entry.indexOf('drag') >=0;
fixed=entry.indexOf('fixed') >=0;
snap=entry.indexOf('snap') >=0;
hover=entry.indexOf('hover') >=0;
unconstrained=entry.indexOf('unconstrained') >=0;
dragAll=entry.indexOf('drag-all') >=0;
smoothSteps=entry.indexOf('smooth-steps') >=0;
if(fixed){
if(parsed.handles!==2){
throw new Error("noUiSlider: 'fixed' behaviour must be used with 2 handles");
}
testMargin(parsed, parsed.start[ 1 ] - parsed.start[ 0 ]);
}
if(unconstrained&&(parsed.margin||parsed.limit)){
throw new Error("noUiSlider: 'unconstrained' behaviour cannot be used with margin or limit");
}
parsed.events={
tap: tap||snap,
drag: drag,
dragAll: dragAll,
smoothSteps: smoothSteps,
fixed: fixed,
snap: snap,
hover: hover,
unconstrained: unconstrained
};}
function testTooltips(parsed, entry){
var i;
if(entry===false){
return;
}
if(entry===true||isValidPartialFormatter(entry)){
parsed.tooltips=[];
for(i=0; i < parsed.handles; i++){
parsed.tooltips.push(entry);
}}else{
entry=asArray(entry);
if(entry.length!==parsed.handles){
throw new Error('noUiSlider: must pass a formatter for all handles.');
}
entry.forEach(function(formatter){
if(typeof formatter!=='boolean'&&! isValidPartialFormatter(formatter)){
throw new Error("noUiSlider: 'tooltips' must be passed a formatter or 'false'.");
}});
parsed.tooltips=entry;
}}
function testHandleAttributes(parsed, entry){
if(entry.length!==parsed.handles){
throw new Error('noUiSlider: must pass a attributes for all handles.');
}
parsed.handleAttributes=entry;
}
function testAriaFormat(parsed, entry){
if(! isValidPartialFormatter(entry)){
throw new Error("noUiSlider: 'ariaFormat' requires 'to' method.");
}
parsed.ariaFormat=entry;
}
function testFormat(parsed, entry){
if(! isValidFormatter(entry)){
throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods.");
}
parsed.format=entry;
}
function testKeyboardSupport(parsed, entry){
if(typeof entry!=='boolean'){
throw new Error("noUiSlider: 'keyboardSupport' option must be a boolean.");
}
parsed.keyboardSupport=entry;
}
function testDocumentElement(parsed, entry){
parsed.documentElement=entry;
}
function testCssPrefix(parsed, entry){
if(typeof entry!=='string'&&entry!==false){
throw new Error("noUiSlider: 'cssPrefix' must be a string or `false`.");
}
parsed.cssPrefix=entry;
}
function testCssClasses(parsed, entry){
if(typeof entry!=='object'){
throw new Error("noUiSlider: 'cssClasses' must be an object.");
}
if(typeof parsed.cssPrefix==='string'){
parsed.cssClasses={};
Object.keys(entry).forEach(function(key){
parsed.cssClasses[ key ]=parsed.cssPrefix + entry[ key ];
});
}else{
parsed.cssClasses=entry;
}}
function testOptions(options){
var parsed={
margin: null,
limit: null,
padding: null,
animate: true,
animationDuration: 300,
ariaFormat: defaultFormatter,
format: defaultFormatter
};
var tests={
step: { r: false, t: testStep },
keyboardPageMultiplier: { r: false, t: testKeyboardPageMultiplier },
keyboardMultiplier: { r: false, t: testKeyboardMultiplier },
keyboardDefaultStep: { r: false, t: testKeyboardDefaultStep },
start: { r: true, t: testStart },
connect: { r: true, t: testConnect },
direction: { r: true, t: testDirection },
snap: { r: false, t: testSnap },
animate: { r: false, t: testAnimate },
animationDuration: { r: false, t: testAnimationDuration },
range: { r: true, t: testRange },
orientation: { r: false, t: testOrientation },
margin: { r: false, t: testMargin },
limit: { r: false, t: testLimit },
padding: { r: false, t: testPadding },
behaviour: { r: true, t: testBehaviour },
ariaFormat: { r: false, t: testAriaFormat },
format: { r: false, t: testFormat },
tooltips: { r: false, t: testTooltips },
keyboardSupport: { r: true, t: testKeyboardSupport },
documentElement: { r: false, t: testDocumentElement },
cssPrefix: { r: true, t: testCssPrefix },
cssClasses: { r: true, t: testCssClasses },
handleAttributes: { r: false, t: testHandleAttributes }};
var defaults={
connect: false,
direction: 'ltr',
behaviour: 'tap',
orientation: 'horizontal',
keyboardSupport: true,
cssPrefix: 'noui-',
cssClasses: cssClasses,
keyboardPageMultiplier: 5,
keyboardMultiplier: 1,
keyboardDefaultStep: 10
};
var d;
var msPrefix;
var noPrefix;
var styles;
if(options.format&&! options.ariaFormat){
options.ariaFormat=options.format;
}
Object.keys(tests).forEach(function(name){
if(! isSet(options[ name ])&&defaults[ name ]===undefined){
if(tests[ name ].r){
throw new Error("noUiSlider: '" + name + "' is required.");
}
return;
}
tests[ name ].t(parsed, ! isSet(options[ name ]) ? defaults[ name ]:options[ name ]);
});
parsed.pips=options.pips;
d=document.createElement('div');
msPrefix=d.style.msTransform!==undefined;
noPrefix=d.style.transform!==undefined;
parsed.transformRule=noPrefix ? 'transform':msPrefix ? 'msTransform':'webkitTransform';
styles=[
[ 'left', 'top' ],
[ 'right', 'bottom' ]
];
parsed.style=styles[ parsed.dir ][ parsed.ort ];
return parsed;
}
function scope(target, options, originalOptions){
var actions=getActions();
var supportsTouchActionNone=getSupportsTouchActionNone();
var supportsPassive=supportsTouchActionNone&&getSupportsPassive();
var scope_Target=target;
var scope_Base;
var scope_Handles;
var scope_Connects;
var scope_Pips;
var scope_Tooltips;
var scope_Spectrum=options.spectrum;
var scope_Values=[];
var scope_Locations=[];
var scope_HandleNumbers=[];
var scope_ActiveHandlesCount=0;
var scope_Events={};
var scope_Document=target.ownerDocument;
var scope_DocumentElement=options.documentElement||scope_Document.documentElement;
var scope_Body=scope_Document.body;
var scope_DirOffset=scope_Document.dir==='rtl'||options.ort===1 ? 0:100;
var scope_Self;
function addNodeTo(addTarget, className){
var div=scope_Document.createElement('div');
if(className){
addClass(div, className);
}
addTarget.appendChild(div);
return div;
}
function addOrigin(base, handleNumber){
var origin=addNodeTo(base, options.cssClasses.origin);
var handle=addNodeTo(origin, options.cssClasses.handle);
var attributes_1;
addNodeTo(handle, options.cssClasses.touchArea);
handle.setAttribute('data-handle', String(handleNumber));
if(options.keyboardSupport){
handle.setAttribute('tabindex', '0');
handle.addEventListener('keydown', function(event){
return eventKeydown(event, handleNumber);
});
}
if(options.handleAttributes!==undefined){
attributes_1=options.handleAttributes[ handleNumber ];
Object.keys(attributes_1).forEach(function(attribute){
handle.setAttribute(attribute, attributes_1[ attribute ]);
});
}
handle.setAttribute('role', 'slider');
handle.setAttribute('aria-orientation', options.ort ? 'vertical':'horizontal');
if(handleNumber===0){
addClass(handle, options.cssClasses.handleLower);
}else if(handleNumber===options.handles - 1){
addClass(handle, options.cssClasses.handleUpper);
}
origin.handle=handle;
return origin;
}
function addConnect(base, add){
if(! add){
return false;
}
return addNodeTo(base, options.cssClasses.connect);
}
function addElements(connectOptions, base){
var connectBase=addNodeTo(base, options.cssClasses.connects);
var i;
scope_Handles=[];
scope_Connects=[];
scope_Connects.push(addConnect(connectBase, connectOptions[ 0 ]));
for(i=0; i < options.handles; i++){
scope_Handles.push(addOrigin(base, i));
scope_HandleNumbers[ i ]=i;
scope_Connects.push(addConnect(connectBase, connectOptions[ i + 1 ]));
}}
function addSlider(addTarget){
var textDirection;
addClass(addTarget, options.cssClasses.target);
if(options.dir===0){
addClass(addTarget, options.cssClasses.ltr);
}else{
addClass(addTarget, options.cssClasses.rtl);
}
if(options.ort===0){
addClass(addTarget, options.cssClasses.horizontal);
}else{
addClass(addTarget, options.cssClasses.vertical);
}
textDirection=getComputedStyle(addTarget).direction;
if(textDirection==='rtl'){
addClass(addTarget, options.cssClasses.textDirectionRtl);
}else{
addClass(addTarget, options.cssClasses.textDirectionLtr);
}
return addNodeTo(addTarget, options.cssClasses.base);
}
function addTooltip(handle, handleNumber){
if(! options.tooltips||! options.tooltips[ handleNumber ]){
return false;
}
return addNodeTo(handle.firstChild, options.cssClasses.tooltip);
}
function isSliderDisabled(){
return scope_Target.hasAttribute('disabled');
}
function isHandleDisabled(handleNumber){
var handleOrigin=scope_Handles[ handleNumber ];
return handleOrigin.hasAttribute('disabled');
}
function disable(handleNumber){
if(handleNumber!==null&&handleNumber!==undefined){
scope_Handles[ handleNumber ].setAttribute('disabled', '');
scope_Handles[ handleNumber ].handle.removeAttribute('tabindex');
}else{
scope_Target.setAttribute('disabled', '');
scope_Handles.forEach(function(handle){
handle.handle.removeAttribute('tabindex');
});
}}
function enable(handleNumber){
if(handleNumber!==null&&handleNumber!==undefined){
scope_Handles[ handleNumber ].removeAttribute('disabled');
scope_Handles[ handleNumber ].handle.setAttribute('tabindex', '0');
}else{
scope_Target.removeAttribute('disabled');
scope_Handles.forEach(function(handle){
handle.removeAttribute('disabled');
handle.handle.setAttribute('tabindex', '0');
});
}}
function removeTooltips(){
if(scope_Tooltips){
removeEvent('update' + INTERNAL_EVENT_NS.tooltips);
scope_Tooltips.forEach(function(tooltip){
if(tooltip){
removeElement(tooltip);
}});
scope_Tooltips=null;
}}
function tooltips(){
var formattedValue;
removeTooltips();
scope_Tooltips=scope_Handles.map(addTooltip);
bindEvent('update' + INTERNAL_EVENT_NS.tooltips, function(values, handleNumber, unencoded){
if(! scope_Tooltips||! options.tooltips){
return;
}
if(scope_Tooltips[ handleNumber ]===false){
return;
}
formattedValue=values[ handleNumber ];
if(options.tooltips[ handleNumber ]!==true){
formattedValue=options.tooltips[ handleNumber ].to(unencoded[ handleNumber ]);
}
scope_Tooltips[ handleNumber ].innerHTML=formattedValue;
});
}
function aria(){
removeEvent('update' + INTERNAL_EVENT_NS.aria);
bindEvent('update' + INTERNAL_EVENT_NS.aria, function(values, handleNumber, unencoded, tap, positions){
scope_HandleNumbers.forEach(function(index){
var handle=scope_Handles[ index ];
var min=checkHandlePosition(scope_Locations, index, 0, true, true, true);
var max=checkHandlePosition(scope_Locations, index, 100, true, true, true);
var now=positions[ index ];
var text=String(options.ariaFormat.to(unencoded[ index ]));
min=scope_Spectrum.fromStepping(min).toFixed(1);
max=scope_Spectrum.fromStepping(max).toFixed(1);
now=scope_Spectrum.fromStepping(now).toFixed(1);
handle.children[ 0 ].setAttribute('aria-valuemin', min);
handle.children[ 0 ].setAttribute('aria-valuemax', max);
handle.children[ 0 ].setAttribute('aria-valuenow', now);
handle.children[ 0 ].setAttribute('aria-valuetext', text);
});
});
}
function getGroup(ipips){
var interval;
var spread;
var values;
if(ipips.mode===exports.PipsMode.Range||ipips.mode===exports.PipsMode.Steps){
return scope_Spectrum.xVal;
}
if(ipips.mode===exports.PipsMode.Count){
if(ipips.values < 2){
throw new Error("noUiSlider: 'values' (>=2) required for mode 'count'.");
}
interval=ipips.values - 1;
spread=100 / interval;
values=[];
while(interval--){
values[ interval ]=interval * spread;
}
values.push(100);
return mapToRange(values, ipips.stepped);
}
if(ipips.mode===exports.PipsMode.Positions){
return mapToRange(ipips.values, ipips.stepped);
}
if(ipips.mode===exports.PipsMode.Values){
if(ipips.stepped){
return ipips.values.map(function(value){
return scope_Spectrum.fromStepping(scope_Spectrum.getStep(scope_Spectrum.toStepping(value)));
});
}
return ipips.values;
}
return [];
}
function mapToRange(values, stepped){
return values.map(function(value){
return scope_Spectrum.fromStepping(stepped ? scope_Spectrum.getStep(value):value);
});
}
function generateSpread(ipips){
var group=getGroup(ipips);
var indexes={};
var firstInRange=scope_Spectrum.xVal[ 0 ];
var lastInRange=scope_Spectrum.xVal[ scope_Spectrum.xVal.length - 1 ];
var ignoreFirst=false;
var ignoreLast=false;
var prevPct=0;
function safeIncrement(value, increment){
return Number(( value + increment).toFixed(7));
}
group=unique(group.slice().sort(function(a, b){
return a - b;
}));
if(group[ 0 ]!==firstInRange){
group.unshift(firstInRange);
ignoreFirst=true;
}
if(group[ group.length - 1 ]!==lastInRange){
group.push(lastInRange);
ignoreLast=true;
}
group.forEach(function(current, index){
var step;
var i;
var q;
var low=current;
var high=group[ index + 1 ];
var newPct;
var pctDifference;
var pctPos;
var type;
var steps;
var realSteps;
var stepSize;
var isSteps=ipips.mode===exports.PipsMode.Steps;
if(isSteps){
step=scope_Spectrum.xNumSteps[ index ];
}
if(! step){
step=high - low;
}
if(high===undefined){
high=low;
}
step=Math.max(step, 0.0000001);
for(i=low; i <=high; i=safeIncrement(i, step)){
newPct=scope_Spectrum.toStepping(i);
pctDifference=newPct - prevPct;
steps=pctDifference /(ipips.density||1);
realSteps=Math.round(steps);
stepSize=pctDifference / realSteps;
for(q=1; q <=realSteps; q +=1){
pctPos=prevPct +(q * stepSize);
indexes[ pctPos.toFixed(5) ]=[ scope_Spectrum.fromStepping(pctPos), 0 ];
}
type=group.indexOf(i) > -1 ? exports.PipsType.LargeValue:isSteps ? exports.PipsType.SmallValue:exports.PipsType.NoValue;
if(! index&&ignoreFirst&&i!==high){
type=0;
}
if(!(i===high&&ignoreLast)){
indexes[ newPct.toFixed(5) ]=[ i, type ];
}
prevPct=newPct;
}});
return indexes;
}
function addMarking(spread, filterFunc, formatter){
var _a, _b;
var element=scope_Document.createElement('div');
var valueSizeClasses=(_a={},
_a[ exports.PipsType.None ]='',
_a[ exports.PipsType.NoValue ]=options.cssClasses.valueNormal,
_a[ exports.PipsType.LargeValue ]=options.cssClasses.valueLarge,
_a[ exports.PipsType.SmallValue ]=options.cssClasses.valueSub,
_a);
var markerSizeClasses=(_b={},
_b[ exports.PipsType.None ]='',
_b[ exports.PipsType.NoValue ]=options.cssClasses.markerNormal,
_b[ exports.PipsType.LargeValue ]=options.cssClasses.markerLarge,
_b[ exports.PipsType.SmallValue ]=options.cssClasses.markerSub,
_b);
var valueOrientationClasses=[ options.cssClasses.valueHorizontal, options.cssClasses.valueVertical ];
var markerOrientationClasses=[ options.cssClasses.markerHorizontal, options.cssClasses.markerVertical ];
addClass(element, options.cssClasses.pips);
addClass(element, options.ort===0 ? options.cssClasses.pipsHorizontal:options.cssClasses.pipsVertical);
function getClasses(type, source){
var a=source===options.cssClasses.value;
var orientationClasses=a ? valueOrientationClasses:markerOrientationClasses;
var sizeClasses=a ? valueSizeClasses:markerSizeClasses;
return source + ' ' + orientationClasses[ options.ort ] + ' ' + sizeClasses[ type ];
}
function addSpread(key, value, type){
var node;
type=filterFunc ? filterFunc(value, type):type;
if(type===exports.PipsType.None){
return;
}
node=addNodeTo(element, false);
node.className=getClasses(type, options.cssClasses.marker);
node.style[ options.style ]=key + '%';
if(type > exports.PipsType.NoValue){
node=addNodeTo(element, false);
node.className=getClasses(type, options.cssClasses.value);
node.setAttribute('data-value', String(value));
node.style[ options.style ]=key + '%';
node.innerHTML=String(formatter.to(value));
}}
Object.keys(spread).forEach(function(key){
addSpread(key, spread[ key ][ 0 ], spread[ key ][ 1 ]);
});
return element;
}
function removePips(){
if(scope_Pips){
removeElement(scope_Pips);
scope_Pips=null;
}}
function pips(ipips){
var filter;
var spread;
var format;
removePips();
spread=generateSpread(ipips);
filter=ipips.filter;
format=ipips.format||{
to: function(value){
return String(Math.round(value));
}};
scope_Pips=scope_Target.appendChild(addMarking(spread, filter, format));
return scope_Pips;
}
function baseSize(){
var rect=scope_Base.getBoundingClientRect();
var alt=('offset' + [ 'Width', 'Height' ][ options.ort ]);
return options.ort===0 ? rect.width||scope_Base[ alt ]:rect.height||scope_Base[ alt ];
}
function attachEvent(events, element, callback, data){
var method=function(event){
var e=fixEvent(event, data.pageOffset, data.target||element);
if(! e){
return false;
}
if(isSliderDisabled()&&! data.doNotReject){
return false;
}
if(hasClass(scope_Target, options.cssClasses.tap)&&! data.doNotReject){
return false;
}
if(events===actions.start&&e.buttons!==undefined&&e.buttons > 1){
return false;
}
if(data.hover&&e.buttons){
return false;
}
if(! supportsPassive){
e.preventDefault();
}
e.calcPoint=e.points[ options.ort ];
callback(e, data);
};
var methods=[];
events.split(' ').forEach(function(eventName){
element.addEventListener(eventName, method, supportsPassive ? { passive: true }:false);
methods.push([ eventName, method ]);
});
return methods;
}
function fixEvent(e, pageOffset, eventTarget){
var touch=e.type.indexOf('touch')===0;
var mouse=e.type.indexOf('mouse')===0;
var pointer=e.type.indexOf('pointer')===0;
var x=0;
var y=0;
var isTouchOnTarget;
var targetTouches;
var targetTouch;
if(e.type.indexOf('MSPointer')===0){
pointer=true;
}
if(e.type==='mousedown'&&! e.buttons&&! e.touches){
return false;
}
if(touch){
isTouchOnTarget=function(checkTouch){
return(checkTouch.target===eventTarget ||
eventTarget.contains(checkTouch.target) ||
(e.composed&&e.composedPath().shift()===eventTarget));
};
if(e.type==='touchstart'){
targetTouches=Array.prototype.filter.call(e.touches, isTouchOnTarget);
if(targetTouches.length > 1){
return false;
}
x=targetTouches[ 0 ].pageX;
y=targetTouches[ 0 ].pageY;
}else{
targetTouch=Array.prototype.find.call(e.changedTouches, isTouchOnTarget);
if(! targetTouch){
return false;
}
x=targetTouch.pageX;
y=targetTouch.pageY;
}}
pageOffset=pageOffset||getPageOffset(scope_Document);
if(mouse||pointer){
x=e.clientX + pageOffset.x;
y=e.clientY + pageOffset.y;
}
e.pageOffset=pageOffset;
e.points=[ x, y ];
e.cursor=mouse||pointer;
return e;
}
function calcPointToPercentage(calcPoint){
var location=calcPoint - offset(scope_Base, options.ort);
var proposal=(location * 100) / baseSize();
proposal=limit(proposal);
return options.dir ? 100 - proposal:proposal;
}
function getClosestHandle(clickedPosition){
var smallestDifference=100;
var handleNumber=false;
scope_Handles.forEach(function(handle, index){
var handlePosition;
var differenceWithThisHandle;
var clickAtEdge;
var isCloser;
var isCloserAfter;
if(isHandleDisabled(index)){
return;
}
handlePosition=scope_Locations[ index ];
differenceWithThisHandle=Math.abs(handlePosition - clickedPosition);
clickAtEdge=differenceWithThisHandle===100&&smallestDifference===100;
isCloser=differenceWithThisHandle < smallestDifference;
isCloserAfter=differenceWithThisHandle <=smallestDifference&&clickedPosition > handlePosition;
if(isCloser||isCloserAfter||clickAtEdge){
handleNumber=index;
smallestDifference=differenceWithThisHandle;
}});
return handleNumber;
}
function documentLeave(event, data){
if(event.type==='mouseout' &&
event.target.nodeName==='HTML' &&
event.relatedTarget===null){
eventEnd(event, data);
}}
function eventMove(event, data){
var movement;
var proposal;
if(navigator.appVersion.indexOf('MSIE 9')===-1&&event.buttons===0&&data.buttonsProperty!==0){
return eventEnd(event, data);
}
movement=(options.dir ? -1:1) *(event.calcPoint - data.startCalcPoint);
proposal=(movement * 100) / data.baseSize;
moveHandles(movement > 0, proposal, data.locations, data.handleNumbers, data.connect);
}
function eventEnd(event, data){
if(data.handle){
removeClass(data.handle, options.cssClasses.active);
scope_ActiveHandlesCount -=1;
}
data.listeners.forEach(function(c){
scope_DocumentElement.removeEventListener(c[ 0 ], c[ 1 ]);
});
if(scope_ActiveHandlesCount===0){
removeClass(scope_Target, options.cssClasses.drag);
setZindex();
if(event.cursor){
scope_Body.style.cursor='';
scope_Body.removeEventListener('selectstart', preventDefault);
}}
if(options.events.smoothSteps){
data.handleNumbers.forEach(function(handleNumber){
setHandle(handleNumber, scope_Locations[ handleNumber ], true, true, false, false);
});
data.handleNumbers.forEach(function(handleNumber){
fireEvent('update', handleNumber);
});
}
data.handleNumbers.forEach(function(handleNumber){
fireEvent('change', handleNumber);
fireEvent('set', handleNumber);
fireEvent('end', handleNumber);
});
}
function eventStart(event, data){
var handle;
var handleOrigin;
var listeners;
var moveEvent;
var endEvent;
var outEvent;
if(data.handleNumbers.some(isHandleDisabled)){
return;
}
if(data.handleNumbers.length===1){
handleOrigin=scope_Handles[ data.handleNumbers[ 0 ] ];
handle=handleOrigin.children[ 0 ];
scope_ActiveHandlesCount +=1;
addClass(handle, options.cssClasses.active);
}
event.stopPropagation();
listeners=[];
moveEvent=attachEvent(actions.move, scope_DocumentElement, eventMove, {
target: event.target,
handle: handle,
connect: data.connect,
listeners: listeners,
startCalcPoint: event.calcPoint,
baseSize: baseSize(),
pageOffset: event.pageOffset,
handleNumbers: data.handleNumbers,
buttonsProperty: event.buttons,
locations: scope_Locations.slice()
});
endEvent=attachEvent(actions.end, scope_DocumentElement, eventEnd, {
target: event.target,
handle: handle,
listeners: listeners,
doNotReject: true,
handleNumbers: data.handleNumbers
});
outEvent=attachEvent('mouseout', scope_DocumentElement, documentLeave, {
target: event.target,
handle: handle,
listeners: listeners,
doNotReject: true,
handleNumbers: data.handleNumbers
});
listeners.push.apply(listeners, moveEvent.concat(endEvent, outEvent));
if(event.cursor){
scope_Body.style.cursor=getComputedStyle(event.target).cursor;
if(scope_Handles.length > 1){
addClass(scope_Target, options.cssClasses.drag);
}
scope_Body.addEventListener('selectstart', preventDefault, false);
}
data.handleNumbers.forEach(function(handleNumber){
fireEvent('start', handleNumber);
});
}
function eventTap(event){
var proposal;
var handleNumber;
event.stopPropagation();
proposal=calcPointToPercentage(event.calcPoint);
handleNumber=getClosestHandle(proposal);
if(handleNumber===false){
return;
}
if(! options.events.snap){
addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);
}
setHandle(handleNumber, proposal, true, true);
setZindex();
fireEvent('slide', handleNumber, true);
fireEvent('update', handleNumber, true);
if(! options.events.snap){
fireEvent('change', handleNumber, true);
fireEvent('set', handleNumber, true);
}else{
eventStart(event, { handleNumbers: [ handleNumber ] });
}}
function eventHover(event){
var proposal=calcPointToPercentage(event.calcPoint);
var to=scope_Spectrum.getStep(proposal);
var value=scope_Spectrum.fromStepping(to);
Object.keys(scope_Events).forEach(function(targetEvent){
if('hover'===targetEvent.split('.')[ 0 ]){
scope_Events[ targetEvent ].forEach(function(callback){
callback.call(scope_Self, value);
});
}});
}
function eventKeydown(event, handleNumber){
var horizontalKeys;
var verticalKeys;
var largeStepKeys;
var edgeKeys;
var key;
var isLargeDown;
var isLargeUp;
var isDown;
var isUp;
var isMin;
var isMax;
var to;
var direction;
var steps;
var step;
if(isSliderDisabled()||isHandleDisabled(handleNumber)){
return false;
}
horizontalKeys=[ 'Left', 'Right' ];
verticalKeys=[ 'Down', 'Up' ];
largeStepKeys=[ 'PageDown', 'PageUp' ];
edgeKeys=[ 'Home', 'End' ];
if(options.dir&&! options.ort){
horizontalKeys.reverse();
}else if(options.ort&&! options.dir){
verticalKeys.reverse();
largeStepKeys.reverse();
}
key=event.key.replace('Arrow', '');
isLargeDown=key===largeStepKeys[ 0 ];
isLargeUp=key===largeStepKeys[ 1 ];
isDown=key===verticalKeys[ 0 ]||key===horizontalKeys[ 0 ]||isLargeDown;
isUp=key===verticalKeys[ 1 ]||key===horizontalKeys[ 1 ]||isLargeUp;
isMin=key===edgeKeys[ 0 ];
isMax=key===edgeKeys[ 1 ];
if(! isDown&&! isUp&&! isMin&&! isMax){
return true;
}
event.preventDefault();
if(isUp||isDown){
direction=isDown ? 0:1;
steps=getNextStepsForHandle(handleNumber);
step=steps[ direction ];
if(step===null){
return false;
}
if(step===false){
step=scope_Spectrum.getDefaultStep(scope_Locations[ handleNumber ], isDown, options.keyboardDefaultStep);
}
if(isLargeUp||isLargeDown){
step *=options.keyboardPageMultiplier;
}else{
step *=options.keyboardMultiplier;
}
step=Math.max(step, 0.0000001);
step=(isDown ? -1:1) * step;
to=scope_Values[ handleNumber ] + step;
}else if(isMax){
to=options.spectrum.xVal[ options.spectrum.xVal.length - 1 ];
}else{
to=options.spectrum.xVal[ 0 ];
}
setHandle(handleNumber, scope_Spectrum.toStepping(to), true, true);
fireEvent('slide', handleNumber);
fireEvent('update', handleNumber);
fireEvent('change', handleNumber);
fireEvent('set', handleNumber);
return false;
}
function bindSliderEvents(behaviour){
var handleBefore;
var handleAfter;
var eventHolders;
var handlesToDrag;
var handleNumbersToDrag;
if(! behaviour.fixed){
scope_Handles.forEach(function(handle, index){
attachEvent(actions.start, handle.children[ 0 ], eventStart, {
handleNumbers: [ index ]
});
});
}
if(behaviour.tap){
attachEvent(actions.start, scope_Base, eventTap, {});
}
if(behaviour.hover){
attachEvent(actions.move, scope_Base, eventHover, {
hover: true
});
}
if(behaviour.drag){
scope_Connects.forEach(function(connect, index){
if(connect===false||index===0||index===scope_Connects.length - 1){
return;
}
handleBefore=scope_Handles[ index - 1 ];
handleAfter=scope_Handles[ index ];
eventHolders=[ connect ];
handlesToDrag=[ handleBefore, handleAfter ];
handleNumbersToDrag=[ index - 1, index ];
addClass(connect, options.cssClasses.draggable);
if(behaviour.fixed){
eventHolders.push(handleBefore.children[ 0 ]);
eventHolders.push(handleAfter.children[ 0 ]);
}
if(behaviour.dragAll){
handlesToDrag=scope_Handles;
handleNumbersToDrag=scope_HandleNumbers;
}
eventHolders.forEach(function(eventHolder){
attachEvent(actions.start, eventHolder, eventStart, {
handles: handlesToDrag,
handleNumbers: handleNumbersToDrag,
connect: connect
});
});
});
}}
function bindEvent(namespacedEvent, callback){
scope_Events[ namespacedEvent ]=scope_Events[ namespacedEvent ]||[];
scope_Events[ namespacedEvent ].push(callback);
if(namespacedEvent.split('.')[ 0 ]==='update'){
scope_Handles.forEach(function(a, index){
fireEvent('update', index);
});
}}
function isInternalNamespace(namespace){
return namespace===INTERNAL_EVENT_NS.aria||namespace===INTERNAL_EVENT_NS.tooltips;
}
function removeEvent(namespacedEvent){
var event=namespacedEvent&&namespacedEvent.split('.')[ 0 ];
var namespace=event ? namespacedEvent.substring(event.length):namespacedEvent;
Object.keys(scope_Events).forEach(function(bind){
var tEvent=bind.split('.')[ 0 ];
var tNamespace=bind.substring(tEvent.length);
if(( ! event||event===tEvent)&&(! namespace||namespace===tNamespace)){
if(! isInternalNamespace(tNamespace)||namespace===tNamespace){
delete scope_Events[ bind ];
}}
});
}
function fireEvent(eventName, handleNumber, tap){
Object.keys(scope_Events).forEach(function(targetEvent){
var eventType=targetEvent.split('.')[ 0 ];
if(eventName===eventType){
scope_Events[ targetEvent ].forEach(function(callback){
callback.call(scope_Self,
scope_Values.map(options.format.to),
handleNumber,
scope_Values.slice(),
tap||false,
scope_Locations.slice(),
scope_Self);
});
}});
}
function checkHandlePosition(reference, handleNumber, to, lookBackward, lookForward, getValue, smoothSteps){
var distance;
if(scope_Handles.length > 1&&! options.events.unconstrained){
if(lookBackward&&handleNumber > 0){
distance=scope_Spectrum.getAbsoluteDistance(reference[ handleNumber - 1 ], options.margin, false);
to=Math.max(to, distance);
}
if(lookForward&&handleNumber < scope_Handles.length - 1){
distance=scope_Spectrum.getAbsoluteDistance(reference[ handleNumber + 1 ], options.margin, true);
to=Math.min(to, distance);
}}
if(scope_Handles.length > 1&&options.limit){
if(lookBackward&&handleNumber > 0){
distance=scope_Spectrum.getAbsoluteDistance(reference[ handleNumber - 1 ], options.limit, false);
to=Math.min(to, distance);
}
if(lookForward&&handleNumber < scope_Handles.length - 1){
distance=scope_Spectrum.getAbsoluteDistance(reference[ handleNumber + 1 ], options.limit, true);
to=Math.max(to, distance);
}}
if(options.padding){
if(handleNumber===0){
distance=scope_Spectrum.getAbsoluteDistance(0, options.padding[ 0 ], false);
to=Math.max(to, distance);
}
if(handleNumber===scope_Handles.length - 1){
distance=scope_Spectrum.getAbsoluteDistance(100, options.padding[ 1 ], true);
to=Math.min(to, distance);
}}
if(! smoothSteps){
to=scope_Spectrum.getStep(to);
}
to=limit(to);
if(to===reference[ handleNumber ]&&! getValue){
return false;
}
return to;
}
function inRuleOrder(v, a){
var o=options.ort;
return(o ? a:v) + ', ' +(o ? v:a);
}
function moveHandles(upward, proposal, locations, handleNumbers, connect){
var proposals=locations.slice();
var firstHandle=handleNumbers[ 0 ];
var smoothSteps=options.events.smoothSteps;
var b=[ ! upward, upward ];
var f=[ upward, ! upward ];
var state=false;
handleNumbers=handleNumbers.slice();
if(upward){
handleNumbers.reverse();
}
if(handleNumbers.length > 1){
handleNumbers.forEach(function(handleNumber, o){
var to=checkHandlePosition(proposals, handleNumber, proposals[ handleNumber ] + proposal, b[ o ], f[ o ], false, smoothSteps);
if(to===false){
proposal=0;
}else{
proposal=to - proposals[ handleNumber ];
proposals[ handleNumber ]=to;
}});
}else{
b=f = [ true ];
}
handleNumbers.forEach(function(handleNumber, o){
state =
setHandle(handleNumber, locations[ handleNumber ] + proposal, b[ o ], f[ o ], false, smoothSteps)||state;
});
if(state){
handleNumbers.forEach(function(handleNumber){
fireEvent('update', handleNumber);
fireEvent('slide', handleNumber);
});
if(connect!==undefined){
fireEvent('drag', firstHandle);
}}
}
function transformDirection(a, b){
return options.dir ? 100 - a - b:a;
}
function updateHandlePosition(handleNumber, to){
var translation;
var translateRule;
scope_Locations[ handleNumber ]=to;
scope_Values[ handleNumber ]=scope_Spectrum.fromStepping(to);
translation=transformDirection(to, 0) - scope_DirOffset;
translateRule='translate(' + inRuleOrder(translation + '%', '0') + ')';
scope_Handles[ handleNumber ].style[ options.transformRule ]=translateRule;
updateConnect(handleNumber);
updateConnect(handleNumber + 1);
}
function setZindex(){
scope_HandleNumbers.forEach(function(handleNumber){
var dir=scope_Locations[ handleNumber ] > 50 ? -1:1;
var zIndex=3 +(scope_Handles.length +(dir * handleNumber));
scope_Handles[ handleNumber ].style.zIndex=String(zIndex);
});
}
function setHandle(handleNumber, to, lookBackward, lookForward, exactInput, smoothSteps){
if(! exactInput){
to=checkHandlePosition(scope_Locations, handleNumber, to, lookBackward, lookForward, false, smoothSteps);
}
if(to===false){
return false;
}
updateHandlePosition(handleNumber, to);
return true;
}
function updateConnect(index){
var l;
var h;
var connectWidth;
var translateRule;
var scaleRule;
if(! scope_Connects[ index ]){
return;
}
l=0;
h=100;
if(index!==0){
l=scope_Locations[ index - 1 ];
}
if(index!==scope_Connects.length - 1){
h=scope_Locations[ index ];
}
connectWidth=h - l;
translateRule='translate(' + inRuleOrder(transformDirection(l, connectWidth) + '%', '0') + ')';
scaleRule='scale(' + inRuleOrder(connectWidth / 100, '1') + ')';
scope_Connects[ index ].style[ options.transformRule ] =
translateRule + ' ' + scaleRule;
}
function resolveToValue(to, handleNumber){
if(to===null||to===false||to===undefined){
return scope_Locations[ handleNumber ];
}
if(typeof to==='number'){
to=String(to);
}
to=options.format.from(to);
if(to!==false){
to=scope_Spectrum.toStepping(to);
}
if(to===false||isNaN(to)){
return scope_Locations[ handleNumber ];
}
return to;
}
function scope_HandleNumbersCallback(exactInput){
return function(handleNumber){
setHandle(handleNumber, scope_Locations[ handleNumber ], true, true, exactInput);
};}
function valueSet(input, fireSetEvent, exactInput){
var values=asArray(input);
var isInit=scope_Locations[ 0 ]===undefined;
var i;
var space_1;
fireSetEvent=fireSetEvent===undefined ? true:fireSetEvent;
if(options.animate&&! isInit){
addClassFor(scope_Target, options.cssClasses.tap, options.animationDuration);
}
scope_HandleNumbers.forEach(function(handleNumber){
setHandle(handleNumber, resolveToValue(values[ handleNumber ], handleNumber), true, false, exactInput);
});
i=scope_HandleNumbers.length===1 ? 0:1;
if(isInit&&scope_Spectrum.hasNoSize()){
exactInput=true;
scope_Locations[ 0 ]=0;
if(scope_HandleNumbers.length > 1){
space_1=100 /(scope_HandleNumbers.length - 1);
scope_HandleNumbers.forEach(function(handleNumber){
scope_Locations[ handleNumber ]=handleNumber * space_1;
});
}}
for(; i < scope_HandleNumbers.length; ++i){
scope_HandleNumbers.forEach(scope_HandleNumbersCallback(exactInput));
}
setZindex();
scope_HandleNumbers.forEach(function(handleNumber){
fireEvent('update', handleNumber);
if(values[ handleNumber ]!==null&&fireSetEvent){
fireEvent('set', handleNumber);
}});
}
function valueReset(fireSetEvent){
valueSet(options.start, fireSetEvent);
}
function valueSetHandle(handleNumber, value, fireSetEvent, exactInput){
handleNumber=Number(handleNumber);
if(!(handleNumber >=0&&handleNumber < scope_HandleNumbers.length)){
throw new Error('noUiSlider: invalid handle number, got: ' + handleNumber);
}
setHandle(handleNumber, resolveToValue(value, handleNumber), true, true, exactInput);
fireEvent('update', handleNumber);
if(fireSetEvent){
fireEvent('set', handleNumber);
}}
function valueGet(unencoded){
var values;
if(unencoded===void 0){
unencoded=false;
}
if(unencoded){
return scope_Values.length===1 ? scope_Values[ 0 ]:scope_Values.slice(0);
}
values=scope_Values.map(options.format.to);
if(values.length===1){
return values[ 0 ];
}
return values;
}
function destroy(){
removeEvent(INTERNAL_EVENT_NS.aria);
removeEvent(INTERNAL_EVENT_NS.tooltips);
Object.keys(options.cssClasses).forEach(function(key){
removeClass(scope_Target, options.cssClasses[ key ]);
});
while(scope_Target.firstChild){
scope_Target.removeChild(scope_Target.firstChild);
}
delete scope_Target.noUiSlider;
}
function getNextStepsForHandle(handleNumber){
var location=scope_Locations[ handleNumber ];
var nearbySteps=scope_Spectrum.getNearbySteps(location);
var value=scope_Values[ handleNumber ];
var increment=nearbySteps.thisStep.step;
var decrement=null;
var stepDecimals;
if(options.snap){
return [
value - nearbySteps.stepBefore.startValue||null,
nearbySteps.stepAfter.startValue - value||null
];
}
if(increment!==false){
if(value + increment > nearbySteps.stepAfter.startValue){
increment=nearbySteps.stepAfter.startValue - value;
}}
if(value > nearbySteps.thisStep.startValue){
decrement=nearbySteps.thisStep.step;
}else if(nearbySteps.stepBefore.step===false){
decrement=false;
}else{
decrement=value - nearbySteps.stepBefore.highestStep;
}
if(location===100){
increment=null;
}else if(location===0){
decrement=null;
}
stepDecimals=scope_Spectrum.countStepDecimals();
if(increment!==null&&increment!==false){
increment=Number(increment.toFixed(stepDecimals));
}
if(decrement!==null&&decrement!==false){
decrement=Number(decrement.toFixed(stepDecimals));
}
return [ decrement, increment ];
}
function getNextSteps(){
return scope_HandleNumbers.map(getNextStepsForHandle);
}
function updateOptions(optionsToUpdate, fireSetEvent){
var v=valueGet();
var updateAble=[
'margin',
'limit',
'padding',
'range',
'animate',
'snap',
'step',
'format',
'pips',
'tooltips'
];
var newOptions;
updateAble.forEach(function(name){
if(optionsToUpdate[ name ]!==undefined){
originalOptions[ name ]=optionsToUpdate[ name ];
}});
newOptions=testOptions(originalOptions);
updateAble.forEach(function(name){
if(optionsToUpdate[ name ]!==undefined){
options[ name ]=newOptions[ name ];
}});
scope_Spectrum=newOptions.spectrum;
options.margin=newOptions.margin;
options.limit=newOptions.limit;
options.padding=newOptions.padding;
if(options.pips){
pips(options.pips);
}else{
removePips();
}
if(options.tooltips){
tooltips();
}else{
removeTooltips();
}
scope_Locations=[];
valueSet(isSet(optionsToUpdate.start) ? optionsToUpdate.start:v, fireSetEvent);
}
function setupSlider(){
scope_Base=addSlider(scope_Target);
addElements(options.connect, scope_Base);
bindSliderEvents(options.events);
valueSet(options.start);
if(options.pips){
pips(options.pips);
}
if(options.tooltips){
tooltips();
}
aria();
}
setupSlider();
scope_Self={
destroy: destroy,
steps: getNextSteps,
on: bindEvent,
off: removeEvent,
get: valueGet,
set: valueSet,
setHandle: valueSetHandle,
reset: valueReset,
disable: disable,
enable: enable,
__moveHandles: function(upward, proposal, handleNumbers){
moveHandles(upward, proposal, scope_Locations, handleNumbers);
},
options: originalOptions,
updateOptions: updateOptions,
target: scope_Target,
removePips: removePips,
removeTooltips: removeTooltips,
getPositions: function(){
return scope_Locations.slice();
},
getTooltips: function(){
return scope_Tooltips;
},
getOrigins: function(){
return scope_Handles;
},
pips: pips
};
return scope_Self;
}
function initialize(target, originalOptions){
var options;
var api;
if(! target||! target.nodeName){
throw new Error('noUiSlider: create requires a single element, got: ' + target);
}
if(target.noUiSlider){
throw new Error('noUiSlider: Slider was already initialized.');
}
options=testOptions(originalOptions);
api=scope(target, options, originalOptions);
target.noUiSlider=api;
return api;
}
nouislider={
__spectrum: Spectrum,
cssClasses: cssClasses,
create: initialize
};
exports.create=initialize;
exports.cssClasses=cssClasses;
exports.default=nouislider;
Object.defineProperty(exports, '__esModule', { value: true });
})));
(function($){
'use strict';
var slice=Array.prototype.slice;
$.extend($.event.special, {
resizestop: {
add: function(handle){
var handler=handle.handler;
$(this).on('resize', function(e){
var _proxy;
clearTimeout(handler._timer);
e.type='resizestop';
_proxy=$.proxy(handler, this, e);
handler._timer=setTimeout(_proxy, handle.data||200);
});
}},
resizestart: {
add: function(handle){
var handler=handle.handler;
$(this).on('resize', function(e){
clearTimeout(handler._timer);
if(! handler._started){
e.type='resizestart';
handler.apply(this, arguments);
handler._started=true;
}
handler._timer=setTimeout(
$.proxy(function(){
handler._started=false;
}, this),
handle.data||300
);
});
}}
});
$.extend($.fn, {
resizestop: function(){
$(this).on.apply(this, [ 'resizestop' ].concat(slice.call(arguments)));
},
resizestart: function(){
$(this).on.apply(this, [ 'resizestart' ].concat(slice.call(arguments)));
}});
}(window.jQuery));
(function(factory){
'use strict';
if(typeof window.define==='function'&&window.define.amd){
window.define([ 'jquery' ], factory);
}else{
factory(window.jQuery);
}}(function($){
'use strict';
var datepicker_instActive;
$.ui.tm_datepicker=$.ui.tm_datepicker||{};
if($.ui.tm_datepicker.version){
return;
}
$.extend($.ui, { tm_datepicker: { version: '1.11.4' }});
function datepicker_getZindex(elem){
var position, value;
while(elem.length&&elem[ 0 ]!==document){
position=elem.css('position');
if(position==='absolute'||position==='relative'||position==='fixed'){
value=parseInt(elem.css('zIndex'), 10);
if(! isNaN(value)&&value!==0){
return value;
}}
elem=elem.parent();
}
return 0;
}
function datepicker_handleMouseover(that){
if(! $.tm_datepicker._isDisabledDatepicker(datepicker_instActive.inline ? datepicker_instActive.dpDiv.parent()[ 0 ]:datepicker_instActive.input[ 0 ])){
$(that).parents('.ui-tm-datepicker-calendar').find('a').removeClass('ui-state-hover');
$(that).addClass('ui-state-hover');
if(that.className.indexOf('ui-tm-datepicker-prev')!==-1){
$(that).addClass('ui-tm-datepicker-prev-hover');
}
if(that.className.indexOf('ui-tm-datepicker-next')!==-1){
$(that).addClass('ui-tm-datepicker-next-hover');
}}
}
function datepicker_bindHover(dpDiv){
var selector='button, .ui-tm-datepicker-prev, .ui-tm-datepicker-next, .ui-tm-datepicker-calendar td a';
return dpDiv
.on('mouseout', selector, function(){
$(this).removeClass('ui-state-hover');
if(this.className.indexOf('ui-tm-datepicker-prev')!==-1){
$(this).removeClass('ui-tm-datepicker-prev-hover');
}
if(this.className.indexOf('ui-tm-datepicker-next')!==-1){
$(this).removeClass('ui-tm-datepicker-next-hover');
}})
.on('mouseover', selector, function(){
datepicker_handleMouseover(this);
});
}
function datepicker_extendRemove(target, props){
var name;
$.extend(target, props);
for(name in props){
if(props[ name ]===null){
target[ name ]=props[ name ];
}}
return target;
}
function Datepicker(){
this._curInst=null;
this._keyEvent=false;
this._disabledInputs=[];
this._datepickerShowing=false;
this._inDialog=false;
this._mainDivId='ui-tm-datepicker-div';
this._inlineClass='ui-tm-datepicker-inline';
this._appendClass='ui-tm-datepicker-append';
this._triggerClass='ui-tm-datepicker-trigger';
this._dialogClass='ui-tm-datepicker-dialog';
this._disableClass='ui-tm-datepicker-disabled';
this._unselectableClass='ui-tm-datepicker-unselectable';
this._currentClass='ui-tm-datepicker-current-day';
this._dayOverClass='ui-tm-datepicker-days-cell-over';
this.regional=[];
this.regional[ '' ]={
closeText: 'Done',
prevText: 'Prev',
nextText: 'Next',
currentText: 'Today',
monthNames: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ],
monthNamesShort: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
dayNames: [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ],
dayNamesShort: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],
dayNamesMin: [ 'Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa' ],
weekHeader: 'Wk',
dateFormat: 'mm/dd/yy',
firstDay: 0,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''
};
this._defaults={
showOn: 'focus', // "focus" for popup on focus,
showAnim: 'fadeIn',
showOptions: {},
defaultDate: null,
appendText: '',
buttonText: '...',
buttonImage: '',
buttonImageOnly: false,
hideIfNoPrevNext: false,
navigationAsDateFormat: false,
gotoCurrent: false,
changeMonth: false,
changeYear: false,
yearRange: 'c-10:c+10',
showOtherMonths: false,
selectOtherMonths: false,
showWeek: false,
calculateWeek: this.iso8601Week,
shortYearCutoff: '+10',
minDate: null,
maxDate: null,
duration: 'fast',
beforeShowDay: null,
beforeShow: null,
onSelect: null,
onChangeMonthYear: null,
onClose: null,
numberOfMonths: 1,
showCurrentAtPos: 0,
stepMonths: 1,
stepBigMonths: 12,
altField: '',
altFormat: '',
constrainInput: true,
showButtonPanel: false,
autoSize: false,
disabled: false
};
$.extend(this._defaults, this.regional[ '' ]);
this.regional.en=$.extend(true, {}, this.regional[ '' ]);
this.regional[ 'en-US' ]=$.extend(true, {}, this.regional.en);
this.dpDiv=datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-tm-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));
}
$.extend(Datepicker.prototype, {
markerClassName: 'hasDatepicker',
maxRows: 4,
_widgetDatepicker: function(){
return this.dpDiv;
},
setDefaults: function(settings){
datepicker_extendRemove(this._defaults, settings||{});
return this;
},
_attachDatepicker: function(target, settings){
var nodeName, inline, inst;
nodeName=target.nodeName.toLowerCase();
inline=nodeName==='div'||nodeName==='span';
if(! target.id){
this.uuid +=1;
target.id='dp' + this.uuid;
}
inst=this._newInst($(target), inline);
inst.settings=$.extend({}, settings||{});
if(nodeName==='input'){
this._connectDatepicker(target, inst);
}else if(inline){
this._inlineDatepicker(target, inst);
}},
_newInst: function(target, inline){
var id=target[ 0 ].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1');
return {
id: id,
input: target,
selectedDay: 0,
selectedMonth: 0,
selectedYear: 0,
drawMonth: 0,
drawYear: 0,
inline: inline,
dpDiv: ! inline ? this.dpDiv:datepicker_bindHover($("<div class='" + this._inlineClass + " ui-tm-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))
};},
_connectDatepicker: function(target, inst){
var input=$(target);
inst.append=$([]);
inst.trigger=$([]);
if(input.hasClass(this.markerClassName)){
return;
}
this._attachments(input, inst);
input.addClass(this.markerClassName).on('keydown', this._doKeyDown).on('keypress', this._doKeyPress).on('keyup', this._doKeyUp);
this._autoSize(inst);
$.data(target, 'datepicker', inst);
if(inst.settings.disabled){
this._disableDatepicker(target);
}},
_attachments: function(input, inst){
var showOn,
buttonText,
buttonImage,
appendText=this._get(inst, 'appendText'),
isRTL=this._get(inst, 'isRTL');
if(inst.append){
inst.append.remove();
}
if(appendText){
inst.append=$("<span class='" + this._appendClass + "'>" + appendText + '</span>');
input[ isRTL ? 'before':'after' ](inst.append);
}
input.off('focus', this._showDatepicker);
if(inst.trigger){
inst.trigger.remove();
}
showOn=this._get(inst, 'showOn');
if(showOn==='focus'||showOn==='both'){
input.on('focus', this._showDatepicker);
}
if(showOn==='button'||showOn==='both'){
buttonText=this._get(inst, 'buttonText');
buttonImage=this._get(inst, 'buttonImage');
inst.trigger=$(
this._get(inst, 'buttonImageOnly')
? $('<img/>').addClass(this._triggerClass).attr({ src: buttonImage, alt: buttonText, title: buttonText })
: $("<button type='button'></button>")
.addClass(this._triggerClass)
.html(! buttonImage ? buttonText:$('<img/>').attr({ src: buttonImage, alt: buttonText, title: buttonText }))
);
input[ isRTL ? 'before':'after' ](inst.trigger);
inst.trigger.on('click', function(){
if($.tm_datepicker._datepickerShowing&&$.tm_datepicker._lastInput===input[ 0 ]){
$.tm_datepicker._hideDatepicker();
}else if($.tm_datepicker._datepickerShowing&&$.tm_datepicker._lastInput!==input[ 0 ]){
$.tm_datepicker._hideDatepicker();
$.tm_datepicker._showDatepicker(input[ 0 ]);
}else{
$.tm_datepicker._showDatepicker(input[ 0 ]);
}
return false;
});
}},
_autoSize: function(inst){
var findMax;
var max;
var maxI;
var i;
var date;
var dateFormat=this._get(inst, 'dateFormat');
if(this._get(inst, 'autoSize')&&! inst.inline){
date=new Date(2009, 12 - 1, 20);
dateFormat=this._get(inst, 'dateFormat');
if(dateFormat.match(/[DM]/)){
findMax=function(names){
max=0;
maxI=0;
for(i=0; i < names.length; i +=1){
if(names[ i ].length > max){
max=names[ i ].length;
maxI=i;
}}
return maxI;
};
date.setMonth(findMax(this._get(inst, dateFormat.match(/MM/) ? 'monthNames':'monthNamesShort')));
date.setDate(findMax(this._get(inst, dateFormat.match(/DD/) ? 'dayNames':'dayNamesShort')) + 20 - date.getDay());
}
inst.input.attr('size', this._formatDate(inst, date).length);
}},
_inlineDatepicker: function(target, inst){
var divSpan=$(target);
if(divSpan.hasClass(this.markerClassName)){
return;
}
divSpan.addClass(this.markerClassName).append(inst.dpDiv);
$.data(target, 'datepicker', inst);
this._setDate(inst, this._getDefaultDate(inst), true);
this._updateDatepicker(inst);
this._updateAlternate(inst);
if(inst.settings.disabled){
this._disableDatepicker(target);
}
inst.dpDiv.css('display', 'block');
},
_dialogDatepicker: function(input, date, onSelect, settings, pos){
var id,
browserWidth,
browserHeight,
scrollX,
scrollY,
inst=this._dialogInst;
if(! inst){
this.uuid +=1;
id='dp' + this.uuid;
this._dialogInput=$("<input type='text' id='" + id + "'>");
this._dialogInput.on('keydown', this._doKeyDown);
$('body').append(this._dialogInput);
inst=this._newInst(this._dialogInput, false);
this._dialogInst=inst;
inst.settings={};
$.data(this._dialogInput[ 0 ], 'datepicker', inst);
}
datepicker_extendRemove(inst.settings, settings||{});
date=date&&date.constructor===Date ? this._formatDate(inst, date):date;
this._dialogInput.val(date);
this._pos=pos ?(pos.length ? pos:[ pos.pageX, pos.pageY ]):null;
if(! this._pos){
browserWidth=document.documentElement.clientWidth;
browserHeight=document.documentElement.clientHeight;
scrollX=document.documentElement.scrollLeft||document.body.scrollLeft;
scrollY=document.documentElement.scrollTop||document.body.scrollTop;
this._pos =
[(browserWidth / 2) - 100 + scrollX,(browserHeight / 2) - 150 + scrollY ];
}
this._dialogInput.css('left', this._pos[ 0 ] + 20 + 'px').css('top', this._pos[ 1 ] + 'px');
inst.settings.onSelect=onSelect;
this._inDialog=true;
this.dpDiv.addClass(this._dialogClass);
this._showDatepicker(this._dialogInput[ 0 ]);
if($.blockUI){
$.blockUI(this.dpDiv);
}
$.data(this._dialogInput[ 0 ], 'datepicker', inst);
return this;
},
_destroyDatepicker: function(target){
var nodeName,
$target=$(target),
inst=$.data(target, 'datepicker');
if(! $target.hasClass(this.markerClassName)){
return;
}
nodeName=target.nodeName.toLowerCase();
$.removeData(target, 'datepicker');
if(nodeName==='input'){
inst.append.remove();
inst.trigger.remove();
$target.removeClass(this.markerClassName).off('focus', this._showDatepicker).off('keydown', this._doKeyDown).off('keypress', this._doKeyPress).off('keyup', this._doKeyUp);
}else if(nodeName==='div'||nodeName==='span'){
$target.removeClass(this.markerClassName).empty();
}
if(datepicker_instActive===inst){
datepicker_instActive=null;
}},
_enableDatepicker: function(target){
var nodeName,
inline,
$target=$(target),
inst=$.data(target, 'datepicker');
if(! $target.hasClass(this.markerClassName)){
return;
}
nodeName=target.nodeName.toLowerCase();
if(nodeName==='input'){
target.disabled=false;
inst.trigger
.filter('button')
.each(function(){
this.disabled=false;
})
.end()
.filter('img')
.css({ opacity: '1.0', cursor: '' });
}else if(nodeName==='div'||nodeName==='span'){
inline=$target.children('.' + this._inlineClass);
inline.children().removeClass('ui-state-disabled');
inline.find('select.ui-tm-datepicker-month, select.ui-tm-datepicker-year').prop('disabled', false);
}
this._disabledInputs=$.map(this._disabledInputs, function(value){
return value===target ? null:value;
});
},
_disableDatepicker: function(target){
var nodeName,
inline,
$target=$(target),
inst=$.data(target, 'datepicker');
if(! $target.hasClass(this.markerClassName)){
return;
}
nodeName=target.nodeName.toLowerCase();
if(nodeName==='input'){
target.disabled=true;
inst.trigger
.filter('button')
.each(function(){
this.disabled=true;
})
.end()
.filter('img')
.css({ opacity: '0.5', cursor: 'default' });
}else if(nodeName==='div'||nodeName==='span'){
inline=$target.children('.' + this._inlineClass);
inline.children().addClass('ui-state-disabled');
inline.find('select.ui-tm-datepicker-month, select.ui-tm-datepicker-year').prop('disabled', true);
}
this._disabledInputs=$.map(this._disabledInputs, function(value){
return value===target ? null:value;
});
this._disabledInputs[ this._disabledInputs.length ]=target;
},
_isDisabledDatepicker: function(target){
var i;
if(! target){
return false;
}
for(i=0; i < this._disabledInputs.length; i +=1){
if(this._disabledInputs[ i ]===target){
return true;
}}
return false;
},
_getInst: function(target){
try {
return $.data(target, 'datepicker');
} catch(err){
throw 'Missing instance data for this datepicker';
}},
_optionDatepicker: function(target, name, value){
var settings,
date,
minDate,
maxDate,
inst=this._getInst(target);
if(arguments.length===2&&typeof name==='string'){
return name==='defaults' ? $.extend({}, $.tm_datepicker._defaults):inst ?(name==='all' ? $.extend({}, inst.settings):this._get(inst, name)):null;
}
settings=name||{};
if(typeof name==='string'){
settings={};
settings[ name ]=value;
}
if(inst){
if(this._curInst===inst){
this._hideDatepicker();
}
date=this._getDateDatepicker(target, true);
minDate=this._getMinMaxDate(inst, 'min');
maxDate=this._getMinMaxDate(inst, 'max');
datepicker_extendRemove(inst.settings, settings);
if(minDate!==null&&settings.dateFormat!==undefined&&settings.minDate===undefined){
inst.settings.minDate=this._formatDate(inst, minDate);
}
if(maxDate!==null&&settings.dateFormat!==undefined&&settings.maxDate===undefined){
inst.settings.maxDate=this._formatDate(inst, maxDate);
}
if('disabled' in settings){
if(settings.disabled){
this._disableDatepicker(target);
}else{
this._enableDatepicker(target);
}}
this._attachments($(target), inst);
this._autoSize(inst);
this._setDate(inst, date);
this._updateAlternate(inst);
this._updateDatepicker(inst);
}},
_changeDatepicker: function(target, name, value){
this._optionDatepicker(target, name, value);
},
_refreshDatepicker: function(target){
var inst=this._getInst(target);
if(inst){
this._updateDatepicker(inst);
}},
_setDateDatepicker: function(target, date){
var inst=this._getInst(target);
if(inst){
this._setDate(inst, date);
this._updateDatepicker(inst);
this._updateAlternate(inst);
}},
_getDateDatepicker: function(target, noDefault){
var inst=this._getInst(target);
if(inst&&! inst.inline){
this._setDateFromField(inst, noDefault);
}
return inst ? this._getDate(inst):null;
},
_doKeyDown: function(event){
var onSelect,
dateStr,
sel,
inst=$.tm_datepicker._getInst(event.target),
handled=true,
isRTL=inst.dpDiv.is('.ui-tm-datepicker-rtl');
inst._keyEvent=true;
if($.tm_datepicker._datepickerShowing){
switch(event.keyCode){
case 9:
$.tm_datepicker._hideDatepicker();
handled=false;
break;
case 13:
sel=$('td.' + $.tm_datepicker._dayOverClass + ':not(.' + $.tm_datepicker._currentClass + ')', inst.dpDiv);
if(sel[ 0 ]){
$.tm_datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[ 0 ]);
}
onSelect=$.tm_datepicker._get(inst, 'onSelect');
if(onSelect){
dateStr=$.tm_datepicker._formatDate(inst);
onSelect.apply(inst.input ? inst.input[ 0 ]:null, [ dateStr, inst ]);
}else{
$.tm_datepicker._hideDatepicker();
}
return false;
case 27:
$.tm_datepicker._hideDatepicker();
break;
case 33:
$.tm_datepicker._adjustDate(event.target, event.ctrlKey ? -$.tm_datepicker._get(inst, 'stepBigMonths'):-$.tm_datepicker._get(inst, 'stepMonths'), 'M');
break;
case 34:
$.tm_datepicker._adjustDate(event.target, event.ctrlKey ? +$.tm_datepicker._get(inst, 'stepBigMonths'):+$.tm_datepicker._get(inst, 'stepMonths'), 'M');
break;
case 35:
if(event.ctrlKey||event.metaKey){
$.tm_datepicker._clearDate(event.target);
}
handled=event.ctrlKey||event.metaKey;
break;
case 36:
if(event.ctrlKey||event.metaKey){
$.tm_datepicker._gotoToday(event.target);
}
handled=event.ctrlKey||event.metaKey;
break;
case 37:
if(event.ctrlKey||event.metaKey){
$.tm_datepicker._adjustDate(event.target, isRTL ? +1:-1, 'D');
}
handled=event.ctrlKey||event.metaKey;
if(event.originalEvent.altKey){
$.tm_datepicker._adjustDate(event.target, event.ctrlKey ? -$.tm_datepicker._get(inst, 'stepBigMonths'):-$.tm_datepicker._get(inst, 'stepMonths'), 'M');
}
break;
case 38:
if(event.ctrlKey||event.metaKey){
$.tm_datepicker._adjustDate(event.target, -7, 'D');
}
handled=event.ctrlKey||event.metaKey;
break;
case 39:
if(event.ctrlKey||event.metaKey){
$.tm_datepicker._adjustDate(event.target, isRTL ? -1:+1, 'D');
}
handled=event.ctrlKey||event.metaKey;
if(event.originalEvent.altKey){
$.tm_datepicker._adjustDate(event.target, event.ctrlKey ? +$.tm_datepicker._get(inst, 'stepBigMonths'):+$.tm_datepicker._get(inst, 'stepMonths'), 'M');
}
break;
case 40:
if(event.ctrlKey||event.metaKey){
$.tm_datepicker._adjustDate(event.target, +7, 'D');
}
handled=event.ctrlKey||event.metaKey;
break;
default:
handled=false;
}}else if(event.keyCode===36&&event.ctrlKey){
$.tm_datepicker._showDatepicker(this);
}else{
handled=false;
}
if(handled){
event.preventDefault();
event.stopPropagation();
}},
_doKeyPress: function(event){
var chars,
chr,
inst=$.tm_datepicker._getInst(event.target);
if($.tm_datepicker._get(inst, 'constrainInput')){
chars=$.tm_datepicker._possibleChars($.tm_datepicker._get(inst, 'dateFormat'));
chr=String.fromCharCode(event.charCode===null ? event.keyCode:event.charCode);
return event.ctrlKey||event.metaKey||chr < ' '||! chars||chars.indexOf(chr) > -1;
}},
_doKeyUp: function(event){
var date,
inst=$.tm_datepicker._getInst(event.target);
if(inst.input.val()!==inst.lastVal){
try {
date=$.tm_datepicker.parseDate($.tm_datepicker._get(inst, 'dateFormat'), inst.input ? inst.input.val():null, $.tm_datepicker._getFormatConfig(inst));
if(date){
$.tm_datepicker._setDateFromField(inst);
$.tm_datepicker._updateAlternate(inst);
$.tm_datepicker._updateDatepicker(inst);
}} catch(err){
return false;
}}
return true;
},
_showDatepicker: function(input){
var inst;
var beforeShow;
var beforeShowSettings;
var isFixed;
var offset;
var showAnim;
var duration;
input=input.target||input;
if(input.nodeName.toLowerCase()!=='input'){
input=$('input', input.parentNode)[ 0 ];
}
if($.tm_datepicker._isDisabledDatepicker(input)||$.tm_datepicker._lastInput===input){
return;
}
inst=$.tm_datepicker._getInst(input);
if($.tm_datepicker._curInst&&$.tm_datepicker._curInst!==inst){
$.tm_datepicker._curInst.dpDiv.stop(true, true);
if(inst&&$.tm_datepicker._datepickerShowing){
$.tm_datepicker._hideDatepicker($.tm_datepicker._curInst.input[ 0 ]);
}}
beforeShow=$.tm_datepicker._get(inst, 'beforeShow');
beforeShowSettings=beforeShow ? beforeShow.apply(input, [ input, inst ]):{};
if(beforeShowSettings===false){
return;
}
datepicker_extendRemove(inst.settings, beforeShowSettings);
inst.lastVal=null;
$.tm_datepicker._lastInput=input;
$.tm_datepicker._setDateFromField(inst);
if($.tm_datepicker._inDialog){
input.value='';
}
if(! $.tm_datepicker._pos){
$.tm_datepicker._pos=$.tm_datepicker._findPos(input);
$.tm_datepicker._pos[ 1 ] +=input.offsetHeight;
}
isFixed=false;
$(input)
.parents()
.each(function(){
isFixed=isFixed||$(this).css('position')==='fixed';
return ! isFixed;
});
offset={ left: $.tm_datepicker._pos[ 0 ], top: $.tm_datepicker._pos[ 1 ] };
$.tm_datepicker._pos=null;
inst.dpDiv.empty();
inst.dpDiv.css({ position: 'absolute', display: 'block', top: '-1000px' });
$.tm_datepicker._updateDatepicker(inst);
offset=$.tm_datepicker._checkOffset(inst, offset, isFixed);
inst.dpDiv.css({
position: $.tm_datepicker._inDialog&&$.blockUI ? 'static':isFixed ? 'fixed':'absolute',
display: 'none',
left: offset.left + 'px',
top: offset.top + 'px'
});
if(! inst.inline){
showAnim=$.tm_datepicker._get(inst, 'showAnim');
duration=$.tm_datepicker._get(inst, 'duration');
inst.dpDiv.css('z-index', datepicker_getZindex($(input)) + 1);
$.tm_datepicker._datepickerShowing=true;
if($.effects&&$.effects.effect[ showAnim ]){
inst.dpDiv.show(showAnim, $.tm_datepicker._get(inst, 'showOptions'), duration);
}else{
inst.dpDiv[ showAnim||'show' ](showAnim ? duration:null);
}
if($.tm_datepicker._shouldFocusInput(inst)){
inst.input.trigger('focus');
}
$.tm_datepicker._curInst=inst;
}},
_updateDatepicker: function(inst){
var origyearshtml;
var numMonths;
var cols;
var width=17;
var activeCell;
this.maxRows=4;
datepicker_instActive=inst;
inst.dpDiv.empty().append(this._generateHTML(inst));
this._attachHandlers(inst);
numMonths=this._getNumberOfMonths(inst);
cols=numMonths[ 1 ];
activeCell=inst.dpDiv.find('.' + this._dayOverClass + ' a');
if(activeCell.length > 0){
datepicker_handleMouseover.apply(activeCell.get(0), [ activeCell.get(0) ]);
}
inst.dpDiv.removeClass('ui-tm-datepicker-multi-2 ui-tm-datepicker-multi-3 ui-tm-datepicker-multi-4').width('');
if(cols > 1){
inst.dpDiv.addClass('ui-tm-datepicker-multi-' + cols).css('width',(width * cols) + 'em');
}
inst.dpDiv[(numMonths[ 0 ]!==1||numMonths[ 1 ]!==1 ? 'add':'remove') + 'Class' ]('ui-tm-datepicker-multi');
inst.dpDiv[(this._get(inst, 'isRTL') ? 'add':'remove') + 'Class' ]('ui-tm-datepicker-rtl');
if(inst===$.tm_datepicker._curInst&&$.tm_datepicker._datepickerShowing&&$.tm_datepicker._shouldFocusInput(inst)){
inst.input.trigger('focus');
}
if(inst.yearshtml){
origyearshtml=inst.yearshtml;
setTimeout(function(){
if(origyearshtml===inst.yearshtml&&inst.yearshtml){
inst.dpDiv.find('select.ui-tm-datepicker-year:first').replaceWith(inst.yearshtml);
}
origyearshtml=null;
inst.yearshtml=null;
}, 0);
}},
_shouldFocusInput: function(inst){
return inst.input&&inst.input.is(':visible')&&! inst.input.is(':disabled')&&! inst.input.is(':focus');
},
_checkOffset: function(inst, offset, isFixed){
var dpWidth=inst.dpDiv.outerWidth(),
dpHeight=inst.dpDiv.outerHeight(),
inputWidth=inst.input ? inst.input.outerWidth():0,
inputHeight=inst.input ? inst.input.outerHeight():0,
viewWidth=document.documentElement.clientWidth +(isFixed ? 0:$(document).scrollLeft()),
viewHeight=document.documentElement.clientHeight +(isFixed ? 0:$(document).scrollTop());
offset.left -=this._get(inst, 'isRTL') ? dpWidth - inputWidth:0;
offset.left -=isFixed&&offset.left===inst.input.offset().left ? $(document).scrollLeft():0;
offset.top -=isFixed&&offset.top===inst.input.offset().top + inputHeight ? $(document).scrollTop():0;
offset.left -=Math.min(offset.left, offset.left + dpWidth > viewWidth&&viewWidth > dpWidth ? Math.abs(offset.left + dpWidth - viewWidth):0);
offset.top -=Math.min(offset.top, offset.top + dpHeight > viewHeight&&viewHeight > dpHeight ? Math.abs(dpHeight + inputHeight):0);
return offset;
},
_findPos: function(obj){
var position,
inst=this._getInst(obj),
isRTL=this._get(inst, 'isRTL');
while(obj&&(obj.type==='hidden'||obj.nodeType!==1||$.expr.filters.hidden(obj))){
obj=obj[ isRTL ? 'previousSibling':'nextSibling' ];
}
position=$(obj).offset();
return [ position.left, position.top ];
},
_hideDatepicker: function(input){
var showAnim,
duration,
postProcess,
onClose,
inst=this._curInst;
if(! inst||(input&&inst!==$.data(input, 'datepicker'))){
return;
}
if(this._datepickerShowing){
showAnim=this._get(inst, 'showAnim');
duration=this._get(inst, 'duration');
postProcess=function(){
$.tm_datepicker._tidyDialog(inst);
};
if($.effects&&($.effects.effect[ showAnim ]||$.effects[ showAnim ])){
inst.dpDiv.hide(showAnim, $.tm_datepicker._get(inst, 'showOptions'), duration, postProcess);
}else{
inst.dpDiv[ showAnim==='slideDown' ? 'slideUp':showAnim==='fadeIn' ? 'fadeOut':'hide' ](showAnim ? duration:null, postProcess);
}
if(! showAnim){
postProcess();
}
this._datepickerShowing=false;
onClose=this._get(inst, 'onClose');
if(onClose){
onClose.apply(inst.input ? inst.input[ 0 ]:null, [ inst.input ? inst.input.val():'', inst ]);
}
this._lastInput=null;
if(this._inDialog){
this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
if($.blockUI){
$.unblockUI();
$('body').append(this.dpDiv);
}}
this._inDialog=false;
}},
_tidyDialog: function(inst){
inst.dpDiv.removeClass(this._dialogClass).off('.ui-tm-datepicker-calendar');
},
_checkExternalClick: function(event){
var $target;
var inst;
if(! $.tm_datepicker._curInst){
return;
}
$target=$(event.target);
inst=$.tm_datepicker._getInst($target[ 0 ]);
if(( $target[ 0 ].id!==$.tm_datepicker._mainDivId&&$target.parents('#' + $.tm_datepicker._mainDivId).length===0&&! $target.hasClass($.tm_datepicker.markerClassName)&&! $target.closest('.' + $.tm_datepicker._triggerClass).length&&$.tm_datepicker._datepickerShowing&&!($.tm_datepicker._inDialog&&$.blockUI))||($target.hasClass($.tm_datepicker.markerClassName)&&$.tm_datepicker._curInst!==inst)){
$.tm_datepicker._hideDatepicker();
}},
_adjustDate: function(id, offset, period){
var target=$(id),
inst=this._getInst(target[ 0 ]);
if(this._isDisabledDatepicker(target[ 0 ])){
return;
}
this._adjustInstDate(inst,
offset +(period==='M' ? this._get(inst, 'showCurrentAtPos'):0),
period
);
this._updateDatepicker(inst);
},
_gotoToday: function(id){
var date,
target=$(id),
inst=this._getInst(target[ 0 ]);
if(this._get(inst, 'gotoCurrent')&&inst.currentDay){
inst.selectedDay=inst.currentDay;
inst.drawMonth=inst.currentMonth;
inst.selectedMonth=inst.currentMonth;
inst.drawYear=inst.currentYear;
inst.selectedYear=inst.currentYear;
}else{
date=new Date();
inst.selectedDay=date.getDate();
inst.drawMonth=date.getMonth();
inst.selectedMonth=inst.drawMonth;
inst.drawYear=date.getFullYear();
inst.selectedYear=inst.drawYear;
}
this._notifyChange(inst);
this._adjustDate(target);
},
_selectMonthYear: function(id, select, period){
var target=$(id),
inst=this._getInst(target[ 0 ]);
inst[ 'selected' +(period==='M' ? 'Month':'Year') ]=parseInt(select.options[ select.selectedIndex ].value, 10);
inst[ 'draw' +(period==='M' ? 'Month':'Year') ]=parseInt(select.options[ select.selectedIndex ].value, 10);
this._notifyChange(inst);
this._adjustDate(target);
},
_selectDay: function(id, month, year, td){
var inst,
target=$(id);
if($(td).hasClass(this._unselectableClass)||this._isDisabledDatepicker(target[ 0 ])){
return;
}
inst=this._getInst(target[ 0 ]);
inst.selectedDay=$('a', td).html();
inst.currentDay=inst.selectedDay;
inst.selectedMonth=month;
inst.currentMonth=month;
inst.selectedYear=year;
inst.currentYear=year;
this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear));
},
_clearDate: function(id){
var target=$(id);
this._selectDate(target, '');
},
_selectDate: function(id, dateStr){
var onSelect,
target=$(id),
inst=this._getInst(target[ 0 ]);
dateStr=dateStr!==null ? dateStr:this._formatDate(inst);
if(inst.input){
inst.input.val(dateStr);
}
this._updateAlternate(inst);
onSelect=this._get(inst, 'onSelect');
if(onSelect){
onSelect.apply(inst.input ? inst.input[ 0 ]:null, [ dateStr, inst ]);
}else if(inst.input){
inst.input.trigger('change');
}
if(inst.inline){
this._updateDatepicker(inst);
}else{
this._hideDatepicker();
this._lastInput=inst.input[ 0 ];
if(typeof inst.input[ 0 ]!=='object'){
inst.input.trigger('focus');
}
this._lastInput=null;
}},
_updateAlternate: function(inst){
var altFormat,
date,
dateStr,
altField=this._get(inst, 'altField');
if(altField){
altFormat=this._get(inst, 'altFormat')||this._get(inst, 'dateFormat');
date=this._getDate(inst);
dateStr=this.formatDate(altFormat, date, this._getFormatConfig(inst));
$(altField).val(dateStr);
}},
noWeekends: function(date){
var day=date.getDay();
return [ day > 0&&day < 6, '' ];
},
iso8601Week: function(date){
var time,
checkDate=new Date(date.getTime());
checkDate.setDate(checkDate.getDate() + 4 -(checkDate.getDay()||7));
time=checkDate.getTime();
checkDate.setMonth(0);
checkDate.setDate(1);
return Math.floor(Math.round(( time - checkDate) / 86400000) / 7) + 1;
},
parseDate: function(format, value, settings){
var iFormat;
var dim;
var extra;
var iValue=0;
var shortYearCutoffTemp;
var shortYearCutoff;
var dayNamesShort;
var dayNames;
var monthNamesShort;
var monthNames;
var year=-1;
var month=-1;
var day=-1;
var doy=-1;
var literal=false;
var date;
var lookAhead;
var getNumber;
var getName;
var checkLiteral;
var condition;
if(format===null||value===null){
throw 'Invalid arguments';
}
value=typeof value==='object' ? value.toString():value + '';
if(value===''){
return null;
}
shortYearCutoffTemp=(settings ? settings.shortYearCutoff:null)||this._defaults.shortYearCutoff;
shortYearCutoff=typeof shortYearCutoffTemp!=='string' ? shortYearCutoffTemp:(new Date().getFullYear() % 100) + parseInt(shortYearCutoffTemp, 10);
dayNamesShort=(settings ? settings.dayNamesShort:null)||this._defaults.dayNamesShort;
dayNames=(settings ? settings.dayNames:null)||this._defaults.dayNames;
monthNamesShort=(settings ? settings.monthNamesShort:null)||this._defaults.monthNamesShort;
monthNames=(settings ? settings.monthNames:null)||this._defaults.monthNames;
lookAhead=function(match){
var matches=iFormat + 1 < format.length&&format.charAt(iFormat + 1)===match;
if(matches){
iFormat=iFormat + 1;
}
return matches;
};
getNumber=function(match){
var isDoubled=lookAhead(match),
size=match==='@' ? 14:match==='!' ? 20:match==='y'&&isDoubled ? 4:match==='o' ? 3:2,
minSize=match==='y' ? size:1,
digits=new RegExp('^\\d{' + minSize + ',' + size + '}'),
num=value.substring(iValue).match(digits);
if(! num){
throw 'Missing number at position ' + iValue;
}
iValue +=num[ 0 ].length;
return parseInt(num[ 0 ], 10);
};
getName=function(match, shortNames, longNames){
var index=-1,
names=$.map(lookAhead(match) ? longNames:shortNames, function(v, k){
return [ [ k, v ] ];
}).sort(function(a, b){
return -(a[ 1 ].length - b[ 1 ].length);
});
$.each(names, function(i, pair){
var name=pair[ 1 ];
if(value.substring(iValue, parseInt(iValue, 10) + name.length).toLowerCase()===name.toLowerCase()){
index=pair[ 0 ];
iValue +=name.length;
return false;
}});
if(index!==-1){
return index + 1;
}
throw 'Unknown name at position ' + iValue;
};
checkLiteral=function(){
if(value.charAt(iValue)!==format.charAt(iFormat)){
throw 'Unexpected literal at position ' + iValue;
}
iValue=iValue + 1;
};
for(iFormat=0; iFormat < format.length; iFormat +=1){
if(literal){
if(format.charAt(iFormat)==="'"&&! lookAhead("'")){
literal=false;
}else{
checkLiteral();
}}else{
switch(format.charAt(iFormat)){
case 'd':
day=getNumber('d');
break;
case 'D':
getName('D', dayNamesShort, dayNames);
break;
case 'o':
doy=getNumber('o');
break;
case 'm':
month=getNumber('m');
break;
case 'M':
month=getName('M', monthNamesShort, monthNames);
break;
case 'y':
year=getNumber('y');
break;
case '@':
date=new Date(getNumber('@'));
year=date.getFullYear();
month=date.getMonth() + 1;
day=date.getDate();
break;
case '!':
date=new Date(( getNumber('!') - this._ticksTo1970) / 10000);
year=date.getFullYear();
month=date.getMonth() + 1;
day=date.getDate();
break;
case "'":
if(lookAhead("'")){
checkLiteral();
}else{
literal=true;
}
break;
default:
checkLiteral();
}}
}
if(iValue < value.length){
extra=value.substring(iValue);
if(! /^\s+/.test(extra)){
throw 'Extra/unparsed characters found in date: ' + extra;
}}
if(year===-1){
year=new Date().getFullYear();
}else if(year < 100){
year +=new Date().getFullYear() -(new Date().getFullYear() % 100) +(year <=shortYearCutoff ? 0:-100);
}
if(doy > -1){
month=1;
day=doy;
condition=true;
do {
dim=this._getDaysInMonth(year, month - 1);
if(day <=dim){
condition=false;
}else{
month=month + 1;
day -=dim;
}} while(condition);
}
date=this._daylightSavingAdjust(new Date(year, month - 1, day));
if(date.getFullYear()!==year||date.getMonth() + 1!==month||date.getDate()!==day){
throw 'Invalid date';
}
return date;
},
ATOM: 'yy-mm-dd',
COOKIE: 'D, dd M yy',
ISO_8601: 'yy-mm-dd',
RFC_822: 'D, d M y',
RFC_850: 'DD, dd-M-y',
RFC_1036: 'D, d M y',
RFC_1123: 'D, d M yy',
RFC_2822: 'D, d M yy',
RSS: 'D, d M y',
TICKS: '!',
TIMESTAMP: '@',
W3C: 'yy-mm-dd',
_ticksTo1970:(((1970 - 1) * 365) + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000,
formatDate: function(format, date, settings){
var iFormat,
dayNamesShort=(settings ? settings.dayNamesShort:null)||this._defaults.dayNamesShort,
dayNames=(settings ? settings.dayNames:null)||this._defaults.dayNames,
monthNamesShort=(settings ? settings.monthNamesShort:null)||this._defaults.monthNamesShort,
monthNames=(settings ? settings.monthNames:null)||this._defaults.monthNames,
lookAhead=function(match){
var matches=iFormat + 1 < format.length&&format.charAt(iFormat + 1)===match;
if(matches){
iFormat=iFormat + 1;
}
return matches;
},
formatNumber=function(match, value, len){
var num='' + value;
if(lookAhead(match)){
while(num.length < len){
num='0' + num;
}}
return num;
},
formatName=function(match, value, shortNames, longNames){
return lookAhead(match) ? longNames[ value ]:shortNames[ value ];
},
output='',
literal=false;
if(! date){
return '';
}
if(date){
for(iFormat=0; iFormat < format.length; iFormat +=1){
if(literal){
if(format.charAt(iFormat)==="'"&&! lookAhead("'")){
literal=false;
}else{
output +=format.charAt(iFormat);
}}else{
switch(format.charAt(iFormat)){
case 'd':
output +=formatNumber('d', date.getDate(), 2);
break;
case 'D':
output +=formatName('D', date.getDay(), dayNamesShort, dayNames);
break;
case 'o':
output +=formatNumber('o', Math.round(( new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
break;
case 'm':
output +=formatNumber('m', date.getMonth() + 1, 2);
break;
case 'M':
output +=formatName('M', date.getMonth(), monthNamesShort, monthNames);
break;
case 'y':
output +=lookAhead('y') ? date.getFullYear():(date.getFullYear() % 100 < 10 ? '0':'') +(date.getFullYear() % 100);
break;
case '@':
output +=date.getTime();
break;
case '!':
output +=(date.getTime() * 10000) + this._ticksTo1970;
break;
case "'":
if(lookAhead("'")){
output +="'";
}else{
literal=true;
}
break;
default:
output +=format.charAt(iFormat);
}}
}}
return output;
},
_possibleChars: function(format){
var iFormat,
chars='',
literal=false,
lookAhead=function(match){
var matches=iFormat + 1 < format.length&&format.charAt(iFormat + 1)===match;
if(matches){
iFormat=iFormat + 1;
}
return matches;
};
for(iFormat=0; iFormat < format.length; iFormat +=1){
if(literal){
if(format.charAt(iFormat)==="'"&&! lookAhead("'")){
literal=false;
}else{
chars +=format.charAt(iFormat);
}}else{
switch(format.charAt(iFormat)){
case 'd':
case 'm':
case 'y':
case '@':
chars +='0123456789';
break;
case 'D':
case 'M':
return null;
case "'":
if(lookAhead("'")){
chars +="'";
}else{
literal=true;
}
break;
default:
chars +=format.charAt(iFormat);
}}
}
return chars;
},
_get: function(inst, name){
return inst.settings[ name ]!==undefined ? inst.settings[ name ]:this._defaults[ name ];
},
_setDateFromField: function(inst, noDefault){
var dateFormat;
var dates;
var defaultDate;
var date;
var settings;
if(inst.input.val()===inst.lastVal){
return;
}
dateFormat=this._get(inst, 'dateFormat');
dates=inst.input ? inst.input.val():null;
defaultDate=this._getDefaultDate(inst);
date=defaultDate;
settings=this._getFormatConfig(inst);
inst.lastVal=dates;
try {
date=this.parseDate(dateFormat, dates, settings)||defaultDate;
} catch(event){
dates=noDefault ? '':dates;
}
inst.selectedDay=date.getDate();
inst.selectedMonth=date.getMonth();
inst.drawMonth=inst.selectedMonth;
inst.selectedYear=date.getFullYear();
inst.drawYear=inst.selectedYear;
inst.currentDay=dates ? date.getDate():0;
inst.currentMonth=dates ? date.getMonth():0;
inst.currentYear=dates ? date.getFullYear():0;
this._adjustInstDate(inst);
},
_getDefaultDate: function(inst){
return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, 'defaultDate'), new Date()));
},
_determineDate: function(inst, date, defaultDate){
var offsetNumeric=function(offset){
var sdate=new Date();
sdate.setDate(sdate.getDate() + offset);
return sdate;
},
offsetString=function(offset){
var sdate;
var year;
var month;
var day;
var pattern;
var matches;
try {
return $.tm_datepicker.parseDate($.tm_datepicker._get(inst, 'dateFormat'), offset, $.tm_datepicker._getFormatConfig(inst));
} catch(e){
}
sdate=(offset.toLowerCase().match(/^c/) ? $.tm_datepicker._getDate(inst):null)||new Date();
year=sdate.getFullYear();
month=sdate.getMonth();
day=sdate.getDate();
pattern=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
matches=pattern.exec(offset);
while(matches){
switch(matches[ 2 ]||'d'){
case 'd':
case 'D':
day +=parseInt(matches[ 1 ], 10);
break;
case 'w':
case 'W':
day +=parseInt(matches[ 1 ], 10) * 7;
break;
case 'm':
case 'M':
month +=parseInt(matches[ 1 ], 10);
day=Math.min(day, $.tm_datepicker._getDaysInMonth(year, month));
break;
case 'y':
case 'Y':
year +=parseInt(matches[ 1 ], 10);
day=Math.min(day, $.tm_datepicker._getDaysInMonth(year, month));
break;
}
matches=pattern.exec(offset);
}
return new Date(year, month, day);
},
newDate=date===null||date==='' ? defaultDate:typeof date==='string' ? offsetString(date):typeof date==='number' ?(! Number.isFinite(date) ? defaultDate:offsetNumeric(date)):new Date(date.getTime());
newDate=newDate&&newDate.toString()==='Invalid Date' ? defaultDate:newDate;
if(newDate){
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
}
return this._daylightSavingAdjust(newDate);
},
_daylightSavingAdjust: function(date){
if(! date){
return null;
}
date.setHours(date.getHours() > 12 ? date.getHours() + 2:0);
return date;
},
_setDate: function(inst, date, noChange){
var clear = ! date,
origMonth=inst.selectedMonth,
origYear=inst.selectedYear,
newDate=this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
inst.currentDay=newDate.getDate();
inst.selectedDay=inst.currentDay;
inst.currentMonth=newDate.getMonth();
inst.drawMonth=inst.currentMonth;
inst.selectedMonth=inst.currentMonth;
inst.currentYear=newDate.getFullYear();
inst.drawYear=inst.currentYear;
inst.selectedYear=inst.currentYear;
if(( origMonth!==inst.selectedMonth||origYear!==inst.selectedYear)&&! noChange){
this._notifyChange(inst);
}
this._adjustInstDate(inst);
if(inst.input){
inst.input.val(clear ? '':this._formatDate(inst));
}},
_getDate: function(inst){
var startDate = ! inst.currentYear||(inst.input&&inst.input.val()==='') ? null:this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
return startDate;
},
_attachHandlers: function(inst){
var stepMonths=this._get(inst, 'stepMonths'),
id='#' + inst.id.replace(/\\\\/g, '\\');
inst.dpDiv.find('[data-handler]').map(function(){
var handler={
prevM: function(){
$.tm_datepicker._adjustDate(id, -1, 'M');
},
nextM: function(){
$.tm_datepicker._adjustDate(id, +1, 'M');
},
prevY: function(){
$.tm_datepicker._adjustDate(id, -1, 'Y');
},
nextY: function(){
$.tm_datepicker._adjustDate(id, +1, 'Y');
},
prev: function(){
$.tm_datepicker._adjustDate(id, -stepMonths, 'M');
},
next: function(){
$.tm_datepicker._adjustDate(id, +stepMonths, 'M');
},
hide: function(){
$.tm_datepicker._hideDatepicker();
},
today: function(){
},
selectDay: function(){
$.tm_datepicker._selectDay(id, +this.getAttribute('data-month'), +this.getAttribute('data-year'), this);
return false;
},
selectMonth: function(){
$.tm_datepicker._selectMonthYear(id, this, 'M');
return false;
},
selectYear: function(){
$.tm_datepicker._selectMonthYear(id, this, 'Y');
return false;
}};
$(this).on(this.getAttribute('data-event'), handler[ this.getAttribute('data-handler') ]);
return null;
});
},
_tm_canAdjustMonth: function(inst, offset, curYear, curMonth){
var date=this._daylightSavingAdjust(new Date(curYear, curMonth + offset, 1));
if(offset < 0){
date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
}
return this._isInRange(inst, date);
},
_generateHTML: function(inst){
var maxDraw,
prevText,
prev,
nextText,
next,
currentText,
gotoDate,
firstDay,
showWeek,
dayNames,
dayNamesMin,
monthNames,
beforeShowDay,
showOtherMonths,
selectOtherMonths,
defaultDate,
html,
dow,
row,
group,
col,
selectedDate,
cornerClass,
calender,
thead,
day,
daysInMonth,
leadDays,
curRows,
numRows,
printDate,
dRow,
tbody,
daySettings,
otherMonth,
unselectable,
tempDate=new Date(),
today=this._daylightSavingAdjust(new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())),
isRTL=this._get(inst, 'isRTL'),
showButtonPanel=this._get(inst, 'showButtonPanel'),
hideIfNoPrevNext=this._get(inst, 'hideIfNoPrevNext'),
navigationAsDateFormat=this._get(inst, 'navigationAsDateFormat'),
numMonths=this._getNumberOfMonths(inst),
showCurrentAtPos=this._get(inst, 'showCurrentAtPos'),
stepMonths=this._get(inst, 'stepMonths'),
isMultiMonth=numMonths[ 0 ]!==1||numMonths[ 1 ]!==1,
currentDate=this._daylightSavingAdjust(! inst.currentDay ? new Date(9999, 9, 9):new Date(inst.currentYear, inst.currentMonth, inst.currentDay)),
minDate=this._getMinMaxDate(inst, 'min'),
maxDate=this._getMinMaxDate(inst, 'max'),
drawMonth=inst.drawMonth - showCurrentAtPos,
drawYear=inst.drawYear,
tm_month,
tm_year,
tm_prev_arrow_m,
tm_next_arrow_m,
tm_prev_arrow_y,
tm_next_arrow_y,
tm_controls,
tm_buttonPanel;
var can_adjust_1;
var can_adjust_2;
var can_adjust_3;
var can_adjust_4;
if(drawMonth < 0){
drawMonth +=12;
drawYear -=1;
}
if(maxDate){
maxDraw=this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() -(numMonths[ 0 ] * numMonths[ 1 ]) + 1, maxDate.getDate()));
maxDraw=minDate&&maxDraw < minDate ? minDate:maxDraw;
while(this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw){
drawMonth -=1;
if(drawMonth < 0){
drawMonth=11;
drawYear -=1;
}}
}
inst.drawMonth=drawMonth;
inst.drawYear=drawYear;
prevText=this._get(inst, 'prevText');
prevText = ! navigationAsDateFormat ? prevText:this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst));
prev=this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? "<a class='ui-tm-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" + " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" +(isRTL ? 'e':'w') + "'>" + prevText + '</span></a>':hideIfNoPrevNext ? '':"<a class='ui-tm-datepicker-prev ui-corner-all ui-state-disabled' title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" +(isRTL ? 'e':'w') + "'>" + prevText + '</span></a>';
nextText=this._get(inst, 'nextText');
nextText = ! navigationAsDateFormat ? nextText:this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst));
next=this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? "<a class='ui-tm-datepicker-next ui-corner-all' data-handler='next' data-event='click'" + " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" +(isRTL ? 'w':'e') + "'>" + nextText + '</span></a>':hideIfNoPrevNext ? '':"<a class='ui-tm-datepicker-next ui-corner-all ui-state-disabled' title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" +(isRTL ? 'w':'e') + "'>" + nextText + '</span></a>';
currentText=this._get(inst, 'currentText');
gotoDate=this._get(inst, 'gotoCurrent')&&inst.currentDay ? currentDate:today;
currentText = ! navigationAsDateFormat ? currentText:this.formatDate(currentText, gotoDate, this._getFormatConfig(inst));
tm_controls = ! inst.inline ? "<div class='tm-ui-dp-btn-wrap tm-ui-dp-close'><div role='button' class='tm-ui-dp-btn ui-tm-datepicker-close' data-handler='hide' data-event='click'>" + this._get(inst, 'closeText') + '</div></div>':'';
tm_buttonPanel=showButtonPanel ? "<div class='tm-ui-dp-buttonpane'>" +(isRTL ? tm_controls:'') +(this._isInRange(inst, gotoDate) ? "<div class='tm-ui-dp-btn-wrap tm-ui-dp-current'><div role='button' class='tm-ui-dp-btn ui-tm-datepicker-current' data-handler='today' data-event='click'" + '>' + currentText + '</div></div>':'') +(isRTL ? '':tm_controls) + '</div>':'';
firstDay=parseInt(this._get(inst, 'firstDay'), 10);
firstDay=isNaN(firstDay) ? 0:firstDay;
showWeek=this._get(inst, 'showWeek');
dayNames=this._get(inst, 'dayNames');
dayNamesMin=this._get(inst, 'dayNamesMin');
monthNames=this._get(inst, 'monthNames');
beforeShowDay=this._get(inst, 'beforeShowDay');
showOtherMonths=this._get(inst, 'showOtherMonths');
selectOtherMonths=this._get(inst, 'selectOtherMonths');
defaultDate=this._getDefaultDate(inst);
html='';
can_adjust_1=this._tm_canAdjustMonth(inst, -1, drawYear, drawMonth);
can_adjust_2=this._tm_canAdjustMonth(inst, +1, drawYear, drawMonth);
can_adjust_3=this._tm_canAdjustMonth(inst, -12, drawYear, drawMonth);
can_adjust_4=this._tm_canAdjustMonth(inst, +12, drawYear, drawMonth);
tm_prev_arrow_m='<div class="tm-ui-dp-button-prev tm-ui-dp-button">' + '<div ' +(can_adjust_1 ? 'data-handler="prevM" data-event="click" ':'') + 'aria-label="' + prevText + '" class="' +(can_adjust_1 ? '':'tm-ui-dp-button-disabled ') + 'tm-ui-dp-button-arrow tcfa tcfa-angle-left" tabindex="0" role="button"></div>' + '</div>';
tm_next_arrow_m='<div class="tm-ui-dp-button-next tm-ui-dp-button">' + '<div ' +(can_adjust_2 ? 'data-handler="nextM" data-event="click" ':'') + 'aria-label="' + nextText + '" class="' +(can_adjust_2 ? '':'tm-ui-dp-button-disabled ') + 'tm-ui-dp-button-arrow tcfa tcfa-angle-right" tabindex="0" role="button"></div>' + '</div>';
tm_prev_arrow_y='<div class="tm-ui-dp-button-prev tm-ui-dp-button">' + '<div ' +(can_adjust_3 ? 'data-handler="prevY" data-event="click" ':'') + 'aria-label="' + prevText + '" class="' +(can_adjust_3 ? '':'tm-ui-dp-button-disabled ') + 'tm-ui-dp-button-arrow tcfa tcfa-angle-left" tabindex="0" role="button"></div>' + '</div>';
tm_next_arrow_y='<div class="tm-ui-dp-button-next tm-ui-dp-button">' + '<div ' +(can_adjust_4 ? 'data-handler="nextY" data-event="click" ':'') + 'aria-label="' + nextText + '" class="' +(can_adjust_4 ? '':'tm-ui-dp-button-disabled ') + 'tm-ui-dp-button-arrow tcfa tcfa-angle-right" tabindex="0" role="button"></div>' + '</div>';
tm_month=hideIfNoPrevNext ? '':'<div class="tm-ui-dp-title-button">' +(isRTL ? tm_next_arrow_m:tm_prev_arrow_m) + '<span aria-label="' + monthNames[ drawMonth ] + '" role="button" class="tm-ui-dp-month">' + monthNames[ drawMonth ] + '</span>' +(isRTL ? tm_prev_arrow_m:tm_next_arrow_m) + '</div>';
tm_year=hideIfNoPrevNext ? '':'<div class="tm-ui-dp-title-button">' +(isRTL ? tm_next_arrow_y:tm_prev_arrow_y) + '<span class="tm-ui-dp-year" role="button" aria-label="' + drawYear + '">' + drawYear + '</span>' +(isRTL ? tm_prev_arrow_y:tm_next_arrow_y) + '</div>';
html +="<div class='tm-ui-dp-wrap'>" + "<div class='tm-ui-dp-overlay'></div>" + "<div class='tm-ui-dp'>" + "<div class='tm-ui-dp-container'>" + "<div class='tm-ui-dp-inner-container'>" + "<div class='tm-ui-dp-ui'>" + "<div class='tm-ui-dp-ui-inner'>" + "<div class='tm-ui-dp-main-wrap'>" + "<div class='tm-ui-dp-main'>";
for(row=0; row < numMonths[ 0 ]; row +=1){
group='';
this.maxRows=4;
for(col=0; col < numMonths[ 1 ]; col +=1){
selectedDate=this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
cornerClass=' ui-corner-all';
calender='';
if(isMultiMonth){
calender +="<div class='ui-tm-datepicker-group";
if(numMonths[ 1 ] > 1){
switch(col){
case 0:
calender +=' ui-tm-datepicker-group-first';
cornerClass=' ui-corner-' +(isRTL ? 'right':'left');
break;
case numMonths[ 1 ] - 1:
calender +=' ui-tm-datepicker-group-last';
cornerClass=' ui-corner-' +(isRTL ? 'left':'right');
break;
default:
calender +=' ui-tm-datepicker-group-middle';
cornerClass='';
break;
}}
calender +="'>";
}
calender +=
"<div class='tm-ui-dp-header ui-tm-datepicker-header ui-widget-header ui-helper-clearfix" +
cornerClass +
"'>" +
(/all|left/.test(cornerClass)&&row===0 ?(isRTL ? next:prev):'') +
(/all|right/.test(cornerClass)&&row===0 ?(isRTL ? prev:next):'') +
'<div class="ui-tm-datepicker-title tm-ui-dp-title">' +
(/all|left/.test(cornerClass)&&row===0 ?(isRTL ? tm_year + tm_month:tm_month + tm_year):'') +
'</div>' +
'</div>';
calender +="<div class='tm-ui-dp-main-content'>";
calender +="<div class='tm-ui-dp-main-header-wrap'><div class='tm-ui-dp-main-header'>";
calender +="<table class='ui-tm-datepicker-calendar'><tbody>" + '<tr>';
thead=showWeek ? "<th class='ui-tm-datepicker-week-col'>" + this._get(inst, 'weekHeader') + '</th>':'';
for(dow=0; dow < 7; dow +=1){
day=(dow + firstDay) % 7;
thead +="<th scope='col'" +(( dow + firstDay + 6) % 7 >=5 ? " class='ui-tm-datepicker-week-end'":'') + '>' + "<span title='" + dayNames[ day ] + "'>" + dayNamesMin[ day ] + '</span></th>';
}
calender +=thead + '</tr></tbody></table>';
calender +='</div></div>';
calender +="<div class='tm-ui-dp-main-table'>";
daysInMonth=this._getDaysInMonth(drawYear, drawMonth);
if(drawYear===inst.selectedYear&&drawMonth===inst.selectedMonth){
inst.selectedDay=Math.min(inst.selectedDay, daysInMonth);
}
leadDays=(this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
curRows=6;
numRows=isMultiMonth ?(this.maxRows > curRows ? this.maxRows:curRows):curRows;
this.maxRows=numRows;
printDate=this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
for(dRow=0; dRow < numRows; dRow +=1){
calender +="<div class='tm-ui-dp-main-row'>";
tbody = ! showWeek ? '':"<div class='ui-tm-datepicker-week-col'>" + this._get(inst, 'calculateWeek')(printDate) + '</div>';
for(dow=0; dow < 7; dow +=1){
daySettings=beforeShowDay ? beforeShowDay.apply(inst.input ? inst.input[ 0 ]:null, [ printDate ]):[ true, '' ];
otherMonth=printDate.getMonth()!==drawMonth;
unselectable=(otherMonth&&! selectOtherMonths)||! daySettings[ 0 ]||(minDate&&printDate < minDate)||(maxDate&&printDate > maxDate);
tbody +=
"<div class='tm-ui-dp-main-cell " +
(( dow + firstDay + 6) % 7 >=5 ? ' ui-tm-datepicker-week-end':'') +
(otherMonth ? ' ui-tm-datepicker-other-month':'') +
(( printDate.getTime()===selectedDate.getTime()&&drawMonth===inst.selectedMonth&&inst._keyEvent)||(defaultDate.getTime()===printDate.getTime()&&defaultDate.getTime()===selectedDate.getTime()) ? ' ' + this._dayOverClass:'') +
(unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled':'') +
(otherMonth&&! showOtherMonths ? '':' ' + daySettings[ 1 ] +(printDate.getTime()===currentDate.getTime() ? ' ' + this._currentClass:'') +(printDate.getTime()===today.getTime() ? ' ui-tm-datepicker-today':'')) +
"'" +
(( ! otherMonth||showOtherMonths)&&daySettings[ 2 ] ? " title='" + daySettings[ 2 ].replace(/'/g, '&#39;') + "'":'') +
(unselectable ? '':" data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") +
'>' +
"<div class='tm-ui-dp-main-cell-inner'>" +
"<div class='tm-ui-dp-main-cell-content'>" +
(otherMonth&&! showOtherMonths ? '&#xa0;':unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + '</span>':"<a class='ui-state-default" +(printDate.getTime()===today.getTime() ? ' ui-state-highlight':'') +(printDate.getTime()===currentDate.getTime() ? ' ui-state-active':'') +(otherMonth ? ' ui-priority-secondary':'') + "' href='#'>" + printDate.getDate() + '</a>') +
'</div></div>' +
'</div>';
printDate.setDate(printDate.getDate() + 1);
printDate=this._daylightSavingAdjust(printDate);
}
calender +=tbody + '</div>';
}
drawMonth +=1;
if(drawMonth > 11){
drawMonth=0;
drawYear +=1;
}
calender +='</div>';
calender +='</div>' +(isMultiMonth ? '</div>' +(numMonths[ 0 ] > 0&&col===numMonths[ 1 ] - 1 ? "<div class='ui-tm-datepicker-row-break'></div>":''):'');
group +=calender;
}
html +=group;
}
html +='</div></div></div></div></div>';
html +=tm_buttonPanel;
html +='</div></div></div>';
inst._keyEvent=false;
return html;
},
_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort){
var inMinYear,
inMaxYear,
month,
years,
thisYear,
determineYear,
year,
endYear,
changeMonth=this._get(inst, 'changeMonth'),
changeYear=this._get(inst, 'changeYear'),
showMonthAfterYear=this._get(inst, 'showMonthAfterYear'),
html="<div class='ui-tm-datepicker-title'>",
monthHtml='';
if(secondary||! changeMonth){
monthHtml +="<span class='ui-tm-datepicker-month'>" + monthNames[ drawMonth ] + '</span>';
}else{
inMinYear=minDate&&minDate.getFullYear()===drawYear;
inMaxYear=maxDate&&maxDate.getFullYear()===drawYear;
monthHtml +="<select class='ui-tm-datepicker-month' data-handler='selectMonth' data-event='change'>";
for(month=0; month < 12; month +=1){
if(( ! inMinYear||month >=minDate.getMonth())&&(! inMaxYear||month <=maxDate.getMonth())){
monthHtml +="<option value='" + month + "'" +(month===drawMonth ? " selected='selected'":'') + '>' + monthNamesShort[ month ] + '</option>';
}}
monthHtml +='</select>';
}
if(! showMonthAfterYear){
html +=monthHtml +(secondary||!(changeMonth&&changeYear) ? '&#xa0;':'');
}
if(! inst.yearshtml){
inst.yearshtml='';
if(secondary||! changeYear){
html +="<span class='ui-tm-datepicker-year'>" + drawYear + '</span>';
}else{
years=this._get(inst, 'yearRange').split(':');
thisYear=new Date().getFullYear();
determineYear=function(value){
var syear=value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10):value.match(/[+-].*/) ? thisYear + parseInt(value, 10):parseInt(value, 10);
return isNaN(syear) ? thisYear:syear;
};
year=determineYear(years[ 0 ]);
endYear=Math.max(year, determineYear(years[ 1 ]||''));
year=minDate ? Math.max(year, minDate.getFullYear()):year;
endYear=maxDate ? Math.min(endYear, maxDate.getFullYear()):endYear;
inst.yearshtml +="<select class='ui-tm-datepicker-year' data-handler='selectYear' data-event='change'>";
for(; year <=endYear; year +=1){
inst.yearshtml +="<option value='" + year + "'" +(year===drawYear ? " selected='selected'":'') + '>' + year + '</option>';
}
inst.yearshtml +='</select>';
html +=inst.yearshtml;
inst.yearshtml=null;
}}
html +=this._get(inst, 'yearSuffix');
if(showMonthAfterYear){
html +=(secondary||!(changeMonth&&changeYear) ? '&#xa0;':'') + monthHtml;
}
html +='</div>';
return html;
},
_adjustInstDate: function(inst, offset, period){
var year=inst.selectedYear +(period==='Y' ? offset:0),
month=inst.selectedMonth +(period==='M' ? offset:0),
day=Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +(period==='D' ? offset:0),
date=this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));
inst.selectedDay=date.getDate();
inst.selectedMonth=date.getMonth();
inst.drawMonth=inst.selectedMonth;
inst.selectedYear=date.getFullYear();
inst.drawYear=inst.selectedYear;
if(period==='M'||period==='Y'){
this._notifyChange(inst);
}},
_restrictMinMax: function(inst, date){
var minDate=this._getMinMaxDate(inst, 'min'),
maxDate=this._getMinMaxDate(inst, 'max'),
newDate=minDate&&date < minDate ? minDate:date;
return maxDate&&newDate > maxDate ? maxDate:newDate;
},
_notifyChange: function(inst){
var onChange=this._get(inst, 'onChangeMonthYear');
if(onChange){
onChange.apply(inst.input ? inst.input[ 0 ]:null, [ inst.selectedYear, inst.selectedMonth + 1, inst ]);
}},
_getNumberOfMonths: function(inst){
var numMonths=this._get(inst, 'numberOfMonths');
return numMonths===null ? [ 1, 1 ]:typeof numMonths==='number' ? [ 1, numMonths ]:numMonths;
},
_getMinMaxDate: function(inst, minMax){
return this._determineDate(inst, this._get(inst, minMax + 'Date'), null);
},
_getDaysInMonth: function(year, month){
return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
},
_getFirstDayOfMonth: function(year, month){
return new Date(year, month, 1).getDay();
},
_canAdjustMonth: function(inst, offset, curYear, curMonth){
var numMonths=this._getNumberOfMonths(inst),
date=this._daylightSavingAdjust(new Date(curYear, curMonth +(offset < 0 ? offset:numMonths[ 0 ] * numMonths[ 1 ]), 1));
if(offset < 0){
date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
}
return this._isInRange(inst, date);
},
_isInRange: function(inst, date){
var yearSplit,
currentYear,
minDate=this._getMinMaxDate(inst, 'min'),
maxDate=this._getMinMaxDate(inst, 'max'),
minYear=null,
maxYear=null,
years=this._get(inst, 'yearRange');
if(years){
yearSplit=years.split(':');
currentYear=new Date().getFullYear();
minYear=parseInt(yearSplit[ 0 ], 10);
maxYear=parseInt(yearSplit[ 1 ], 10);
if(yearSplit[ 0 ].match(/[+-].*/)){
minYear +=currentYear;
}
if(yearSplit[ 1 ].match(/[+-].*/)){
maxYear +=currentYear;
}}
return(! minDate||date.getTime() >=minDate.getTime())&&(! maxDate||date.getTime() <=maxDate.getTime())&&(! minYear||date.getFullYear() >=minYear)&&(! maxYear||date.getFullYear() <=maxYear);
},
_getFormatConfig: function(inst){
var shortYearCutoff=this._get(inst, 'shortYearCutoff');
shortYearCutoff=typeof shortYearCutoff!=='string' ? shortYearCutoff:(new Date().getFullYear() % 100) + parseInt(shortYearCutoff, 10);
return {
shortYearCutoff: shortYearCutoff,
dayNamesShort: this._get(inst, 'dayNamesShort'),
dayNames: this._get(inst, 'dayNames'),
monthNamesShort: this._get(inst, 'monthNamesShort'),
monthNames: this._get(inst, 'monthNames')
};},
_formatDate: function(inst, day, month, year){
var date;
if(! day){
inst.currentDay=inst.selectedDay;
inst.currentMonth=inst.selectedMonth;
inst.currentYear=inst.selectedYear;
}
date=day ?(typeof day==='object' ? day:this._daylightSavingAdjust(new Date(year, month, day))):this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
}});
$.fn.tm_datepicker=function(options){
var otherArgs;
if(! this.length){
return this;
}
if(! $.tm_datepicker.initialized){
$(document).on('mousedown', $.tm_datepicker._checkExternalClick);
$.tm_datepicker.initialized=true;
}
if($('#' + $.tm_datepicker._mainDivId).length===0){
$('body').append($.tm_datepicker.dpDiv);
}
otherArgs=Array.prototype.slice.call(arguments, 1);
if(typeof options==='string'&&(options==='isDisabled'||options==='getDate'||options==='widget')){
return $.tm_datepicker[ '_' + options + 'Datepicker' ].apply($.tm_datepicker, [ this[ 0 ] ].concat(otherArgs));
}
if(options==='option'&&arguments.length===2&&typeof arguments[ 1 ]==='string'){
return $.tm_datepicker[ '_' + options + 'Datepicker' ].apply($.tm_datepicker, [ this[ 0 ] ].concat(otherArgs));
}
return this.each(function(){
if(typeof options==='string'){
$.tm_datepicker[ '_' + options + 'Datepicker' ].apply($.tm_datepicker, [ this ].concat(otherArgs));
}else{
$.tm_datepicker._attachDatepicker(this, options);
}});
};
$.tm_datepicker=new Datepicker();
$.tm_datepicker.initialized=false;
$.tm_datepicker.uuid=new Date().getTime();
$.tm_datepicker.version='1.11.4';
}));
(function(factory){
'use strict';
if(typeof window.define==='function'&&window.define.amd){
window.define([ 'jquery', 'jquery-ui' ], factory);
}else{
factory(window.jQuery);
}}(function($){
'use strict';
var extendRemove=function(target, props){
var name;
$.extend(target, props);
for(name in props){
if(props[ name ]===null||props[ name ]===undefined){
target[ name ]=props[ name ];
}}
return target;
};
var isEmptyObject=function(obj){
var prop;
for(prop in obj){
if(Object.prototype.hasOwnProperty.call(obj, prop)){
return false;
}}
return true;
};
var detectSupport=function(timeFormat){
var tf=timeFormat.replace(/'.*?'/g, '').toLowerCase(),
isIn=function(f, t){
return f.indexOf(t)!==-1 ? true:false;
};
return {
hour: isIn(tf, 'h'),
minute: isIn(tf, 'm'),
second: isIn(tf, 's'),
millisec: isIn(tf, 'l'),
microsec: isIn(tf, 'c'),
timezone: isIn(tf, 'z'),
ampm: isIn(tf, 't')&&isIn(timeFormat, 'h'),
iso8601: isIn(timeFormat, 'Z')
};};
var convert24to12=function(hour){
hour %=12;
if(hour===0){
hour=12;
}
return String(hour);
};
var computeEffectiveSetting=function(settings, property){
return settings&&settings[ property ] ? settings[ property ]:$.tm_timepicker._defaults[ property ];
};
var splitDateTime=function(dateTimeString, timeSettings){
var separator=computeEffectiveSetting(timeSettings, 'separator'),
format=computeEffectiveSetting(timeSettings, 'timeFormat'),
timeParts=format.split(separator),
timePartsLen=timeParts.length,
allParts=dateTimeString.split(separator),
allPartsLen=allParts.length;
if(allPartsLen > 1){
return {
dateString: allParts.splice(0, allPartsLen - timePartsLen).join(separator),
timeString: allParts.splice(0, timePartsLen).join(separator)
};}
return {
dateString: dateTimeString,
timeString: ''
};};
var parseDateTimeInternal=function(dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings){
var date, parts, parsedTime;
parts=splitDateTime(dateTimeString, timeSettings);
date=$.tm_datepicker._base_parseDate(dateFormat, parts.dateString, dateSettings);
if(parts.timeString===''){
return {
date: date
};}
parsedTime=$.tm_datepicker.parseTime(timeFormat, parts.timeString, timeSettings);
if(! parsedTime){
throw 'Wrong time format';
}
return {
date: date,
timeObj: parsedTime
};};
var selectLocalTimezone=function(tp_inst, date){
var now;
if(tp_inst&&tp_inst.timezone_select){
now=date||new Date();
tp_inst.timezone_select.val(-now.getTimezoneOffset());
}};
var Timepicker=function(){
this.regional=[];
this.regional[ '' ]={
currentText: 'Now',
closeText: 'Done',
amNames: [ 'AM', 'A' ],
pmNames: [ 'PM', 'P' ],
timeFormat: 'HH:mm',
timeSuffix: '',
timeOnlyTitle: 'Choose Time',
timeText: 'Time',
hourText: 'Hour',
minuteText: 'Minute',
secondText: 'Second',
millisecText: 'Millisecond',
microsecText: 'Microsecond',
timezoneText: 'Time Zone',
isRTL: false
};
this._defaults={
showButtonPanel: true,
timeOnly: false,
timeOnlyShowDate: false,
showHour: null,
showMinute: null,
showSecond: null,
showMillisec: null,
showMicrosec: null,
showTimezone: null,
showTime: true,
stepHour: 1,
stepMinute: 1,
stepSecond: 1,
stepMillisec: 1,
stepMicrosec: 1,
hour: 0,
minute: 0,
second: 0,
millisec: 0,
microsec: 0,
timezone: null,
hourMin: 0,
minuteMin: 0,
secondMin: 0,
millisecMin: 0,
microsecMin: 0,
hourMax: 23,
minuteMax: 59,
secondMax: 59,
millisecMax: 999,
microsecMax: 999,
minDateTime: null,
maxDateTime: null,
maxTime: null,
minTime: null,
onSelect: null,
hourGrid: 0,
minuteGrid: 0,
secondGrid: 0,
millisecGrid: 0,
microsecGrid: 0,
alwaysSetTime: true,
separator: ' ',
altFieldTimeOnly: true,
altTimeFormat: null,
altSeparator: null,
altTimeSuffix: null,
altRedirectFocus: true,
pickerTimeFormat: null,
pickerTimeSuffix: null,
showTimepicker: true,
timezoneList: null,
addSliderAccess: false,
sliderAccessArgs: null,
controlType: 'slider',
oneLine: false,
defaultValue: null,
parse: 'strict',
afterInject: null
};
$.extend(this._defaults, this.regional[ '' ]);
};
$.ui.tm_timepicker=$.ui.tm_timepicker||{};
if($.ui.tm_timepicker.version){
return;
}
$.extend($.ui, {
tm_timepicker: {
version: '1.6.3'
}});
$.extend(Timepicker.prototype, {
$input: null,
$altInput: null,
$timeObj: null,
inst: null,
hour_slider: null,
minute_slider: null,
second_slider: null,
millisec_slider: null,
microsec_slider: null,
timezone_select: null,
maxTime: null,
minTime: null,
hour: 0,
minute: 0,
second: 0,
millisec: 0,
microsec: 0,
timezone: null,
hourMinOriginal: null,
minuteMinOriginal: null,
secondMinOriginal: null,
millisecMinOriginal: null,
microsecMinOriginal: null,
hourMaxOriginal: null,
minuteMaxOriginal: null,
secondMaxOriginal: null,
millisecMaxOriginal: null,
microsecMaxOriginal: null,
ampm: '',
formattedDate: '',
formattedTime: '',
formattedDateTime: '',
timezoneList: null,
units: [ 'hour', 'minute', 'second', 'millisec', 'microsec' ],
support: {},
control: null,
setDefaults: function(settings){
extendRemove(this._defaults, settings||{});
return this;
},
_newInst: function($input, opts){
var tp_inst=new Timepicker(),
inlineSettings={},
fns={},
overrides,
i;
var attrName;
var attrValue;
var timezoneList;
var tzl;
var tzi=0;
var tzv=null;
for(attrName in this._defaults){
if(Object.prototype.hasOwnProperty.call(this._defaults, attrName)){
attrValue=$input.attr('data-' + attrName);
if(attrValue){
inlineSettings[ attrName ]=attrValue;
}}
}
overrides={
beforeShow: function(input, dp_inst){
if(typeof tp_inst._defaults.evnts.beforeShow==='function'){
return tp_inst._defaults.evnts.beforeShow.call($input[ 0 ], input, dp_inst, tp_inst);
}},
onChangeMonthYear: function(year, month, dp_inst){
if(typeof tp_inst._defaults.evnts.onChangeMonthYear==='function'){
tp_inst._defaults.evnts.onChangeMonthYear.call($input[ 0 ], year, month, dp_inst, tp_inst);
}},
onClose: function(dateText, dp_inst){
if(tp_inst.timeDefined===true&&$input.val()!==''){
tp_inst._updateDateTime(dp_inst);
}
if(typeof tp_inst._defaults.evnts.onClose==='function'){
tp_inst._defaults.evnts.onClose.call($input[ 0 ], dateText, dp_inst, tp_inst);
}}
};
for(i in overrides){
if(Object.prototype.hasOwnProperty.call(overrides, i)){
fns[ i ]=opts[ i ]||this._defaults[ i ]||null;
}}
tp_inst._defaults=$.extend({}, this._defaults, inlineSettings, opts, overrides, {
evnts: fns,
tm_timepicker: tp_inst
});
tp_inst.amNames=$.map(tp_inst._defaults.amNames, function(val){
return val.toUpperCase();
});
tp_inst.pmNames=$.map(tp_inst._defaults.pmNames, function(val){
return val.toUpperCase();
});
tp_inst.support=detectSupport(tp_inst._defaults.timeFormat +(tp_inst._defaults.pickerTimeFormat ? tp_inst._defaults.pickerTimeFormat:'') +(tp_inst._defaults.altTimeFormat ? tp_inst._defaults.altTimeFormat:''));
if(typeof tp_inst._defaults.controlType==='string'){
if(tp_inst._defaults.controlType==='slider'&&typeof $.ui.slider==='undefined'){
tp_inst._defaults.controlType='select';
}
tp_inst.control=tp_inst._controls[ tp_inst._defaults.controlType ];
}else{
tp_inst.control=tp_inst._defaults.controlType;
}
timezoneList=[ -720, -660, -600, -570, -540, -480, -420, -360, -300, -270, -240, -210, -180, -120, -60, 0, 60, 120, 180, 210, 240, 270, 300, 330, 345, 360, 390, 420, 480, 525, 540, 570, 600, 630, 660, 690, 720, 765, 780, 840 ];
if(tp_inst._defaults.timezoneList!==null){
timezoneList=tp_inst._defaults.timezoneList;
}
tzl=timezoneList.length;
if(tzl > 0&&typeof timezoneList[ 0 ]!=='object'){
for(; tzi < tzl; tzi +=1){
tzv=timezoneList[ tzi ];
timezoneList[ tzi ]={
value: tzv,
label: $.tm_timepicker.timezoneOffsetString(tzv, tp_inst.support.iso8601)
};}}
tp_inst._defaults.timezoneList=timezoneList;
tp_inst.timezone=tp_inst._defaults.timezone!==null ? $.tm_timepicker.timezoneOffsetNumber(tp_inst._defaults.timezone):new Date().getTimezoneOffset() * -1;
tp_inst.hour=tp_inst._defaults.hour < tp_inst._defaults.hourMin ? tp_inst._defaults.hourMin:tp_inst._defaults.hour > tp_inst._defaults.hourMax ? tp_inst._defaults.hourMax:tp_inst._defaults.hour;
tp_inst.minute=tp_inst._defaults.minute < tp_inst._defaults.minuteMin ? tp_inst._defaults.minuteMin:tp_inst._defaults.minute > tp_inst._defaults.minuteMax ? tp_inst._defaults.minuteMax:tp_inst._defaults.minute;
tp_inst.second=tp_inst._defaults.second < tp_inst._defaults.secondMin ? tp_inst._defaults.secondMin:tp_inst._defaults.second > tp_inst._defaults.secondMax ? tp_inst._defaults.secondMax:tp_inst._defaults.second;
tp_inst.millisec =
tp_inst._defaults.millisec < tp_inst._defaults.millisecMin ? tp_inst._defaults.millisecMin:tp_inst._defaults.millisec > tp_inst._defaults.millisecMax ? tp_inst._defaults.millisecMax:tp_inst._defaults.millisec;
tp_inst.microsec =
tp_inst._defaults.microsec < tp_inst._defaults.microsecMin ? tp_inst._defaults.microsecMin:tp_inst._defaults.microsec > tp_inst._defaults.microsecMax ? tp_inst._defaults.microsecMax:tp_inst._defaults.microsec;
tp_inst.ampm='';
tp_inst.$input=$input;
if(tp_inst._defaults.altField){
tp_inst.$altInput=$(tp_inst._defaults.altField);
if(tp_inst._defaults.altRedirectFocus===true){
tp_inst.$altInput
.css({
cursor: 'pointer'
})
.on('focus', function(){
$input.trigger('focus');
});
}}
if(tp_inst._defaults.minDate===0||tp_inst._defaults.minDateTime===0){
tp_inst._defaults.minDate=new Date();
}
if(tp_inst._defaults.maxDate===0||tp_inst._defaults.maxDateTime===0){
tp_inst._defaults.maxDate=new Date();
}
if(tp_inst._defaults.minDate!==undefined&&tp_inst._defaults.minDate instanceof Date){
tp_inst._defaults.minDateTime=new Date(tp_inst._defaults.minDate.getTime());
}
if(tp_inst._defaults.minDateTime!==undefined&&tp_inst._defaults.minDateTime instanceof Date){
tp_inst._defaults.minDate=new Date(tp_inst._defaults.minDateTime.getTime());
}
if(tp_inst._defaults.maxDate!==undefined&&tp_inst._defaults.maxDate instanceof Date){
tp_inst._defaults.maxDateTime=new Date(tp_inst._defaults.maxDate.getTime());
}
if(tp_inst._defaults.maxDateTime!==undefined&&tp_inst._defaults.maxDateTime instanceof Date){
tp_inst._defaults.maxDate=new Date(tp_inst._defaults.maxDateTime.getTime());
}
tp_inst.$input.on('focus', function(){
tp_inst._onFocus();
});
tp_inst.$input.next('.ui-tm-timepicker-trigger').on('click', function(){
tp_inst._onFocus();
return false;
});
return tp_inst;
},
_addTimePicker: function(dp_inst){
var currDT=$.epoAPI.util.trim(this.$altInput&&this._defaults.altFieldTimeOnly ? this.$input.val() + ' ' + this.$altInput.val():this.$input.val());
this.timeDefined=this._parseTime(currDT);
this._limitMinMaxDateTime(dp_inst, false);
this._injectTimePicker();
this._afterInject();
},
_parseTime: function(timeString, withDate){
var dp_dateFormat;
var parseRes;
var timeObj;
if(! this.inst){
this.inst=$.tm_datepicker._getInst(this.$input[ 0 ]);
}
if(withDate||! this._defaults.timeOnly){
dp_dateFormat=$.tm_datepicker._get(this.inst, 'dateFormat');
try {
parseRes=parseDateTimeInternal(dp_dateFormat, this._defaults.timeFormat, timeString, $.tm_datepicker._getFormatConfig(this.inst), this._defaults);
if(! parseRes.timeObj){
return false;
}
$.extend(this, parseRes.timeObj);
} catch(err){
$.tm_timepicker.log('Error parsing the date/time string: ' + err + '\ndate/time string=' + timeString + '\ntimeFormat=' + this._defaults.timeFormat + '\ndateFormat=' + dp_dateFormat);
return false;
}
return true;
}
timeObj=$.tm_datepicker.parseTime(this._defaults.timeFormat, timeString, this._defaults);
if(! timeObj){
return false;
}
$.extend(this, timeObj);
return true;
},
_afterInject: function(){
var o=this.inst.settings;
if(typeof o.afterInject==='function'){
o.afterInject.call(this);
}},
_ui_tpicker_onclick: function(event){
var $t=$(event.target),
h=$t.html(),
n=parseInt(h.replace(/[^0-9]/g), 10),
ap=h.replace(/[^apm]/gi),
f=$t.data('for');
if(f==='hour'){
if(ap.indexOf('p')!==-1&&n < 12){
n +=12;
}else if(ap.indexOf('a')!==-1&&n===12){
n=0;
}}
event.data.tp_inst.control.value(event.data.tp_inst, event.data.tp_inst[ f + '_slider' ], event.data.litem, n);
event.data.tp_inst._onTimeChange();
event.data.tp_inst._onSelectHandler();
},
_injectTimePicker: function(){
var $dp=this.inst.dpDiv,
o=this.inst.settings,
tp_inst=this,
litem='',
uitem='',
show=null,
max={},
gridSize={},
size=null,
i=0,
l=0;
var noDisplay;
var html;
var h;
var tmph;
var m;
var showTz;
var $tp;
var local_timezone;
var $buttonPanel;
var timeDefined;
var sliderAccessArgs;
var rtl;
if($dp.find('div.ui-tm-timepicker-div').length===0&&o.showTimepicker){
noDisplay=' ui_tpicker_unit_hide';
html =
'<div class="ui-tm-timepicker-div' +
(o.isRTL ? ' ui-tm-timepicker-rtl':'') +
(o.oneLine&&o.controlType==='select' ? ' ui-tm-timepicker-oneLine':'') +
'"><dl>' +
'<dt class="ui_tpicker_time_label' +
(o.showTime ? '':noDisplay) +
'">' +
o.timeText +
'</dt>' +
'<dd class="ui_tpicker_time ' +
(o.showTime ? '':noDisplay) +
'"><input class="ui_tpicker_time_input" ' +
(o.timeInput ? '':'disabled') +
'></dd>';
for(i=0, l=this.units.length; i < l; i +=1){
litem=this.units[ i ];
uitem=litem.substring(0, 1).toUpperCase() + litem.substring(1);
show=o[ 'show' + uitem ]!==null ? o[ 'show' + uitem ]:this.support[ litem ];
max[ litem ]=parseInt(o[ litem + 'Max' ] -(( o[ litem + 'Max' ] - o[ litem + 'Min' ]) % o[ 'step' + uitem ]), 10);
gridSize[ litem ]=0;
html +=
'<dt class="ui_tpicker_' +
litem +
'_label' +
(show ? '':noDisplay) +
'">' +
o[ litem + 'Text' ] +
'</dt>' +
'<dd class="ui_tpicker_' +
litem +
(show ? '':noDisplay) +
'"><div class="ui_tpicker_' +
litem +
'_slider' +
(show ? '':noDisplay) +
'"></div>';
if(show&&o[ litem + 'Grid' ] > 0){
html +='<div><table class="ui-tpicker-grid-label"><tr>';
if(litem==='hour'){
for(h=o[ litem + 'Min' ]; h <=max[ litem ]; h +=parseInt(o[ litem + 'Grid' ], 10)){
gridSize[ litem ] +=1;
tmph=$.tm_datepicker.formatTime(this.support.ampm ? 'hht':'HH', { hour: h }, o);
html +='<td data-for="' + litem + '">' + tmph + '</td>';
}}else{
for(m=o[ litem + 'Min' ]; m <=max[ litem ]; m +=parseInt(o[ litem + 'Grid' ], 10)){
gridSize[ litem ] +=1;
html +='<td data-for="' + litem + '">' +(m < 10 ? '0':'') + m + '</td>';
}}
html +='</tr></table></div>';
}
html +='</dd>';
}
showTz=o.showTimezone!==null ? o.showTimezone:this.support.timezone;
html +='<dt class="ui_tpicker_timezone_label' +(showTz ? '':noDisplay) + '">' + o.timezoneText + '</dt>';
html +='<dd class="ui_tpicker_timezone' +(showTz ? '':noDisplay) + '"></dd>';
html +='</dl></div>';
$tp=$(html);
if(o.timeOnly===true){
$tp.prepend('<div class="tm-ui-widget-header">' + '<div class="tm-ui-tp-title">' + o.timeOnlyTitle + '</div>' + '</div>');
$dp.find('.tm-ui-dp-inner-container').hide();
}
for(i=0, l=tp_inst.units.length; i < l; i +=1){
litem=tp_inst.units[ i ];
uitem=litem.substring(0, 1).toUpperCase() + litem.substring(1);
show=o[ 'show' + uitem ]!==null ? o[ 'show' + uitem ]:this.support[ litem ];
tp_inst[ litem + '_slider' ]=tp_inst.control.create(tp_inst, $tp.find('.ui_tpicker_' + litem + '_slider'), litem, tp_inst[ litem ], o[ litem + 'Min' ], max[ litem ], o[ 'step' + uitem ]);
if(show&&o[ litem + 'Grid' ] > 0){
size=(100 * gridSize[ litem ] * o[ litem + 'Grid' ]) /(max[ litem ] - o[ litem + 'Min' ]);
$tp.find('.ui_tpicker_' + litem + ' table')
.css({
width: size + '%',
marginLeft: o.isRTL ? '0':(size /(-2 * gridSize[ litem ])) + '%',
marginRight: o.isRTL ?(size /(-2 * gridSize[ litem ])) + '%':'0',
borderCollapse: 'collapse'
})
.find('td')
.on('click', { that: this, tp_inst: tp_inst, litem: litem }, this._ui_tpicker_onclick)
.css({
cursor: 'pointer',
width:(100 / gridSize[ litem ]) + '%',
textAlign: 'center',
overflow: 'hidden'
});
}}
this.timezone_select=$tp.find('.ui_tpicker_timezone').append('<select></select>').find('select');
$.fn.append.apply(this.timezone_select,
$.map(o.timezoneList, function(val){
return $('<option />')
.val(typeof val==='object' ? val.value:val)
.text(typeof val==='object' ? val.label:val);
})
);
if(typeof this.timezone!=='undefined'&&this.timezone!==null&&this.timezone!==''){
local_timezone=new Date(this.inst.selectedYear, this.inst.selectedMonth, this.inst.selectedDay, 12).getTimezoneOffset() * -1;
if(local_timezone===this.timezone){
selectLocalTimezone(tp_inst);
}else{
this.timezone_select.val(this.timezone);
}}else if(typeof this.hour!=='undefined'&&this.hour!==null&&this.hour!==''){
this.timezone_select.val(o.timezone);
}else{
selectLocalTimezone(tp_inst);
}
this.timezone_select.on('change', function(){
tp_inst._onTimeChange();
tp_inst._onSelectHandler();
tp_inst._afterInject();
});
$buttonPanel=$dp.find('.tm-ui-dp-buttonpane');
if($buttonPanel.length){
$buttonPanel.before($tp);
}else{
$dp.append($tp);
}
this.$timeObj=$tp.find('.ui_tpicker_time_input');
this.$timeObj.on('change', function(){
var timeFormat=tp_inst.inst.settings.timeFormat;
var parsedTime=$.tm_datepicker.parseTime(timeFormat, this.value);
var update=new Date();
if(parsedTime){
update.setHours(parsedTime.hour);
update.setMinutes(parsedTime.minute);
update.setSeconds(parsedTime.second);
$.datepicker._setTime(tp_inst.inst, update);
}else{
this.value=tp_inst.formattedTime;
this.trigger('blur');
}});
if(this.inst!==null){
timeDefined=this.timeDefined;
this._onTimeChange();
this.timeDefined=timeDefined;
}
if(this._defaults.addSliderAccess){
sliderAccessArgs=this._defaults.sliderAccessArgs;
rtl=this._defaults.isRTL;
sliderAccessArgs.isRTL=rtl;
setTimeout(function(){
var sliderAccessWidth;
if($tp.find('.ui-slider-access').length===0){
$tp.find('.ui-slider:visible').sliderAccess(sliderAccessArgs);
sliderAccessWidth=$tp.find('.ui-slider-access:eq(0)').outerWidth(true);
if(sliderAccessWidth){
$tp.find('table:visible').each(function(){
var $g=$(this),
oldWidth=$g.outerWidth(),
oldMarginLeft=$g
.css(rtl ? 'marginRight':'marginLeft')
.toString()
.replace('%', ''),
newWidth=oldWidth - sliderAccessWidth,
newMarginLeft=(( oldMarginLeft * newWidth) / oldWidth) + '%',
css={ width: newWidth, marginRight: 0, marginLeft: 0 };
css[ rtl ? 'marginRight':'marginLeft' ]=newMarginLeft;
$g.css(css);
});
}}
}, 10);
}
tp_inst._limitMinMaxDateTime(this.inst, true);
}},
_limitMinMaxDateTime: function(dp_inst, adjustSliders){
var o=this._defaults,
dp_date=new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay);
var minDateTime;
var minDateTimeDate;
var maxDateTime;
var maxDateTimeDate;
var tempMinTime;
var tempMaxTime;
var hourMax;
var minMax;
var secMax;
var millisecMax;
var microsecMax;
if(! this._defaults.showTimepicker){
return;
}
if($.tm_datepicker._get(dp_inst, 'minDateTime')!==null&&$.tm_datepicker._get(dp_inst, 'minDateTime')!==undefined&&dp_date){
minDateTime=$.tm_datepicker._get(dp_inst, 'minDateTime');
minDateTimeDate=new Date(minDateTime.getFullYear(), minDateTime.getMonth(), minDateTime.getDate(), 0, 0, 0, 0);
if(this.hourMinOriginal===null||this.minuteMinOriginal===null||this.secondMinOriginal===null||this.millisecMinOriginal===null||this.microsecMinOriginal===null){
this.hourMinOriginal=o.hourMin;
this.minuteMinOriginal=o.minuteMin;
this.secondMinOriginal=o.secondMin;
this.millisecMinOriginal=o.millisecMin;
this.microsecMinOriginal=o.microsecMin;
}
if(dp_inst.settings.timeOnly||minDateTimeDate.getTime()===dp_date.getTime()){
this._defaults.hourMin=minDateTime.getHours();
if(this.hour <=this._defaults.hourMin){
this.hour=this._defaults.hourMin;
this._defaults.minuteMin=minDateTime.getMinutes();
if(this.minute <=this._defaults.minuteMin){
this.minute=this._defaults.minuteMin;
this._defaults.secondMin=minDateTime.getSeconds();
if(this.second <=this._defaults.secondMin){
this.second=this._defaults.secondMin;
this._defaults.millisecMin=minDateTime.getMilliseconds();
if(this.millisec <=this._defaults.millisecMin){
this.millisec=this._defaults.millisecMin;
this._defaults.microsecMin=minDateTime.getMicroseconds();
}else{
if(this.microsec < this._defaults.microsecMin){
this.microsec=this._defaults.microsecMin;
}
this._defaults.microsecMin=this.microsecMinOriginal;
}}else{
this._defaults.millisecMin=this.millisecMinOriginal;
this._defaults.microsecMin=this.microsecMinOriginal;
}}else{
this._defaults.secondMin=this.secondMinOriginal;
this._defaults.millisecMin=this.millisecMinOriginal;
this._defaults.microsecMin=this.microsecMinOriginal;
}}else{
this._defaults.minuteMin=this.minuteMinOriginal;
this._defaults.secondMin=this.secondMinOriginal;
this._defaults.millisecMin=this.millisecMinOriginal;
this._defaults.microsecMin=this.microsecMinOriginal;
}}else{
this._defaults.hourMin=this.hourMinOriginal;
this._defaults.minuteMin=this.minuteMinOriginal;
this._defaults.secondMin=this.secondMinOriginal;
this._defaults.millisecMin=this.millisecMinOriginal;
this._defaults.microsecMin=this.microsecMinOriginal;
}}
if($.tm_datepicker._get(dp_inst, 'maxDateTime')!==null&&$.tm_datepicker._get(dp_inst, 'maxDateTime')!==undefined&&dp_date){
maxDateTime=$.tm_datepicker._get(dp_inst, 'maxDateTime');
maxDateTimeDate=new Date(maxDateTime.getFullYear(), maxDateTime.getMonth(), maxDateTime.getDate(), 0, 0, 0, 0);
if(this.hourMaxOriginal===null||this.minuteMaxOriginal===null||this.secondMaxOriginal===null||this.millisecMaxOriginal===null){
this.hourMaxOriginal=o.hourMax;
this.minuteMaxOriginal=o.minuteMax;
this.secondMaxOriginal=o.secondMax;
this.millisecMaxOriginal=o.millisecMax;
this.microsecMaxOriginal=o.microsecMax;
}
if(dp_inst.settings.timeOnly||maxDateTimeDate.getTime()===dp_date.getTime()){
this._defaults.hourMax=maxDateTime.getHours();
if(this.hour >=this._defaults.hourMax){
this.hour=this._defaults.hourMax;
this._defaults.minuteMax=maxDateTime.getMinutes();
if(this.minute >=this._defaults.minuteMax){
this.minute=this._defaults.minuteMax;
this._defaults.secondMax=maxDateTime.getSeconds();
if(this.second >=this._defaults.secondMax){
this.second=this._defaults.secondMax;
this._defaults.millisecMax=maxDateTime.getMilliseconds();
if(this.millisec >=this._defaults.millisecMax){
this.millisec=this._defaults.millisecMax;
this._defaults.microsecMax=maxDateTime.getMicroseconds();
}else{
if(this.microsec > this._defaults.microsecMax){
this.microsec=this._defaults.microsecMax;
}
this._defaults.microsecMax=this.microsecMaxOriginal;
}}else{
this._defaults.millisecMax=this.millisecMaxOriginal;
this._defaults.microsecMax=this.microsecMaxOriginal;
}}else{
this._defaults.secondMax=this.secondMaxOriginal;
this._defaults.millisecMax=this.millisecMaxOriginal;
this._defaults.microsecMax=this.microsecMaxOriginal;
}}else{
this._defaults.minuteMax=this.minuteMaxOriginal;
this._defaults.secondMax=this.secondMaxOriginal;
this._defaults.millisecMax=this.millisecMaxOriginal;
this._defaults.microsecMax=this.microsecMaxOriginal;
}}else{
this._defaults.hourMax=this.hourMaxOriginal;
this._defaults.minuteMax=this.minuteMaxOriginal;
this._defaults.secondMax=this.secondMaxOriginal;
this._defaults.millisecMax=this.millisecMaxOriginal;
this._defaults.microsecMax=this.microsecMaxOriginal;
}}
if(dp_inst.settings.minTime!==null){
tempMinTime=new Date('01/01/1970 ' + dp_inst.settings.minTime);
if(parseFloat(dp_inst.settings.minTime).toString()===dp_inst.settings.minTime){
tempMinTime=new Date(Date.now() + parseFloat(dp_inst.settings.minTime));
}
if(this.hour < tempMinTime.getHours()){
this._defaults.hourMin=tempMinTime.getHours();
this.hour=this._defaults.hourMin;
this._defaults.minuteMin=tempMinTime.getMinutes();
this.minute=this._defaults.minuteMin;
}else if(this.hour===tempMinTime.getHours()&&this.minute < tempMinTime.getMinutes()){
this._defaults.minuteMin=tempMinTime.getMinutes();
this.minute=this._defaults.minuteMin;
}else if(this._defaults.hourMin < tempMinTime.getHours()){
this._defaults.hourMin=tempMinTime.getHours();
this._defaults.minuteMin=tempMinTime.getMinutes();
}else if(( this._defaults.hourMin===tempMinTime.getHours())===this.hour&&this._defaults.minuteMin < tempMinTime.getMinutes()){
this._defaults.minuteMin=tempMinTime.getMinutes();
}else{
this._defaults.minuteMin=0;
}}
if(dp_inst.settings.maxTime!==null){
tempMaxTime=new Date('01/01/1970 ' + dp_inst.settings.maxTime);
if(this.hour > tempMaxTime.getHours()){
this._defaults.hourMax=tempMaxTime.getHours();
this.hour=this._defaults.hourMax;
this._defaults.minuteMax=tempMaxTime.getMinutes();
this.minute=this._defaults.minuteMax;
}else if(this.hour===tempMaxTime.getHours()&&this.minute > tempMaxTime.getMinutes()){
this._defaults.minuteMax=tempMaxTime.getMinutes();
this.minute=this._defaults.minuteMax;
}else if(this._defaults.hourMax > tempMaxTime.getHours()){
this._defaults.hourMax=tempMaxTime.getHours();
this._defaults.minuteMax=tempMaxTime.getMinutes();
}else if(( this._defaults.hourMax===tempMaxTime.getHours())===this.hour&&this._defaults.minuteMax > tempMaxTime.getMinutes()){
this._defaults.minuteMax=tempMaxTime.getMinutes();
}else{
this._defaults.minuteMax=59;
}}
if(adjustSliders!==undefined&&adjustSliders===true){
hourMax=parseInt(this._defaults.hourMax -(( this._defaults.hourMax - this._defaults.hourMin) % this._defaults.stepHour), 10);
minMax=parseInt(this._defaults.minuteMax -(( this._defaults.minuteMax - this._defaults.minuteMin) % this._defaults.stepMinute), 10);
secMax=parseInt(this._defaults.secondMax -(( this._defaults.secondMax - this._defaults.secondMin) % this._defaults.stepSecond), 10);
millisecMax=parseInt(this._defaults.millisecMax -(( this._defaults.millisecMax - this._defaults.millisecMin) % this._defaults.stepMillisec), 10);
microsecMax=parseInt(this._defaults.microsecMax -(( this._defaults.microsecMax - this._defaults.microsecMin) % this._defaults.stepMicrosec), 10);
if(this.hour_slider){
this.control.options(this, this.hour_slider, 'hour', {
min: this._defaults.hourMin,
max: hourMax,
step: this._defaults.stepHour
});
this.control.value(this, this.hour_slider, 'hour', this.hour -(this.hour % this._defaults.stepHour));
}
if(this.minute_slider){
this.control.options(this, this.minute_slider, 'minute', {
min: this._defaults.minuteMin,
max: minMax,
step: this._defaults.stepMinute
});
this.control.value(this, this.minute_slider, 'minute', this.minute -(this.minute % this._defaults.stepMinute));
}
if(this.second_slider){
this.control.options(this, this.second_slider, 'second', {
min: this._defaults.secondMin,
max: secMax,
step: this._defaults.stepSecond
});
this.control.value(this, this.second_slider, 'second', this.second -(this.second % this._defaults.stepSecond));
}
if(this.millisec_slider){
this.control.options(this, this.millisec_slider, 'millisec', {
min: this._defaults.millisecMin,
max: millisecMax,
step: this._defaults.stepMillisec
});
this.control.value(this, this.millisec_slider, 'millisec', this.millisec -(this.millisec % this._defaults.stepMillisec));
}
if(this.microsec_slider){
this.control.options(this, this.microsec_slider, 'microsec', {
min: this._defaults.microsecMin,
max: microsecMax,
step: this._defaults.stepMicrosec
});
this.control.value(this, this.microsec_slider, 'microsec', this.microsec -(this.microsec % this._defaults.stepMicrosec));
}}
},
_onTimeChange: function(){
var hour=this.hour_slider ? this.control.value(this, this.hour_slider, 'hour'):false,
minute=this.minute_slider ? this.control.value(this, this.minute_slider, 'minute'):false,
second=this.second_slider ? this.control.value(this, this.second_slider, 'second'):false,
millisec=this.millisec_slider ? this.control.value(this, this.millisec_slider, 'millisec'):false,
microsec=this.microsec_slider ? this.control.value(this, this.microsec_slider, 'microsec'):false,
timezone=this.timezone_select ? this.timezone_select.val():false,
o=this._defaults,
pickerTimeFormat=o.pickerTimeFormat||o.timeFormat,
pickerTimeSuffix=o.pickerTimeSuffix||o.timeSuffix;
var ampm;
var hasChanged;
var sPos;
var ePos;
if(! this._defaults.showTimepicker){
return;
}
if(typeof hour==='object'){
hour=false;
}
if(typeof minute==='object'){
minute=false;
}
if(typeof second==='object'){
second=false;
}
if(typeof millisec==='object'){
millisec=false;
}
if(typeof microsec==='object'){
microsec=false;
}
if(typeof timezone==='object'){
timezone=false;
}
if(hour!==false){
hour=parseInt(hour, 10);
}
if(minute!==false){
minute=parseInt(minute, 10);
}
if(second!==false){
second=parseInt(second, 10);
}
if(millisec!==false){
millisec=parseInt(millisec, 10);
}
if(microsec!==false){
microsec=parseInt(microsec, 10);
}
if(timezone!==false){
timezone=timezone.toString();
}
ampm=o[ hour < 12 ? 'amNames':'pmNames' ][ 0 ];
hasChanged =
hour!==parseInt(this.hour, 10) ||
minute!==parseInt(this.minute, 10) ||
second!==parseInt(this.second, 10) ||
millisec!==parseInt(this.millisec, 10) ||
microsec!==parseInt(this.microsec, 10) ||
(this.ampm.length > 0&&(hour < 12)!==($.inArray(this.ampm.toUpperCase(), this.amNames)!==-1)) ||
(this.timezone!==null&&timezone!==this.timezone.toString());
if(hasChanged){
if(hour!==false){
this.hour=hour;
}
if(minute!==false){
this.minute=minute;
}
if(second!==false){
this.second=second;
}
if(millisec!==false){
this.millisec=millisec;
}
if(microsec!==false){
this.microsec=microsec;
}
if(timezone!==false){
this.timezone=timezone;
}
if(! this.inst){
this.inst=$.tm_datepicker._getInst(this.$input[ 0 ]);
}
this._limitMinMaxDateTime(this.inst, true);
}
if(this.support.ampm){
this.ampm=ampm;
}
this.formattedTime=$.tm_datepicker.formatTime(o.timeFormat, this, o);
if(this.$timeObj){
if(pickerTimeFormat===o.timeFormat){
this.$timeObj.val(this.formattedTime + pickerTimeSuffix);
}else{
this.$timeObj.val($.tm_datepicker.formatTime(pickerTimeFormat, this, o) + pickerTimeSuffix);
}
if(this.$timeObj[ 0 ].setSelectionRange){
sPos=this.$timeObj[ 0 ].selectionStart;
ePos=this.$timeObj[ 0 ].selectionEnd;
this.$timeObj[ 0 ].setSelectionRange(sPos, ePos);
}}
this.timeDefined=true;
if(hasChanged){
this._updateDateTime();
}},
_onSelectHandler: function(){
var onSelect=this._defaults.onSelect||this.inst.settings.onSelect;
var inputEl=this.$input ? this.$input[ 0 ]:null;
if(onSelect&&inputEl){
onSelect.apply(inputEl, [ this.formattedDateTime, this ]);
}},
_updateDateTime: function(dp_inst){
var dtTmp;
var dt;
var dateFmt;
var formatCfg;
var timeAvailable;
var formattedDateTime;
var altFormattedDateTime='';
var altSeparator;
var altTimeSuffix;
dp_inst=this.inst||dp_inst;
dtTmp=dp_inst.currentYear > 0 ? new Date(dp_inst.currentYear, dp_inst.currentMonth, dp_inst.currentDay):new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay);
dt=$.tm_datepicker._daylightSavingAdjust(dtTmp);
dateFmt=$.tm_datepicker._get(dp_inst, 'dateFormat');
formatCfg=$.tm_datepicker._getFormatConfig(dp_inst);
timeAvailable=dt!==null&&this.timeDefined;
this.formattedDate=$.tm_datepicker.formatDate(dateFmt, dt===null ? new Date():dt, formatCfg);
formattedDateTime=this.formattedDate;
if(dp_inst.lastVal===''){
dp_inst.currentYear=dp_inst.selectedYear;
dp_inst.currentMonth=dp_inst.selectedMonth;
dp_inst.currentDay=dp_inst.selectedDay;
}
if(this._defaults.timeOnly===true&&this._defaults.timeOnlyShowDate===false){
formattedDateTime=this.formattedTime;
}else if(( this._defaults.timeOnly!==true&&(this._defaults.alwaysSetTime||timeAvailable))||(this._defaults.timeOnly===true&&this._defaults.timeOnlyShowDate===true)){
formattedDateTime +=this._defaults.separator + this.formattedTime + this._defaults.timeSuffix;
}
this.formattedDateTime=formattedDateTime;
if(! this._defaults.showTimepicker){
this.$input.val(this.formattedDate);
}else if(this.$altInput&&this._defaults.timeOnly===false&&this._defaults.altFieldTimeOnly===true){
this.$altInput.val(this.formattedTime);
this.$input.val(this.formattedDate);
}else if(this.$altInput){
this.$input.val(formattedDateTime);
altFormattedDateTime='';
altSeparator=this._defaults.altSeparator!==null ? this._defaults.altSeparator:this._defaults.separator;
altTimeSuffix=this._defaults.altTimeSuffix!==null ? this._defaults.altTimeSuffix:this._defaults.timeSuffix;
if(! this._defaults.timeOnly){
if(this._defaults.altFormat){
altFormattedDateTime=$.tm_datepicker.formatDate(this._defaults.altFormat, dt===null ? new Date():dt, formatCfg);
}else{
altFormattedDateTime=this.formattedDate;
}
if(altFormattedDateTime){
altFormattedDateTime +=altSeparator;
}}
if(this._defaults.altTimeFormat!==null){
altFormattedDateTime +=$.tm_datepicker.formatTime(this._defaults.altTimeFormat, this, this._defaults) + altTimeSuffix;
}else{
altFormattedDateTime +=this.formattedTime + altTimeSuffix;
}
this.$altInput.val(altFormattedDateTime);
}else{
this.$input.val(formattedDateTime);
}
this.$input.trigger('change');
},
_onFocus: function(){
var inst;
var tp_inst;
if(! this.$input.val()&&this._defaults.defaultValue){
this.$input.val(this._defaults.defaultValue);
inst=$.tm_datepicker._getInst(this.$input.get(0));
tp_inst=$.tm_datepicker._get(inst, 'tm_timepicker');
if(tp_inst){
if(tp_inst._defaults.timeOnly&&inst.input.val()!==inst.lastVal){
try {
$.tm_datepicker._updateDatepicker(inst);
} catch(err){
$.tm_timepicker.log(err);
}}
}}
},
_controls: {
slider: {
create: function(tp_inst, obj, unit, val, min, max, step){
var rtl=tp_inst._defaults.isRTL;
return obj.prop('slide', null).slider({
orientation: 'horizontal',
value: rtl ? val * -1:val,
min: rtl ? max * -1:min,
max: rtl ? min * -1:max,
step: step,
slide: function(event, ui){
tp_inst.control.value(tp_inst, $(this), unit, rtl ? ui.value * -1:ui.value);
tp_inst._onTimeChange();
},
stop: function(){
tp_inst._onSelectHandler();
}});
},
options: function(tp_inst, obj, unit, opts, val){
var min;
var max;
if(tp_inst._defaults.isRTL){
if(typeof opts==='string'){
if(opts==='min'||opts==='max'){
if(val!==undefined){
return obj.slider(opts, val * -1);
}
return Math.abs(obj.slider(opts));
}
return obj.slider(opts);
}
min=opts.min;
max=opts.max;
opts.max=null;
opts.min=null;
if(min!==undefined){
opts.max=min * -1;
}
if(max!==undefined){
opts.min=max * -1;
}
return obj.slider(opts);
}
if(typeof opts==='string'&&val!==undefined){
return obj.slider(opts, val);
}
return obj.slider(opts);
},
value: function(tp_inst, obj, unit, val){
if(tp_inst._defaults.isRTL){
if(val!==undefined){
return obj.slider('value', val * -1);
}
return Math.abs(obj.slider('value'));
}
if(val!==undefined){
return obj.slider('value', val);
}
return obj.slider('value');
}},
select: {
create: function(tp_inst, obj, unit, val, min, max, step){
var sel='<select class="ui-tm-timepicker-select ui-state-default ui-corner-all" data-unit="' + unit + '" data-min="' + min + '" data-max="' + max + '" data-step="' + step + '">',
format=tp_inst._defaults.pickerTimeFormat||tp_inst._defaults.timeFormat;
var i;
for(i=min; i <=max; i +=step){
sel +='<option value="' + i + '"' +(i===val ? ' selected':'') + '>';
if(unit==='hour'){
sel +=$.tm_datepicker.formatTime($.epoAPI.util.trim(format.replace(/[^ht ]/gi, '')), { hour: i }, tp_inst._defaults);
}else if(unit==='millisec'||unit==='microsec'||i >=10){
sel +=i;
}else{
sel +='0' + i.toString();
}
sel +='</option>';
}
sel +='</select>';
obj.children('select').remove();
$(sel)
.appendTo(obj)
.on('change', function(){
tp_inst._onTimeChange();
tp_inst._onSelectHandler();
tp_inst._afterInject();
});
return obj;
},
options: function(tp_inst, obj, unit, opts, val){
var o={},
$t=obj.children('select');
if(typeof opts==='string'){
if(val===undefined){
return $t.data(opts);
}
o[ opts ]=val;
}else{
o=opts;
}
return tp_inst.control.create(tp_inst, obj, $t.data('unit'), $t.val(), o.min >=0 ? o.min:$t.data('min'), o.max||$t.data('max'), o.step||$t.data('step'));
},
value: function(tp_inst, obj, unit, val){
var $t=obj.children('select');
if(val!==undefined){
return $t.val(val);
}
return $t.val();
}}
}});
$.fn.extend({
tm_timepicker: function(o){
var tmp_args=Array.prototype.slice.call(arguments);
o=o||{};
if(typeof o==='object'){
tmp_args[ 0 ]=$.extend(o, {
timeOnly: true
});
}
return $(this).each(function(){
$.fn.tm_datetimepicker.apply($(this), tmp_args);
});
},
tm_datetimepicker: function(o){
var tmp_args=arguments;
o=o||{};
if(typeof o==='string'){
if(o==='getDate'||(o==='option'&&tmp_args.length===2&&typeof tmp_args[ 1 ]==='string')){
return $.fn.tm_datepicker.apply($(this[ 0 ]), tmp_args);
}
return this.each(function(){
var $t=$(this);
$t.tm_datepicker.apply($t, tmp_args);
});
}
return this.each(function(){
var $t=$(this);
$t.tm_datepicker($.tm_timepicker._newInst($t, o)._defaults);
});
}});
$.tm_datepicker.parseDateTime=function(dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings){
var parseRes=parseDateTimeInternal(dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings);
var t;
if(parseRes.timeObj){
t=parseRes.timeObj;
parseRes.date.setHours(t.hour, t.minute, t.second, t.millisec);
parseRes.date.setMicroseconds(t.microsec);
}
return parseRes.date;
};
$.tm_datepicker.parseTime=function(timeFormat, timeString, options){
var o=extendRemove(extendRemove({}, $.tm_timepicker._defaults), options||{});
var strictParse=function(f, s, oo){
var getPatternAmpm=function(amNames, pmNames){
var markers=[];
if(amNames){
$.merge(markers, amNames);
}
if(pmNames){
$.merge(markers, pmNames);
}
markers=$.map(markers, function(val){
return val.replace(/[.*+?|()[\]{}\\]/g, '\\$&');
});
return '(' + markers.join('|') + ')?';
};
var getFormatPositions=function(formatoftime){
var finds=formatoftime.toLowerCase().match(/(h{1,2}|m{1,2}|s{1,2}|l{1}|c{1}|t{1,2}|z|'.*?')/g),
orders={
h: -1,
m: -1,
s: -1,
l: -1,
c: -1,
t: -1,
z: -1
};
var i;
if(finds){
for(i=0; i < finds.length; i +=1){
if(orders[ finds[ i ].toString().charAt(0) ]===-1){
orders[ finds[ i ].toString().charAt(0) ]=i + 1;
}}
}
return orders;
};
var regstr =
'^' +
f
.toString()
.replace(/([hH]{1,2}|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|'.*?')/g, function(match){
var ml=match.length;
switch(match.charAt(0).toLowerCase()){
case 'h':
return ml===1 ? '(\\d?\\d)':'(\\d{' + ml + '})';
case 'm':
return ml===1 ? '(\\d?\\d)':'(\\d{' + ml + '})';
case 's':
return ml===1 ? '(\\d?\\d)':'(\\d{' + ml + '})';
case 'l':
return '(\\d?\\d?\\d)';
case 'c':
return '(\\d?\\d?\\d)';
case 'z':
return '(z|[-+]\\d\\d:?\\d\\d|\\S+)?';
case 't':
return getPatternAmpm(oo.amNames, oo.pmNames);
default:
return (
'(' +
match.replace(/'/g, '').replace(/(\.|\$|\^|\\|\/|\(|\)|\[|\]|\?|\+|\*)/g, function(m){
return '\\' + m;
}) +
')?'
);
}})
.replace(/\s/g, '\\s?') +
oo.timeSuffix +
'$',
order=getFormatPositions(f),
ampm='',
treg;
var resTime={
hour: 0,
minute: 0,
second: 0,
millisec: 0,
microsec: 0
};
treg=s.match(new RegExp(regstr, 'i'));
if(treg){
if(order.t!==-1){
if(treg[ order.t ]===undefined||treg[ order.t ].length===0){
ampm='';
resTime.ampm='';
}else{
ampm =
$.inArray(treg[ order.t ].toUpperCase(),
$.map(oo.amNames, function(x){
return x.toUpperCase();
})
)!==-1
? 'AM'
: 'PM';
resTime.ampm=oo[ ampm==='AM' ? 'amNames':'pmNames' ][ 0 ];
}}
if(order.h!==-1){
if(ampm==='AM'&&treg[ order.h ]==='12'){
resTime.hour=0;
}else if(ampm==='PM'&&treg[ order.h ]!=='12'){
resTime.hour=parseInt(treg[ order.h ], 10) + 12;
}else{
resTime.hour=Number(treg[ order.h ]);
}}
if(order.m!==-1){
resTime.minute=Number(treg[ order.m ]);
}
if(order.s!==-1){
resTime.second=Number(treg[ order.s ]);
}
if(order.l!==-1){
resTime.millisec=Number(treg[ order.l ]);
}
if(order.c!==-1){
resTime.microsec=Number(treg[ order.c ]);
}
if(order.z!==-1&&treg[ order.z ]!==undefined){
resTime.timezone=$.tm_timepicker.timezoneOffsetNumber(treg[ order.z ]);
}
return resTime;
}
return false;
};
var looseParse=function(f, s, oo){
var d;
try {
d=new Date('2012-01-01 ' + s);
if(isNaN(d.getTime())){
d=new Date('2012-01-01T' + s);
if(isNaN(d.getTime())){
d=new Date('01/01/2012 ' + s);
if(isNaN(d.getTime())){
throw 'Unable to parse time with native Date: ' + s;
}}
}
return {
hour: d.getHours(),
minute: d.getMinutes(),
second: d.getSeconds(),
millisec: d.getMilliseconds(),
microsec: d.getMicroseconds(),
timezone: d.getTimezoneOffset() * -1
};} catch(err){
try {
return strictParse(f, s, oo);
} catch(err2){
$.tm_timepicker.log('Unable to parse \ntimeString: ' + s + '\ntimeFormat: ' + f);
}}
return false;
};
if(typeof o.parse==='function'){
return o.parse(timeFormat, timeString, o);
}
if(o.parse==='loose'){
return looseParse(timeFormat, timeString, o);
}
return strictParse(timeFormat, timeString, o);
};
$.tm_datepicker.formatTime=function(format, time, options){
var tmptime;
var ampmName;
var hour;
options=options||{};
options=$.extend({}, $.tm_timepicker._defaults, options);
time=$.extend({
hour: 0,
minute: 0,
second: 0,
millisec: 0,
microsec: 0,
timezone: null
},
time
);
tmptime=format;
ampmName=options.amNames[ 0 ];
hour=parseInt(time.hour, 10);
if(hour > 11){
ampmName=options.pmNames[ 0 ];
}
tmptime=tmptime.replace(/(?:HH?|hh?|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|'.*?')/g, function(match){
switch(match){
case 'HH':
return('0' + hour).slice(-2);
case 'H':
return hour;
case 'hh':
return('0' + convert24to12(hour)).slice(-2);
case 'h':
return convert24to12(hour);
case 'mm':
return('0' + time.minute).slice(-2);
case 'm':
return time.minute;
case 'ss':
return('0' + time.second).slice(-2);
case 's':
return time.second;
case 'l':
return('00' + time.millisec).slice(-3);
case 'c':
return('00' + time.microsec).slice(-3);
case 'z':
return $.tm_timepicker.timezoneOffsetString(time.timezone===null ? options.timezone:time.timezone, false);
case 'Z':
return $.tm_timepicker.timezoneOffsetString(time.timezone===null ? options.timezone:time.timezone, true);
case 'T':
return ampmName.charAt(0).toUpperCase();
case 'TT':
return ampmName.toUpperCase();
case 't':
return ampmName.charAt(0).toLowerCase();
case 'tt':
return ampmName.toLowerCase();
default:
return match.replace(/'/g, '');
}});
return tmptime;
};
$.tm_datepicker._base_selectDate=$.tm_datepicker._selectDate;
$.tm_datepicker._selectDate=function(id, dateStr){
var inst=this._getInst($(id)[ 0 ]),
tp_inst=this._get(inst, 'tm_timepicker'),
was_inline;
if(tp_inst&&inst.settings.showTimepicker){
tp_inst._limitMinMaxDateTime(inst, true);
was_inline=inst.inline;
inst.stay_open=true;
inst.inline=true;
this._base_selectDate(id, dateStr);
inst.inline=was_inline;
inst.stay_open=false;
this._notifyChange(inst);
this._updateDatepicker(inst);
}else{
this._base_selectDate(id, dateStr);
}};
$.tm_datepicker._base_updateDatepicker=$.tm_datepicker._updateDatepicker;
$.tm_datepicker._updateDatepicker=function(inst){
var input=inst.input[ 0 ];
var tp_inst;
if($.tm_datepicker._curInst&&$.tm_datepicker._curInst!==inst&&$.tm_datepicker._datepickerShowing&&$.tm_datepicker._lastInput!==input){
return;
}
if(typeof inst.stay_open!=='boolean'||inst.stay_open===false){
this._base_updateDatepicker(inst);
tp_inst=this._get(inst, 'tm_timepicker');
if(tp_inst){
tp_inst._addTimePicker(inst);
}}
};
$.tm_datepicker._base_doKeyPress=$.tm_datepicker._doKeyPress;
$.tm_datepicker._doKeyPress=function(event){
var inst=$.tm_datepicker._getInst(event.target),
tp_inst=$.tm_datepicker._get(inst, 'tm_timepicker');
var ampm;
var tz;
var dateChars;
var datetimeChars;
var chr;
if(tp_inst){
if($.tm_datepicker._get(inst, 'constrainInput')){
ampm=tp_inst.support.ampm;
tz=tp_inst._defaults.showTimezone!==null ? tp_inst._defaults.showTimezone:tp_inst.support.timezone;
dateChars=$.tm_datepicker._possibleChars($.tm_datepicker._get(inst, 'dateFormat'));
datetimeChars =
tp_inst._defaults.timeFormat
.toString()
.replace(/[hms]/g, '')
.replace(/TT/g, ampm ? 'APM':'')
.replace(/Tt/g, ampm ? 'AaPpMm':'')
.replace(/tT/g, ampm ? 'AaPpMm':'')
.replace(/T/g, ampm ? 'AP':'')
.replace(/tt/g, ampm ? 'apm':'')
.replace(/t/g, ampm ? 'ap':'') +
' ' +
tp_inst._defaults.separator +
tp_inst._defaults.timeSuffix +
(tz ? tp_inst._defaults.timezoneList.join(''):'') +
tp_inst._defaults.amNames.join('') +
tp_inst._defaults.pmNames.join('') +
dateChars;
chr=String.fromCharCode(event.charCode===undefined ? event.keyCode:event.charCode);
return event.ctrlKey||chr < ' '||! dateChars||datetimeChars.indexOf(chr) > -1;
}}
return $.tm_datepicker._base_doKeyPress(event);
};
$.tm_datepicker._base_updateAlternate=$.tm_datepicker._updateAlternate;
$.tm_datepicker._updateAlternate=function(inst){
var tp_inst=this._get(inst, 'tm_timepicker');
var altField;
var date;
var formatCfg;
var altFormattedDateTime;
var altSeparator;
var altTimeSuffix;
var altTimeFormat;
if(tp_inst){
altField=tp_inst._defaults.altField;
if(altField){
date=this._getDate(inst);
formatCfg=$.tm_datepicker._getFormatConfig(inst);
altFormattedDateTime='';
altSeparator=tp_inst._defaults.altSeparator ? tp_inst._defaults.altSeparator:tp_inst._defaults.separator;
altTimeSuffix=tp_inst._defaults.altTimeSuffix ? tp_inst._defaults.altTimeSuffix:tp_inst._defaults.timeSuffix;
altTimeFormat=tp_inst._defaults.altTimeFormat!==null ? tp_inst._defaults.altTimeFormat:tp_inst._defaults.timeFormat;
altFormattedDateTime +=$.tm_datepicker.formatTime(altTimeFormat, tp_inst, tp_inst._defaults) + altTimeSuffix;
if(! tp_inst._defaults.timeOnly&&! tp_inst._defaults.altFieldTimeOnly&&date!==null){
if(tp_inst._defaults.altFormat){
altFormattedDateTime=$.tm_datepicker.formatDate(tp_inst._defaults.altFormat, date, formatCfg) + altSeparator + altFormattedDateTime;
}else{
altFormattedDateTime=tp_inst.formattedDate + altSeparator + altFormattedDateTime;
}}
$(altField).val(inst.input.val() ? altFormattedDateTime:'');
}}else{
$.tm_datepicker._base_updateAlternate(inst);
}};
$.tm_datepicker._base_doKeyUp=$.tm_datepicker._doKeyUp;
$.tm_datepicker._doKeyUp=function(event){
var inst=$.tm_datepicker._getInst(event.target),
tp_inst=$.tm_datepicker._get(inst, 'tm_timepicker');
if(tp_inst){
if(tp_inst._defaults.timeOnly&&inst.input.val()!==inst.lastVal){
try {
$.tm_datepicker._updateDatepicker(inst);
} catch(err){
$.tm_timepicker.log(err);
}}
}
return $.tm_datepicker._base_doKeyUp(event);
};
$.tm_datepicker._base_gotoToday=$.tm_datepicker._gotoToday;
$.tm_datepicker._gotoToday=function(id){
var inst=this._getInst($(id)[ 0 ]);
var tp_inst;
var tzoffset;
var now;
this._base_gotoToday(id);
tp_inst=this._get(inst, 'timepicker');
if(! tp_inst){
return;
}
tzoffset=$.tm_timepicker.timezoneOffsetNumber(tp_inst.timezone);
now=new Date();
now.setMinutes(now.getMinutes() + now.getTimezoneOffset() + parseInt(tzoffset, 10));
this._setTime(inst, now);
this._setDate(inst, now);
tp_inst._onSelectHandler();
};
$.tm_datepicker._disableTimepickerDatepicker=function(target){
var inst=this._getInst(target);
var tp_inst;
if(! inst){
return;
}
tp_inst=this._get(inst, 'tm_timepicker');
$(target).tm_datepicker('getDate');
if(tp_inst){
inst.settings.showTimepicker=false;
tp_inst._defaults.showTimepicker=false;
tp_inst._updateDateTime(inst);
}};
$.tm_datepicker._enableTimepickerDatepicker=function(target){
var inst=this._getInst(target);
var tp_inst;
if(! inst){
return;
}
tp_inst=this._get(inst, 'tm_timepicker');
$(target).tm_datepicker('getDate');
if(tp_inst){
inst.settings.showTimepicker=true;
tp_inst._defaults.showTimepicker=true;
tp_inst._addTimePicker(inst);
tp_inst._updateDateTime(inst);
}};
$.tm_datepicker._setTime=function(inst, date){
var tp_inst=this._get(inst, 'tm_timepicker');
var defaults;
if(tp_inst){
defaults=tp_inst._defaults;
tp_inst.hour=date ? date.getHours():defaults.hour;
tp_inst.minute=date ? date.getMinutes():defaults.minute;
tp_inst.second=date ? date.getSeconds():defaults.second;
tp_inst.millisec=date ? date.getMilliseconds():defaults.millisec;
tp_inst.microsec=date ? date.getMicroseconds():defaults.microsec;
tp_inst._limitMinMaxDateTime(inst, true);
tp_inst._onTimeChange();
tp_inst._updateDateTime(inst);
}};
$.tm_datepicker._setTimeDatepicker=function(target, date, withDate){
var inst=this._getInst(target);
var tp_inst;
var tp_date;
if(! inst){
return;
}
tp_inst=this._get(inst, 'tm_timepicker');
if(tp_inst){
this._setDateFromField(inst);
if(date){
if(typeof date==='string'){
tp_inst._parseTime(date, withDate);
tp_date=new Date();
tp_date.setHours(tp_inst.hour, tp_inst.minute, tp_inst.second, tp_inst.millisec);
tp_date.setMicroseconds(tp_inst.microsec);
}else{
tp_date=new Date(date.getTime());
tp_date.setMicroseconds(date.getMicroseconds());
}
if(tp_date.toString()==='Invalid Date'){
tp_date=undefined;
}
this._setTime(inst, tp_date);
}}
};
$.tm_datepicker._base_setDateDatepicker=$.tm_datepicker._setDateDatepicker;
$.tm_datepicker._setDateDatepicker=function(target, _date){
var inst=this._getInst(target);
var date=_date;
var tp_inst;
var tp_date;
if(! inst){
return;
}
if(typeof _date==='string'){
date=new Date(_date);
if(! date.getTime()){
this._base_setDateDatepicker.apply(this, arguments);
date=$(target).tm_datepicker('getDate');
}}
tp_inst=this._get(inst, 'tm_timepicker');
if(date instanceof Date){
tp_date=new Date(date.getTime());
tp_date.setMicroseconds(date.getMicroseconds());
}else{
tp_date=date;
}
if(tp_inst&&tp_date){
if(! tp_inst.support.timezone&&tp_inst._defaults.timezone===null){
tp_inst.timezone=tp_date.getTimezoneOffset() * -1;
}
date=$.tm_timepicker.timezoneAdjust(date, $.tm_timepicker.timezoneOffsetString(-date.getTimezoneOffset()), tp_inst.timezone);
tp_date=$.tm_timepicker.timezoneAdjust(tp_date, $.tm_timepicker.timezoneOffsetString(-tp_date.getTimezoneOffset()), tp_inst.timezone);
}
this._updateDatepicker(inst);
this._base_setDateDatepicker.apply(this, arguments);
this._setTimeDatepicker(target, tp_date, true);
};
$.tm_datepicker._base_getDateDatepicker=$.tm_datepicker._getDateDatepicker;
$.tm_datepicker._getDateDatepicker=function(target, noDefault){
var inst=this._getInst(target);
var tp_inst;
var date;
var currDT;
if(! inst){
return;
}
tp_inst=this._get(inst, 'tm_timepicker');
if(tp_inst){
if(inst.lastVal===undefined){
this._setDateFromField(inst, noDefault);
}
date=this._getDate(inst);
currDT=null;
if(tp_inst.$altInput&&tp_inst._defaults.altFieldTimeOnly){
currDT=tp_inst.$input.val() + ' ' + tp_inst.$altInput.val();
}else if(tp_inst.$input.get(0).tagName!=='INPUT'&&tp_inst.$altInput){
currDT=tp_inst.$altInput.val();
}else{
currDT=tp_inst.$input.val();
}
if(date&&tp_inst._parseTime(currDT, ! inst.settings.timeOnly)){
date.setHours(tp_inst.hour, tp_inst.minute, tp_inst.second, tp_inst.millisec);
date.setMicroseconds(tp_inst.microsec);
if(tp_inst.timezone!==null){
if(! tp_inst.support.timezone&&tp_inst._defaults.timezone===null){
tp_inst.timezone=date.getTimezoneOffset() * -1;
}
date=$.tm_timepicker.timezoneAdjust(date, tp_inst.timezone, $.tm_timepicker.timezoneOffsetString(-date.getTimezoneOffset()));
}}
return date;
}
return this._base_getDateDatepicker(target, noDefault);
};
$.tm_datepicker._base_parseDate=$.tm_datepicker.parseDate;
$.tm_datepicker.parseDate=function(format, value, settings){
var date;
try {
date=this._base_parseDate(format, value, settings);
} catch(err){
if(err.indexOf(':') >=0){
date=this._base_parseDate(format, value.substring(0, value.length -(err.length - err.indexOf(':') - 2)), settings);
$.tm_timepicker.log('Error parsing the date string: ' + err + '\ndate string=' + value + '\ndate format=' + format);
}else{
throw err;
}}
return date;
};
$.tm_datepicker._base_formatDate=$.tm_datepicker._formatDate;
$.tm_datepicker._formatDate=function(inst){
var tp_inst=this._get(inst, 'tm_timepicker');
if(tp_inst){
tp_inst._updateDateTime(inst);
return tp_inst.$input.val();
}
return this._base_formatDate(inst);
};
$.tm_datepicker._base_optionDatepicker=$.tm_datepicker._optionDatepicker;
$.tm_datepicker._optionDatepicker=function(target, name, value){
var inst=this._getInst(target),
name_clone;
var tp_inst;
var min, max, onselect, overrides, fns, prop, ret, oldVal, $target;
if(! inst){
return null;
}
tp_inst=this._get(inst, 'tm_timepicker');
if(tp_inst){
min=null;
max=null;
onselect=null;
overrides=tp_inst._defaults.evnts;
fns={};
if(typeof name==='string'){
if(name==='minDate'||name==='minDateTime'){
min=value;
}else if(name==='maxDate'||name==='maxDateTime'){
max=value;
}else if(name==='onSelect'){
onselect=value;
}else if(Object.prototype.hasOwnProperty.call(overrides, name)){
if(typeof value==='undefined'){
return overrides[ name ];
}
fns[ name ]=value;
name_clone={};}}else if(typeof name==='object'){
if(name.minDate){
min=name.minDate;
}else if(name.minDateTime){
min=name.minDateTime;
}else if(name.maxDate){
max=name.maxDate;
}else if(name.maxDateTime){
max=name.maxDateTime;
}
for(prop in overrides){
if(Object.prototype.hasOwnProperty.call(overrides, prop)&&name[ prop ]){
fns[ prop ]=name[ prop ];
}}
}
for(prop in fns){
if(Object.prototype.hasOwnProperty.call(fns, prop)){
overrides[ prop ]=fns[ prop ];
if(! name_clone){
name_clone=$.extend({}, name);
}
delete name_clone[ prop ];
}}
if(name_clone&&isEmptyObject(name_clone)){
return;
}
if(min){
if(min===0){
min=new Date();
}else{
min=new Date(min);
}
tp_inst._defaults.minDate=min;
tp_inst._defaults.minDateTime=min;
}else if(max){
if(max===0){
max=new Date();
}else{
max=new Date(max);
}
tp_inst._defaults.maxDate=max;
tp_inst._defaults.maxDateTime=max;
}else if(onselect){
tp_inst._defaults.onSelect=onselect;
}
if(min||max){
$target=$(target);
oldVal=$target.tm_datetimepicker('getDate');
ret=this._base_optionDatepicker.call($.tm_datepicker, target, name_clone||name, value);
$target.tm_datetimepicker('setDate', oldVal);
return ret;
}}
if(value===undefined){
return this._base_optionDatepicker.call($.tm_datepicker, target, name);
}
return this._base_optionDatepicker.call($.tm_datepicker, target, name_clone||name, value);
};
$.tm_timepicker=new Timepicker();
$.tm_timepicker.timezoneOffsetString=function(tzMinutes, iso8601){
var off, minutes, hours, iso, tz;
if(isNaN(tzMinutes)||tzMinutes > 840||tzMinutes < -720){
return tzMinutes;
}
off=tzMinutes;
minutes=off % 60;
hours=(off - minutes) / 60;
iso=iso8601 ? ':':'';
tz=(off >=0 ? '+':'-') +('0' + Math.abs(hours)).slice(-2) + iso +('0' + Math.abs(minutes)).slice(-2);
if(tz==='+00:00'){
return 'Z';
}
return tz;
};
$.tm_timepicker.timezoneOffsetNumber=function(tzString){
var normalized=tzString.toString().replace(':', '');
if(normalized.toUpperCase()==='Z'){
return 0;
}
if(! /^(-|\+)\d{4}$/.test(normalized)){
return parseInt(tzString, 10);
}
return (
(normalized.substring(0, 1)==='-' ? -1:1) *
(( parseInt(normalized.substring(1, 3), 10) * 60) +
parseInt(normalized.substring(3, 5), 10))
);
};
$.tm_timepicker.timezoneAdjust=function(date, fromTimezone, toTimezone){
var fromTz=$.timepicker.timezoneOffsetNumber(fromTimezone);
var toTz=$.tm_timepicker.timezoneOffsetNumber(toTimezone);
if(! isNaN(toTz)){
date.setMinutes(date.getMinutes() + -fromTz - -toTz);
}
return date;
};
$.tm_timepicker.timeRange=function(startTime, endTime, options){
return $.tm_timepicker.handleRange('tm_timepicker', startTime, endTime, options);
};
$.tm_timepicker.datetimeRange=function(startTime, endTime, options){
$.tm_timepicker.handleRange('tm_datetimepicker', startTime, endTime, options);
};
$.tm_timepicker.dateRange=function(startTime, endTime, options){
$.tm_timepicker.handleRange('tm_datepicker', startTime, endTime, options);
};
$.tm_timepicker.handleRange=function(method, startTime, endTime, options){
var timeOnly=false;
options=$.extend({},
{
minInterval: 0,
maxInterval: 0,
start: {},
end: {}},
options
);
if(method==='tm_timepicker'){
timeOnly=true;
method='tm_datetimepicker';
}
function checkDates(changed, other){
var startdt=startTime[ method ]('getDate'),
enddt=endTime[ method ]('getDate'),
changeddt=changed[ method ]('getDate');
var minDate;
var maxDate;
if(startdt!==null){
minDate=new Date(startdt.getTime());
maxDate=new Date(startdt.getTime());
minDate.setMilliseconds(minDate.getMilliseconds() + options.minInterval);
maxDate.setMilliseconds(maxDate.getMilliseconds() + options.maxInterval);
if(options.minInterval > 0&&minDate > enddt){
endTime[ method ]('setDate', minDate);
}else if(options.maxInterval > 0&&maxDate < enddt){
endTime[ method ]('setDate', maxDate);
}else if(startdt > enddt){
other[ method ]('setDate', changeddt);
}}
}
function selected(changed, other, option){
var date;
if(! changed.val()){
return;
}
date=changed[ method ].call(changed, 'getDate');
if(date!==null&&options.minInterval > 0){
if(option==='minDate'){
date.setMilliseconds(date.getMilliseconds() + options.minInterval);
}
if(option==='maxDate'){
date.setMilliseconds(date.getMilliseconds() - options.minInterval);
}}
if(date.getTime){
other[ method ].call(other, 'option', option, date);
}}
$.fn[ method ].call(startTime,
$.extend({
timeOnly: timeOnly,
onClose: function(){
checkDates($(this), endTime);
},
onSelect: function(){
selected($(this), endTime, 'minDate');
}},
options,
options.start
)
);
$.fn[ method ].call(endTime,
$.extend({
timeOnly: timeOnly,
onClose: function(){
checkDates($(this), startTime);
},
onSelect: function(){
selected($(this), startTime, 'maxDate');
}},
options,
options.end
)
);
checkDates(startTime, endTime);
selected(startTime, endTime, 'minDate');
selected(endTime, startTime, 'maxDate');
return $([ startTime.get(0), endTime.get(0) ]);
};
$.tm_timepicker.log=function(){
if(window.console&&window.console.log&&window.console.log.apply){
window.console.log.apply(window.console, Array.prototype.slice.call(arguments));
}};
$.tm_timepicker._util={
_extendRemove: extendRemove,
_isEmptyObject: isEmptyObject,
_convert24to12: convert24to12,
_detectSupport: detectSupport,
_selectLocalTimezone: selectLocalTimezone,
_computeEffectiveSetting: computeEffectiveSetting,
_splitDateTime: splitDateTime,
_parseDateTimeInternal: parseDateTimeInternal
};
if(! Date.prototype.getMicroseconds){
Object.defineProperty(Date.prototype, 'microseconds', {
value: 0,
writable: true
});
Object.defineProperty(Date.prototype, 'getMicroseconds', {
value: function(){
return this.microseconds;
}});
Object.defineProperty(Date.prototype, 'setMicroseconds', {
value: function(m){
this.setMilliseconds(this.getMilliseconds() + Math.floor(m / 1000));
this.microseconds=m % 1000;
return this;
}});
}
$.tm_timepicker.version='1.6.3';
}));
(function($, window, document){
'use strict';
function Owl(element, options){
this.settings=null;
this.options=$.extend({}, Owl.Defaults, options);
this.$element=$(element);
this._handlers={};
this._plugins={};
this._supress={};
this._current=null;
this._speed=null;
this._coordinates=[];
this._breakpoint=null;
this._width=null;
this._items=[];
this._clones=[];
this._mergers=[];
this._widths=[];
this._invalidated={};
this._pipe=[];
this._drag={
time: null,
target: null,
pointer: null,
stage: {
start: null,
current: null
},
direction: null
};
this._states={
current: {},
tags: {
initializing: [ 'busy' ],
animating: [ 'busy' ],
dragging: [ 'interacting' ]
}};
$.each([ 'onResize', 'onThrottledResize' ],
$.proxy(function(i, handler){
this._handlers[ handler ]=$.proxy(this[ handler ], this);
}, this)
);
$.each(Owl.Plugins,
$.proxy(function(key, Plugin){
this._plugins[ key.charAt(0).toLowerCase() + key.slice(1) ]=new Plugin(this);
}, this)
);
$.each(Owl.Workers,
$.proxy(function(priority, worker){
this._pipe.push({
filter: worker.filter,
run: $.proxy(worker.run, this)
});
}, this)
);
this.setup();
this.initialize();
}
Owl.Defaults={
items: 3,
loop: false,
center: false,
rewind: false,
checkVisibility: true,
mouseDrag: true,
touchDrag: true,
pullDrag: true,
freeDrag: false,
margin: 0,
stagePadding: 0,
merge: false,
mergeFit: true,
autoWidth: false,
startPosition: 0,
rtl: false,
smartSpeed: 250,
fluidSpeed: false,
dragEndSpeed: false,
responsive: {},
responsiveRefreshRate: 200,
responsiveBaseElement: window,
fallbackEasing: 'linear',
slideTransition: '',
info: false,
nestedItemSelector: false,
itemElement: 'div',
stageElement: 'div',
refreshClass: 'owl-refresh',
loadedClass: 'owl-loaded',
loadingClass: 'owl-loading',
rtlClass: 'owl-rtl',
responsiveClass: 'owl-responsive',
dragClass: 'owl-drag',
itemClass: 'owl-item',
stageClass: 'owl-stage',
stageOuterClass: 'owl-stage-outer',
grabClass: 'owl-grab'
};
Owl.Width={
Default: 'default',
Inner: 'inner',
Outer: 'outer'
};
Owl.Type={
Event: 'event',
State: 'state'
};
Owl.Plugins={};
Owl.Workers=[
{
filter: [ 'width', 'settings' ],
run: function(){
this._width=this.$element.width();
}},
{
filter: [ 'width', 'items', 'settings' ],
run: function(cache){
cache.current=this._items&&this._items[ this.relative(this._current) ];
}},
{
filter: [ 'items', 'settings' ],
run: function(){
this.$stage.children('.cloned').remove();
}},
{
filter: [ 'width', 'items', 'settings' ],
run: function(cache){
var margin=this.settings.margin||'',
grid = ! this.settings.autoWidth,
rtl=this.settings.rtl,
css={
width: 'auto',
'margin-left': rtl ? margin:'',
'margin-right': rtl ? '':margin
};
if(! grid){
this.$stage.children().css(css);
}
cache.css=css;
}},
{
filter: [ 'width', 'items', 'settings' ],
run: function(cache){
var width=(this.width() / this.settings.items).toFixed(3) - this.settings.margin,
merge=null,
iterator=this._items.length,
grid = ! this.settings.autoWidth,
widths=[];
cache.items={
merge: false,
width: width
};
while(iterator > 0){
iterator=iterator - 1;
merge=this._mergers[ iterator ];
merge=(this.settings.mergeFit&&Math.min(merge, this.settings.items))||merge;
cache.items.merge=merge > 1||cache.items.merge;
widths[ iterator ] = ! grid ? this._items[ iterator ].width():width * merge;
}
this._widths=widths;
}},
{
filter: [ 'items', 'settings' ],
run: function(){
var clones=[],
items=this._items,
settings=this.settings,
view=Math.max(settings.items * 2, 4),
size=Math.ceil(items.length / 2) * 2,
repeat=settings.loop&&items.length ?(settings.rewind ? view:Math.max(view, size)):0,
append='',
prepend='';
repeat /=2;
while(repeat > 0){
clones.push(this.normalize(clones.length / 2, true));
append=append + items[ clones[ clones.length - 1 ] ][ 0 ].outerHTML;
clones.push(this.normalize(items.length - 1 -(( clones.length - 1) / 2), true));
prepend=items[ clones[ clones.length - 1 ] ][ 0 ].outerHTML + prepend;
repeat -=1;
}
this._clones=clones;
$(append).addClass('cloned').appendTo(this.$stage);
$(prepend).addClass('cloned').prependTo(this.$stage);
}},
{
filter: [ 'width', 'items', 'settings' ],
run: function(){
var rtl=this.settings.rtl ? 1:-1,
size=this._clones.length + this._items.length,
iterator=0,
previous=0,
current=0,
coordinates=[];
while(iterator < size){
previous=coordinates[ iterator - 1 ]||0;
current=this._widths[ this.relative(iterator) ] + this.settings.margin;
coordinates.push(previous +(current * rtl));
iterator=iterator + 1;
}
this._coordinates=coordinates;
}},
{
filter: [ 'width', 'items', 'settings' ],
run: function(){
var padding=this.settings.stagePadding,
coordinates=this._coordinates,
css={
width: Math.ceil(Math.abs(coordinates[ coordinates.length - 1 ])) +(padding * 2),
'padding-left': padding||'',
'padding-right': padding||''
};
this.$stage.css(css);
}},
{
filter: [ 'width', 'items', 'settings' ],
run: function(cache){
var iterator=this._coordinates.length,
grid = ! this.settings.autoWidth,
items=this.$stage.children();
if(grid&&cache.items.merge){
while(iterator > 0){
iterator=iterator - 1;
cache.css.width=this._widths[ this.relative(iterator) ];
items.eq(iterator).css(cache.css);
}}else if(grid){
cache.css.width=cache.items.width;
items.css(cache.css);
}}
},
{
filter: [ 'items' ],
run: function(){
if(this._coordinates.length < 1){
this.$stage.removeAttr('style');
}}
},
{
filter: [ 'width', 'items', 'settings' ],
run: function(cache){
cache.current=cache.current ? this.$stage.children().index(cache.current):0;
cache.current=Math.max(this.minimum(), Math.min(this.maximum(), cache.current));
this.reset(cache.current);
}},
{
filter: [ 'position' ],
run: function(){
this.animate(this.coordinates(this._current));
}},
{
filter: [ 'width', 'position', 'items', 'settings' ],
run: function(){
var rtl=this.settings.rtl ? 1:-1,
padding=this.settings.stagePadding * 2,
begin=this.coordinates(this.current()) + padding,
end=begin +(this.width() * rtl),
inner,
outer,
matches=[],
i,
n;
for(i=0, n=this._coordinates.length; i < n; i +=1){
inner=this._coordinates[ i - 1 ]||0;
outer=Math.abs(this._coordinates[ i ]) +(padding * rtl);
if(( this.op(inner, '<=', begin)&&this.op(inner, '>', end))||(this.op(outer, '<', begin)&&this.op(outer, '>', end))){
matches.push(i);
}}
this.$stage.children('.active').removeClass('active');
this.$stage.children(':eq(' + matches.join('), :eq(') + ')').addClass('active');
this.$stage.children('.center').removeClass('center');
if(this.settings.center){
this.$stage.children().eq(this.current()).addClass('center');
}}
}
];
Owl.prototype.initializeStage=function(){
this.$stage=this.$element.find('.' + this.settings.stageClass);
if(this.$stage.length){
return;
}
this.$element.addClass(this.options.loadingClass);
this.$stage=$('<' + this.settings.stageElement + '>', {
class: this.settings.stageClass
}).wrap($('<div/>', {
class: this.settings.stageOuterClass
})
);
this.$element.append(this.$stage.parent());
};
Owl.prototype.initializeItems=function(){
var $items=this.$element.find('.owl-item');
if($items.length){
this._items=$items.get().map(function(item){
return $(item);
});
this._mergers=this._items.map(function(){
return 1;
});
this.refresh();
return;
}
this.replace(this.$element.children().not(this.$stage.parent()));
if(this.isVisible()){
this.refresh();
}else{
this.invalidate('width');
}
this.$element.removeClass(this.options.loadingClass).addClass(this.options.loadedClass);
};
Owl.prototype.initialize=function(){
var imgs, nestedSelector, width;
this.enter('initializing');
this.trigger('initialize');
this.$element.toggleClass(this.settings.rtlClass, this.settings.rtl);
if(this.settings.autoWidth&&! this.is('pre-loading')){
imgs=this.$element.find('img');
nestedSelector=this.settings.nestedItemSelector ? '.' + this.settings.nestedItemSelector:undefined;
width=this.$element.children(nestedSelector).width();
if(imgs.length&&width <=0){
this.preloadAutoWidthImages(imgs);
}}
this.initializeStage();
this.initializeItems();
this.registerEventHandlers();
this.leave('initializing');
this.trigger('initialized');
};
Owl.prototype.isVisible=function(){
return this.settings.checkVisibility ? this.$element.is(':visible'):true;
};
Owl.prototype.setup=function(){
var viewport=this.viewport(),
overwrites=this.options.responsive,
match=-1,
settings=null;
if(! overwrites){
settings=$.extend({}, this.options);
}else{
$.each(overwrites, function(breakpoint){
if(breakpoint <=viewport&&breakpoint > match){
match=Number(breakpoint);
}});
settings=$.extend({}, this.options, overwrites[ match ]);
if(typeof settings.stagePadding==='function'){
settings.stagePadding=settings.stagePadding();
}
delete settings.responsive;
if(settings.responsiveClass){
this.$element.attr('class', this.$element.attr('class').replace(new RegExp('(' + this.options.responsiveClass + '-)\\S+\\s', 'g'), '$1' + match));
}}
this.trigger('change', { property: { name: 'settings', value: settings }});
this._breakpoint=match;
this.settings=settings;
this.invalidate('settings');
this.trigger('changed', { property: { name: 'settings', value: this.settings }});
};
Owl.prototype.optionsLogic=function(){
if(this.settings.autoWidth){
this.settings.stagePadding=false;
this.settings.merge=false;
}};
Owl.prototype.prepare=function(item){
var event=this.trigger('prepare', { content: item });
if(! event.data){
event.data=$('<' + this.settings.itemElement + '/>')
.addClass(this.options.itemClass)
.append(item);
}
this.trigger('prepared', { content: event.data });
return event.data;
};
Owl.prototype.update=function(){
var i=0,
n=this._pipe.length,
filter=$.proxy(function(p){
return this[ p ];
}, this._invalidated),
cache={};
while(i < n){
if(this._invalidated.all||$.grep(this._pipe[ i ].filter, filter).length > 0){
this._pipe[ i ].run(cache);
}
i +=1;
}
this._invalidated={};
if(! this.is('valid')){
this.enter('valid');
}};
Owl.prototype.width=function(dimension){
dimension=dimension||Owl.Width.Default;
switch(dimension){
case Owl.Width.Inner:
case Owl.Width.Outer:
return this._width;
default:
return this._width -(this.settings.stagePadding * 2) + this.settings.margin;
}};
Owl.prototype.refresh=function(){
this.enter('refreshing');
this.trigger('refresh');
this.setup();
this.optionsLogic();
this.$element.addClass(this.options.refreshClass);
this.update();
this.$element.removeClass(this.options.refreshClass);
this.leave('refreshing');
this.trigger('refreshed');
};
Owl.prototype.onThrottledResize=function(){
window.clearTimeout(this.resizeTimer);
this.resizeTimer=window.setTimeout(this._handlers.onResize, this.settings.responsiveRefreshRate);
};
Owl.prototype.onResize=function(){
if(! this._items.length){
return false;
}
if(this._width===this.$element.width()){
return false;
}
if(! this.isVisible()){
return false;
}
this.enter('resizing');
if(this.trigger('resize').isDefaultPrevented()){
this.leave('resizing');
return false;
}
this.invalidate('width');
this.refresh();
this.leave('resizing');
this.trigger('resized');
};
Owl.prototype.registerEventHandlers=function(){
if($.support.transition){
this.$stage.on($.support.transition.end + '.owl.core', $.proxy(this.onTransitionEnd, this));
}
if(this.settings.responsive!==false){
this.on(window, 'resize', this._handlers.onThrottledResize);
}
if(this.settings.mouseDrag){
this.$element.addClass(this.options.dragClass);
this.$stage.on('mousedown.owl.core', $.proxy(this.onDragStart, this));
this.$stage.on('dragstart.owl.core selectstart.owl.core', function(){
return false;
});
}
if(this.settings.touchDrag){
this.$stage.on('touchstart.owl.core', $.proxy(this.onDragStart, this));
this.$stage.on('touchcancel.owl.core', $.proxy(this.onDragEnd, this));
}};
Owl.prototype.onDragStart=function(event){
var stage=null;
if(event.which===3){
return;
}
if($.support.transform){
stage=this.$stage
.css('transform')
.replace(/.*\(|\)| /g, '')
.split(',');
stage={
x: stage[ stage.length===16 ? 12:4 ],
y: stage[ stage.length===16 ? 13:5 ]
};}else{
stage=this.$stage.position();
stage={
x: this.settings.rtl ? stage.left + this.$stage.width() - this.width() + this.settings.margin:stage.left,
y: stage.top
};}
if(this.is('animating')){
if($.support.transform){
this.animate(stage.x);
}else{
this.$stage.stop();
}
this.invalidate('position');
}
this.$element.toggleClass(this.options.grabClass, event.type==='mousedown');
this.speed(0);
this._drag.time=new Date().getTime();
this._drag.target=$(event.target);
this._drag.stage.start=stage;
this._drag.stage.current=stage;
this._drag.pointer=this.pointer(event);
$(document).on('mouseup.owl.core touchend.owl.core', $.proxy(this.onDragEnd, this));
$(document).one('mousemove.owl.core touchmove.owl.core',
$.proxy(function(e){
var delta=this.difference(this._drag.pointer, this.pointer(e));
$(document).on('mousemove.owl.core touchmove.owl.core', $.proxy(this.onDragMove, this));
if(Math.abs(delta.x) < Math.abs(delta.y)&&this.is('valid')){
return;
}
e.preventDefault();
this.enter('dragging');
this.trigger('drag');
}, this)
);
};
Owl.prototype.onDragMove=function(event){
var minimum=null,
maximum=null,
pull=null,
delta=this.difference(this._drag.pointer, this.pointer(event)),
stage=this.difference(this._drag.stage.start, delta);
if(! this.is('dragging')){
return;
}
event.preventDefault();
if(this.settings.loop){
minimum=this.coordinates(this.minimum());
maximum=this.coordinates(this.maximum() + 1) - minimum;
stage.x=(((( stage.x - minimum) % maximum) + maximum) % maximum) + minimum;
}else{
minimum=this.settings.rtl ? this.coordinates(this.maximum()):this.coordinates(this.minimum());
maximum=this.settings.rtl ? this.coordinates(this.minimum()):this.coordinates(this.maximum());
pull=this.settings.pullDrag ?(-1 * delta.x) / 5:0;
stage.x=Math.max(Math.min(stage.x, minimum + pull), maximum + pull);
}
this._drag.stage.current=stage;
this.animate(stage.x);
};
Owl.prototype.onDragEnd=function(event){
var delta=this.difference(this._drag.pointer, this.pointer(event)),
stage=this._drag.stage.current,
direction,
isdeltax=delta.x > 0;
if(( isdeltax&&! this.settings.rtl)||(this.settings.rtl&&! isdeltax)){
direction='left';
}else{
direction='right';
}
$(document).off('.owl.core');
this.$element.removeClass(this.options.grabClass);
if(( delta.x!==0&&this.is('dragging'))||! this.is('valid')){
this.speed(this.settings.dragEndSpeed||this.settings.smartSpeed);
this.current(this.closest(stage.x, delta.x!==0 ? direction:this._drag.direction));
this.invalidate('position');
this.update();
this._drag.direction=direction;
if(Math.abs(delta.x) > 3||new Date().getTime() - this._drag.time > 300){
this._drag.target.one('click.owl.core', function(){
return false;
});
}}
if(! this.is('dragging')){
return;
}
this.leave('dragging');
this.trigger('dragged');
};
Owl.prototype.closest=function(coordinate, direction){
var position=-1,
pull=30,
width=this.width(),
coordinates=this.coordinates();
if(! this.settings.freeDrag){
$.each(coordinates,
$.proxy(function(index, value){
if(direction==='left'&&coordinate > value - pull&&coordinate < value + pull){
position=index;
}else if(direction==='right'&&coordinate > value - width - pull&&coordinate < value - width + pull){
position=index + 1;
}else if(this.op(coordinate, '<', value)&&this.op(coordinate, '>', coordinates[ index + 1 ]!==undefined ? coordinates[ index + 1 ]:value - width)){
position=direction==='left' ? index + 1:index;
}
return position===-1;
}, this)
);
}
if(! this.settings.loop){
if(this.op(coordinate, '>', coordinates[ this.minimum() ])){
coordinate=this.minimum();
position=coordinate;
}else if(this.op(coordinate, '<', coordinates[ this.maximum() ])){
coordinate=this.maximum();
position=coordinate;
}}
return position;
};
Owl.prototype.animate=function(coordinate){
var animate=this.speed() > 0;
if(this.is('animating')){
this.onTransitionEnd();
}
if(animate){
this.enter('animating');
this.trigger('translate');
}
if($.support.transform3d&&$.support.transition){
this.$stage.css({
transform: 'translate3d(' + coordinate + 'px,0px,0px)',
transition:(this.speed() / 1000) + 's' +(this.settings.slideTransition ? ' ' + this.settings.slideTransition:'')
});
}else if(animate){
this.$stage.animate({
left: coordinate + 'px'
},
this.speed(),
this.settings.fallbackEasing,
$.proxy(this.onTransitionEnd, this)
);
}else{
this.$stage.css({
left: coordinate + 'px'
});
}};
Owl.prototype.is=function(state){
return this._states.current[ state ]&&this._states.current[ state ] > 0;
};
Owl.prototype.current=function(position){
var event;
if(position===undefined){
return this._current;
}
if(this._items.length===0){
return undefined;
}
position=this.normalize(position);
if(this._current!==position){
event=this.trigger('change', { property: { name: 'position', value: position }});
if(event.data!==undefined){
position=this.normalize(event.data);
}
this._current=position;
this.invalidate('position');
this.trigger('changed', { property: { name: 'position', value: this._current }});
}
return this._current;
};
Owl.prototype.invalidate=function(part){
if(typeof part==='string'){
this._invalidated[ part ]=true;
if(this.is('valid')){
this.leave('valid');
}}
return $.map(this._invalidated, function(v, i){
return i;
});
};
Owl.prototype.reset=function(position){
position=this.normalize(position);
if(position===undefined){
return;
}
this._speed=0;
this._current=position;
this.suppress([ 'translate', 'translated' ]);
this.animate(this.coordinates(position));
this.release([ 'translate', 'translated' ]);
};
Owl.prototype.normalize=function(position, relative){
var n=this._items.length,
m=relative ? 0:this._clones.length;
if(! this.isNumeric(position)||n < 1){
position=undefined;
}else if(position < 0||position >=n + m){
position=(((( position -(m / 2)) % n) + n) % n) +(m / 2);
}
return position;
};
Owl.prototype.relative=function(position){
position -=this._clones.length / 2;
return this.normalize(position, true);
};
Owl.prototype.maximum=function(relative){
var settings=this.settings,
maximum=this._coordinates.length,
iterator,
reciprocalItemsWidth,
elementWidth;
if(settings.loop){
maximum=(this._clones.length / 2) + this._items.length - 1;
}else if(settings.autoWidth||settings.merge){
iterator=this._items.length;
if(iterator){
iterator=iterator - 1;
reciprocalItemsWidth=this._items[ iterator ].width();
elementWidth=this.$element.width();
while(iterator > 0){
reciprocalItemsWidth +=this._items[ iterator ].width() + this.settings.margin;
if(reciprocalItemsWidth > elementWidth){
break;
}
iterator=iterator - 1;
}}
maximum=iterator + 1;
}else if(settings.center){
maximum=this._items.length - 1;
}else{
maximum=this._items.length - settings.items;
}
if(relative){
maximum -=this._clones.length / 2;
}
return Math.max(maximum, 0);
};
Owl.prototype.minimum=function(relative){
return relative ? 0:this._clones.length / 2;
};
Owl.prototype.items=function(position){
if(position===undefined){
return this._items.slice();
}
position=this.normalize(position, true);
return this._items[ position ];
};
Owl.prototype.mergers=function(position){
if(position===undefined){
return this._mergers.slice();
}
position=this.normalize(position, true);
return this._mergers[ position ];
};
Owl.prototype.clones=function(position){
var odd=this._clones.length / 2,
even=odd + this._items.length,
map=function(index){
return index % 2===0 ? even +(index / 2):odd -(( index + 1) / 2);
};
if(position===undefined){
return $.map(this._clones, function(v, i){
return map(i);
});
}
return $.map(this._clones, function(v, i){
return v===position ? map(i):null;
});
};
Owl.prototype.speed=function(speed){
if(speed!==undefined){
this._speed=speed;
}
return this._speed;
};
Owl.prototype.coordinates=function(position){
var multiplier=1,
newPosition=position - 1,
coordinate;
if(position===undefined){
return $.map(this._coordinates,
$.proxy(function(scoordinate, index){
return this.coordinates(index);
}, this)
);
}
if(this.settings.center){
if(this.settings.rtl){
multiplier=-1;
newPosition=position + 1;
}
coordinate=this._coordinates[ position ];
coordinate +=(( this.width() - coordinate +(this._coordinates[ newPosition ]||0)) / 2) * multiplier;
}else{
coordinate=this._coordinates[ newPosition ]||0;
}
coordinate=Math.ceil(coordinate);
return coordinate;
};
Owl.prototype.duration=function(from, to, factor){
if(factor===0){
return 0;
}
return Math.min(Math.max(Math.abs(to - from), 1), 6) * Math.abs(factor||this.settings.smartSpeed);
};
Owl.prototype.to=function(position, speed){
var current=this.current(),
revert=null,
distance=position - this.relative(current),
direction=(distance > 0) -(distance < 0),
items=this._items.length,
minimum=this.minimum(),
maximum=this.maximum();
if(this.settings.loop){
if(! this.settings.rewind&&Math.abs(distance) > items / 2){
distance +=direction * -1 * items;
}
position=current + distance;
revert=(((( position - minimum) % items) + items) % items) + minimum;
if(revert!==position&&revert - distance <=maximum&&revert - distance > 0){
current=revert - distance;
position=revert;
this.reset(current);
}}else if(this.settings.rewind){
maximum +=1;
position=(( position % maximum) + maximum) % maximum;
}else{
position=Math.max(minimum, Math.min(maximum, position));
}
this.speed(this.duration(current, position, speed));
this.current(position);
if(this.isVisible()){
this.update();
}};
Owl.prototype.next=function(speed){
speed=speed||false;
this.to(this.relative(this.current()) + 1, speed);
};
Owl.prototype.prev=function(speed){
speed=speed||false;
this.to(this.relative(this.current()) - 1, speed);
};
Owl.prototype.onTransitionEnd=function(event){
if(event!==undefined){
event.stopPropagation();
if(( event.target||event.srcElement||event.originalTarget)!==this.$stage.get(0)){
return false;
}}
this.leave('animating');
this.trigger('translated');
};
Owl.prototype.viewport=function(){
var width;
if(this.options.responsiveBaseElement!==window){
width=$(this.options.responsiveBaseElement).width();
}else if(window.innerWidth){
width=window.innerWidth;
}else if(document.documentElement&&document.documentElement.clientWidth){
width=document.documentElement.clientWidth;
}else{
return width;
}
return width;
};
Owl.prototype.replace=function(content){
this.$stage.empty();
this._items=[];
if(content){
content=content instanceof window.jQuery ? content:$(content);
}
if(this.settings.nestedItemSelector){
content=content.find('.' + this.settings.nestedItemSelector);
}
content
.filter(function(){
return this.nodeType===1;
})
.each($.proxy(function(index, item){
item=this.prepare(item);
this.$stage.append(item);
this._items.push(item);
this._mergers.push(item.find('[data-merge]').addBack('[data-merge]').attr('data-merge') * 1||1);
}, this)
);
this.reset(this.isNumeric(this.settings.startPosition) ? this.settings.startPosition:0);
this.invalidate('items');
};
Owl.prototype.add=function(content, position){
var current=this.relative(this._current);
position=position===undefined ? this._items.length:this.normalize(position, true);
content=content instanceof window.jQuery ? content:$(content);
this.trigger('add', { content: content, position: position });
content=this.prepare(content);
if(this._items.length===0||position===this._items.length){
if(this._items.length===0){
this.$stage.append(content);
}
if(this._items.length!==0){
this._items[ position - 1 ].after(content);
}
this._items.push(content);
this._mergers.push(content.find('[data-merge]').addBack('[data-merge]').attr('data-merge') * 1||1);
}else{
this._items[ position ].before(content);
this._items.splice(position, 0, content);
this._mergers.splice(position, 0, content.find('[data-merge]').addBack('[data-merge]').attr('data-merge') * 1||1);
}
if(this._items[ current ]){
this.reset(this._items[ current ].index());
}
this.invalidate('items');
this.trigger('added', { content: content, position: position });
};
Owl.prototype.remove=function(position){
position=this.normalize(position, true);
if(position===undefined){
return;
}
this.trigger('remove', { content: this._items[ position ], position: position });
this._items[ position ].remove();
this._items.splice(position, 1);
this._mergers.splice(position, 1);
this.invalidate('items');
this.trigger('removed', { content: null, position: position });
};
Owl.prototype.preloadAutoWidthImages=function(images){
images.each($.proxy(function(i, element){
this.enter('pre-loading');
element=$(element);
$(new Image())
.one('load',
$.proxy(function(e){
element.attr('src', e.target.src);
element.css('opacity', 1);
this.leave('pre-loading');
if(! this.is('pre-loading')&&! this.is('initializing')){
this.refresh();
}}, this)
)
.attr('src', element.attr('src')||element.attr('data-src')||element.attr('data-src-retina'));
}, this)
);
};
Owl.prototype.destroy=function(){
this.$element.off('.owl.core');
this.$stage.off('.owl.core');
$(document).off('.owl.core');
if(this.settings.responsive!==false){
window.clearTimeout(this.resizeTimer);
this.off(window, 'resize', this._handlers.onThrottledResize);
}
$.map(this._plugins, function(value){
return value;
}).forEach(function(inst){
if(inst){
inst.destroy();
}});
this.$stage.children('.cloned').remove();
this.$stage.unwrap();
this.$stage.children().contents().unwrap();
this.$stage.children().unwrap();
this.$stage.remove();
this.$element
.removeClass(this.options.refreshClass)
.removeClass(this.options.loadingClass)
.removeClass(this.options.loadedClass)
.removeClass(this.options.rtlClass)
.removeClass(this.options.dragClass)
.removeClass(this.options.grabClass)
.attr('class', this.$element.attr('class').replace(new RegExp(this.options.responsiveClass + '-\\S+\\s', 'g'), ''))
.removeData('owl.carousel');
};
Owl.prototype.op=function(a, o, b){
var rtl=this.settings.rtl;
switch(o){
case '<':
return rtl ? a > b:a < b;
case '>':
return rtl ? a < b:a > b;
case '>=':
return rtl ? a <=b:a >=b;
case '<=':
return rtl ? a >=b:a <=b;
default:
break;
}};
Owl.prototype.on=function(element, event, listener, capture){
if(element.addEventListener){
element.addEventListener(event, listener, capture);
}else if(element.attachEvent){
element.attachEvent('on' + event, listener);
}};
Owl.prototype.off=function(element, event, listener, capture){
if(element.removeEventListener){
element.removeEventListener(event, listener, capture);
}else if(element.detachEvent){
element.detachEvent('on' + event, listener);
}};
Owl.prototype.trigger=function(name, data, namespace){
var status={
item: { count: this._items.length, index: this.current() }},
handler=$.camelCase($.grep([ 'on', name, namespace ], function(v){
return v;
})
.join('-')
.toLowerCase()
),
event=$.Event([ name, 'owl', namespace||'carousel' ].join('.').toLowerCase(), $.extend({ relatedTarget: this }, status, data));
if(! this._supress[ name ]){
$.each(this._plugins, function(sname, plugin){
if(plugin.onTrigger){
plugin.onTrigger(event);
}});
this.register({ type: Owl.Type.Event, name: name });
this.$element.trigger(event);
if(this.settings&&typeof this.settings[ handler ]==='function'){
this.settings[ handler ].call(this, event);
}}
return event;
};
Owl.prototype.enter=function(name){
$.each([ name ].concat(this._states.tags[ name ]||[]),
$.proxy(function(i, sname){
if(this._states.current[ sname ]===undefined){
this._states.current[ sname ]=0;
}
this._states.current[ sname ] +=1;
}, this)
);
};
Owl.prototype.leave=function(name){
$.each([ name ].concat(this._states.tags[ name ]||[]),
$.proxy(function(i, sname){
this._states.current[ sname ] -=1;
}, this)
);
};
Owl.prototype.register=function(object){
var _default;
if(object.type===Owl.Type.Event){
if(! $.event.special[ object.name ]){
$.event.special[ object.name ]={};}
if(! $.event.special[ object.name ].owl){
_default=$.event.special[ object.name ]._default;
$.event.special[ object.name ]._default=function(e){
if(_default&&_default.apply&&(! e.namespace||e.namespace.indexOf('owl')===-1)){
return _default.apply(this, arguments);
}
return e.namespace&&e.namespace.indexOf('owl') > -1;
};
$.event.special[ object.name ].owl=true;
}}else if(object.type===Owl.Type.State){
if(! this._states.tags[ object.name ]){
this._states.tags[ object.name ]=object.tags;
}else{
this._states.tags[ object.name ]=this._states.tags[ object.name ].concat(object.tags);
}
this._states.tags[ object.name ]=$.grep(this._states.tags[ object.name ],
$.proxy(function(tag, i){
return $.inArray(tag, this._states.tags[ object.name ])===i;
}, this)
);
}};
Owl.prototype.suppress=function(events){
$.each(events,
$.proxy(function(index, event){
this._supress[ event ]=true;
}, this)
);
};
Owl.prototype.release=function(events){
$.each(events,
$.proxy(function(index, event){
delete this._supress[ event ];
}, this)
);
};
Owl.prototype.pointer=function(event){
var result={ x: null, y: null };
event=event.originalEvent||event||window.event;
event=event.touches&&event.touches.length ? event.touches[ 0 ]:event.changedTouches&&event.changedTouches.length ? event.changedTouches[ 0 ]:event;
if(event.pageX){
result.x=event.pageX;
result.y=event.pageY;
}else{
result.x=event.clientX;
result.y=event.clientY;
}
return result;
};
Owl.prototype.isNumeric=function(number){
return ! isNaN(parseFloat(number));
};
Owl.prototype.difference=function(first, second){
return {
x: first.x - second.x,
y: first.y - second.y
};};
$.fn.tmowlCarousel=function(option){
var args=Array.prototype.slice.call(arguments, 1);
return this.each(function(){
var $this=$(this),
data=$this.data('owl.carousel');
if(! data){
data=new Owl(this, typeof option==='object'&&option);
$this.data('owl.carousel', data);
$.each([ 'next', 'prev', 'to', 'destroy', 'refresh', 'replace', 'add', 'remove' ], function(i, event){
data.register({ type: Owl.Type.Event, name: event });
data.$element.on(event + '.owl.carousel.core',
$.proxy(function(e){
if(e.namespace&&e.relatedTarget!==this){
this.suppress([ event ]);
data[ event ].apply(this, [].slice.call(arguments, 1));
this.release([ event ]);
}}, data)
);
});
}
if(typeof option==='string'&&option.charAt(0)!=='_'){
data[ option ].apply(data, args);
}});
};
$.fn.tmowlCarousel.Constructor=Owl;
}(window.Zepto||window.jQuery, window, document));
(function($, window){
'use strict';
var AutoRefresh=function(carousel){
this._core=carousel;
this._interval=null;
this._visible=null;
this._handlers={
'initialized.owl.carousel': $.proxy(function(e){
if(e.namespace&&this._core.settings.autoRefresh){
this.watch();
}}, this)
};
this._core.options=$.extend({}, AutoRefresh.Defaults, this._core.options);
this._core.$element.on(this._handlers);
};
AutoRefresh.Defaults={
autoRefresh: true,
autoRefreshInterval: 500
};
AutoRefresh.prototype.watch=function(){
if(this._interval){
return;
}
this._visible=this._core.isVisible();
this._interval=window.setInterval($.proxy(this.refresh, this), this._core.settings.autoRefreshInterval);
};
AutoRefresh.prototype.refresh=function(){
if(this._core.isVisible()===this._visible){
return;
}
this._visible = ! this._visible;
this._core.$element.toggleClass('owl-hidden', ! this._visible);
if(this._visible&&this._core.invalidate('width')){
this._core.refresh();
}};
AutoRefresh.prototype.destroy=function(){
var handler, property;
window.clearInterval(this._interval);
for(handler in this._handlers){
if(handler){
this._core.$element.off(handler, this._handlers[ handler ]);
}}
for(property in Object.getOwnPropertyNames(this)){
if(typeof this[ property ]!=='function'){
this[ property ]=null;
}}
};
$.fn.tmowlCarousel.Constructor.Plugins.AutoRefresh=AutoRefresh;
}(window.Zepto||window.jQuery, window));
(function($, window){
'use strict';
var Lazy=function(carousel){
this._core=carousel;
this._loaded=[];
this._handlers={
'initialized.owl.carousel change.owl.carousel resized.owl.carousel': $.proxy(function(e){
var settings;
var n;
var i;
var position;
var clones;
var load;
if(! e.namespace){
return;
}
if(! this._core.settings||! this._core.settings.lazyLoad){
return;
}
if(( e.property&&e.property.name==='position')||e.type==='initialized'){
settings=this._core.settings;
n=(settings.center&&Math.ceil(settings.items / 2))||settings.items;
i=(settings.center&&n * -1)||0;
position=(e.property&&e.property.value!==undefined ? e.property.value:this._core.current()) + i;
clones=this._core.clones().length;
load=$.proxy(function(ii, v){
this.load(v);
}, this);
if(settings.lazyLoadEager > 0){
n +=settings.lazyLoadEager;
if(settings.loop){
position -=settings.lazyLoadEager;
n +=1;
}}
while(i < n){
i +=1;
this.load(( clones / 2) + this._core.relative(position));
if(clones){
$.each(this._core.clones(this._core.relative(position)), load);
}
position +=1;
}}
}, this)
};
this._core.options=$.extend({}, Lazy.Defaults, this._core.options);
this._core.$element.on(this._handlers);
};
Lazy.Defaults={
lazyLoad: false,
lazyLoadEager: 0
};
Lazy.prototype.load=function(position){
var $item=this._core.$stage.children().eq(position),
$elements=$item&&$item.find('.owl-lazy');
if(! $elements||$.inArray($item.get(0), this._loaded) > -1){
return;
}
$elements.each($.proxy(function(index, element){
var $element=$(element),
image,
url=(window.devicePixelRatio > 1&&$element.attr('data-src-retina'))||$element.attr('data-src')||$element.attr('data-srcset');
this._core.trigger('load', { element: $element, url: url }, 'lazy');
if($element.is('img')){
$element
.one('load.owl.lazy',
$.proxy(function(){
$element.css('opacity', 1);
this._core.trigger('loaded', { element: $element, url: url }, 'lazy');
}, this)
)
.attr('src', url);
}else if($element.is('source')){
$element
.one('load.owl.lazy',
$.proxy(function(){
this._core.trigger('loaded', { element: $element, url: url }, 'lazy');
}, this)
)
.attr('srcset', url);
}else{
image=new Image();
image.onload=$.proxy(function(){
$element.css({
'background-image': 'url("' + url + '")',
opacity: '1'
});
this._core.trigger('loaded', { element: $element, url: url }, 'lazy');
}, this);
image.src=url;
}}, this)
);
this._loaded.push($item.get(0));
};
Lazy.prototype.destroy=function(){
var handler, property;
for(handler in this.handlers){
if(handler){
this._core.$element.off(handler, this.handlers[ handler ]);
}}
for(property in Object.getOwnPropertyNames(this)){
if(typeof this[ property ]!=='function'){
this[ property ]=null;
}}
};
$.fn.tmowlCarousel.Constructor.Plugins.Lazy=Lazy;
}(window.Zepto||window.jQuery, window));
(function($, window){
'use strict';
var AutoHeight=function(carousel){
var refThis=this;
this._core=carousel;
this._previousHeight=null;
this._handlers={
'initialized.owl.carousel refreshed.owl.carousel': $.proxy(function(e){
if(e.namespace&&this._core.settings.autoHeight){
this.update();
}}, this),
'changed.owl.carousel': $.proxy(function(e){
if(e.namespace&&this._core.settings.autoHeight&&e.property.name==='position'){
this.update();
}}, this),
'loaded.owl.lazy': $.proxy(function(e){
if(e.namespace&&this._core.settings.autoHeight&&e.element.closest('.' + this._core.settings.itemClass).index()===this._core.current()){
this.update();
}}, this)
};
this._core.options=$.extend({}, AutoHeight.Defaults, this._core.options);
this._core.$element.on(this._handlers);
this._intervalId=null;
$(window).on('load', function(){
if(refThis._core.settings.autoHeight){
refThis.update();
}});
$(window).on('resize', function(){
if(refThis._core.settings.autoHeight){
if(refThis._intervalId!==null){
clearTimeout(refThis._intervalId);
}
refThis._intervalId=setTimeout(function(){
refThis.update();
}, 250);
}});
};
AutoHeight.Defaults={
autoHeight: false,
autoHeightClass: 'owl-height'
};
AutoHeight.prototype.update=function(){
var start=this._core._current,
end=start + this._core.settings.items,
lazyLoadEnabled=this._core.settings.lazyLoad,
visible=this._core.$stage.children().toArray().slice(start, end),
heights=[],
maxheight=0;
$.each(visible, function(index, item){
heights.push($(item).height());
});
maxheight=Math.max.apply(null, heights);
if(maxheight <=1&&lazyLoadEnabled&&this._previousHeight){
maxheight=this._previousHeight;
}
this._previousHeight=maxheight;
this._core.$stage.parent().height(maxheight).addClass(this._core.settings.autoHeightClass);
};
AutoHeight.prototype.destroy=function(){
var handler, property;
for(handler in this._handlers){
if(handler){
this._core.$element.off(handler, this._handlers[ handler ]);
}}
for(property in Object.getOwnPropertyNames(this)){
if(typeof this[ property ]!=='function'){
this[ property ]=null;
}}
};
$.fn.tmowlCarousel.Constructor.Plugins.AutoHeight=AutoHeight;
}(window.Zepto||window.jQuery));
(function($, window, document){
'use strict';
var Video=function(carousel){
this._core=carousel;
this._videos={};
this._playing=null;
this._handlers={
'initialized.owl.carousel': $.proxy(function(e){
if(e.namespace){
this._core.register({ type: 'state', name: 'playing', tags: [ 'interacting' ] });
}}, this),
'resize.owl.carousel': $.proxy(function(e){
if(e.namespace&&this._core.settings.video&&this.isInFullScreen()){
e.preventDefault();
}}, this),
'refreshed.owl.carousel': $.proxy(function(e){
if(e.namespace&&this._core.is('resizing')){
this._core.$stage.find('.cloned .owl-video-frame').remove();
}}, this),
'changed.owl.carousel': $.proxy(function(e){
if(e.namespace&&e.property.name==='position'&&this._playing){
this.stop();
}}, this),
'prepared.owl.carousel': $.proxy(function(e){
var $element;
if(! e.namespace){
return;
}
$element=$(e.content).find('.owl-video');
if($element.length){
$element.css('display', 'none');
this.fetch($element, $(e.content));
}}, this)
};
this._core.options=$.extend({}, Video.Defaults, this._core.options);
this._core.$element.on(this._handlers);
this._core.$element.on('click.owl.video',
'.owl-video-play-icon',
$.proxy(function(e){
this.play(e);
}, this)
);
};
Video.Defaults={
video: false,
videoHeight: false,
videoWidth: false
};
Video.prototype.fetch=function(target, item){
var type=(function(){
if(target.attr('data-vimeo-id')){
return 'vimeo';
}else if(target.attr('data-vzaar-id')){
return 'vzaar';
}
return 'youtube';
}()),
id=target.attr('data-vimeo-id')||target.attr('data-youtube-id')||target.attr('data-vzaar-id'),
width=target.attr('data-width')||this._core.settings.videoWidth,
height=target.attr('data-height')||this._core.settings.videoHeight,
url=target.attr('href');
if(url){
id=url.match(/(http:|https:|)\/\/(player.|www.|app.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com|be\-nocookie\.com)|vzaar\.com)\/(video\/|videos\/|embed\/|channels\/.+\/|groups\/.+\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/
);
if(id[ 3 ].indexOf('youtu') > -1){
type='youtube';
}else if(id[ 3 ].indexOf('vimeo') > -1){
type='vimeo';
}else if(id[ 3 ].indexOf('vzaar') > -1){
type='vzaar';
}else{
throw new Error('Video URL not supported.');
}
id=id[ 6 ];
}else{
throw new Error('Missing video URL.');
}
this._videos[ url ]={
type: type,
id: id,
width: width,
height: height
};
item.attr('data-video', url);
this.thumbnail(target, this._videos[ url ]);
};
Video.prototype.thumbnail=function(target, video){
var tnLink,
icon,
path,
dimensions=video.width&&video.height ? 'width:' + video.width + 'px;height:' + video.height + 'px;':'',
customTn=target.find('img'),
srcType='src',
lazyClass='',
settings=this._core.settings,
create=function(thispath){
icon='<div class="owl-video-play-icon"></div>';
if(settings.lazyLoad){
tnLink=$('<div/>', {
class: 'owl-video-tn ' + lazyClass,
srcType: thispath
});
}else{
tnLink=$('<div/>', {
class: 'owl-video-tn',
style: 'opacity:1;background-image:url(' + thispath + ')'
});
}
target.after(tnLink);
target.after(icon);
};
target.wrap($('<div/>', {
class: 'owl-video-wrapper',
style: dimensions
})
);
if(this._core.settings.lazyLoad){
srcType='data-src';
lazyClass='owl-lazy';
}
if(customTn.length){
create(customTn.attr(srcType));
customTn.remove();
return false;
}
if(video.type==='youtube'){
path='//img.youtube.com/vi/' + video.id + '/hqdefault.jpg';
create(path);
}else if(video.type==='vimeo'){
$.ajax({
type: 'GET',
url: '//vimeo.com/api/v2/video/' + video.id + '.json',
jsonp: 'callback',
dataType: 'jsonp',
success: function(data){
path=data[ 0 ].thumbnail_large;
create(path);
}});
}else if(video.type==='vzaar'){
$.ajax({
type: 'GET',
url: '//vzaar.com/api/videos/' + video.id + '.json',
jsonp: 'callback',
dataType: 'jsonp',
success: function(data){
path=data.framegrab_url;
create(path);
}});
}};
Video.prototype.stop=function(){
this._core.trigger('stop', null, 'video');
this._playing.find('.owl-video-frame').remove();
this._playing.removeClass('owl-video-playing');
this._playing=null;
this._core.leave('playing');
this._core.trigger('stopped', null, 'video');
};
Video.prototype.play=function(event){
var target=$(event.target),
item=target.closest('.' + this._core.settings.itemClass),
video=this._videos[ item.attr('data-video') ],
width=video.width||'100%',
height=video.height||this._core.$stage.height(),
html;
if(this._playing){
return;
}
this._core.enter('playing');
this._core.trigger('play', null, 'video');
item=this._core.items(this._core.relative(item.index()));
this._core.reset(item.index());
html=$('<iframe frameborder="0" allowfullscreen mozallowfullscreen webkitAllowFullScreen ></iframe>');
html.attr('height', height);
html.attr('width', width);
if(video.type==='youtube'){
html.attr('src', '//www.youtube.com/embed/' + video.id + '?autoplay=1&rel=0&v=' + video.id);
}else if(video.type==='vimeo'){
html.attr('src', '//player.vimeo.com/video/' + video.id + '?autoplay=1');
}else if(video.type==='vzaar'){
html.attr('src', '//view.vzaar.com/' + video.id + '/player?autoplay=true');
}
$(html).wrap('<div class="owl-video-frame" />').insertAfter(item.find('.owl-video'));
this._playing=item.addClass('owl-video-playing');
};
Video.prototype.isInFullScreen=function(){
var element=document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement;
return element&&$(element).parent().hasClass('owl-video-frame');
};
Video.prototype.destroy=function(){
var handler, property;
this._core.$element.off('click.owl.video');
for(handler in this._handlers){
if(handler){
this._core.$element.off(handler, this._handlers[ handler ]);
}}
for(property in Object.getOwnPropertyNames(this)){
if(typeof this[ property ]!=='function'){
this[ property ]=null;
}}
};
$.fn.tmowlCarousel.Constructor.Plugins.Video=Video;
}(window.Zepto||window.jQuery, window, document));
(function($){
'use strict';
var Animate=function(scope){
this.core=scope;
this.core.options=$.extend({}, Animate.Defaults, this.core.options);
this.swapping=true;
this.previous=undefined;
this.next=undefined;
this.handlers={
'change.owl.carousel': $.proxy(function(e){
if(e.namespace&&e.property.name==='position'){
this.previous=this.core.current();
this.next=e.property.value;
}}, this),
'drag.owl.carousel dragged.owl.carousel translated.owl.carousel': $.proxy(function(e){
if(e.namespace){
this.swapping=e.type==='translated';
}}, this),
'translate.owl.carousel': $.proxy(function(e){
if(e.namespace&&this.swapping&&(this.core.options.animateOut||this.core.options.animateIn)){
this.swap();
}}, this)
};
this.core.$element.on(this.handlers);
};
Animate.Defaults={
animateOut: false,
animateIn: false
};
Animate.prototype.swap=function(){
var left, clear, previous, next, incoming, outgoing;
if(this.core.settings.items!==1){
return;
}
if(! $.support.animation||! $.support.transition){
return;
}
this.core.speed(0);
clear=$.proxy(this.clear, this);
previous=this.core.$stage.children().eq(this.previous);
next=this.core.$stage.children().eq(this.next);
incoming=this.core.settings.animateIn;
outgoing=this.core.settings.animateOut;
if(this.core.current()===this.previous){
return;
}
if(outgoing){
left=this.core.coordinates(this.previous) - this.core.coordinates(this.next);
previous
.one($.support.animation.end, clear)
.css({ left: left + 'px' })
.addClass('animated owl-animated-out')
.addClass(outgoing);
}
if(incoming){
next.one($.support.animation.end, clear).addClass('animated owl-animated-in').addClass(incoming);
}};
Animate.prototype.clear=function(e){
$(e.target).css({ left: '' }).removeClass('animated owl-animated-out owl-animated-in').removeClass(this.core.settings.animateIn).removeClass(this.core.settings.animateOut);
this.core.onTransitionEnd();
};
Animate.prototype.destroy=function(){
var handler, property;
for(handler in this.handlers){
if(handler){
this.core.$element.off(handler, this.handlers[ handler ]);
}}
for(property in Object.getOwnPropertyNames(this)){
if(typeof this[ property ]!=='function'){
this[ property ]=null;
}}
};
$.fn.tmowlCarousel.Constructor.Plugins.Animate=Animate;
}(window.Zepto||window.jQuery));
(function($, window, document){
'use strict';
var Autoplay=function(carousel){
this._core=carousel;
this._call=null;
this._time=0;
this._timeout=0;
this._paused=true;
this._handlers={
'changed.owl.carousel': $.proxy(function(e){
if(e.namespace&&e.property.name==='settings'){
if(this._core.settings.autoplay){
this.play();
}else{
this.stop();
}}else if(e.namespace&&e.property.name==='position'&&this._paused){
this._time=0;
}}, this),
'initialized.owl.carousel': $.proxy(function(e){
if(e.namespace&&this._core.settings.autoplay){
this.play();
}}, this),
'play.owl.autoplay': $.proxy(function(e, t, s){
if(e.namespace){
this.play(t, s);
}}, this),
'stop.owl.autoplay': $.proxy(function(e){
if(e.namespace){
this.stop();
}}, this),
'mouseover.owl.autoplay': $.proxy(function(){
if(this._core.settings.autoplayHoverPause&&this._core.is('rotating')){
this.pause();
}}, this),
'mouseleave.owl.autoplay': $.proxy(function(){
if(this._core.settings.autoplayHoverPause&&this._core.is('rotating')){
this.play();
}}, this),
'touchstart.owl.core': $.proxy(function(){
if(this._core.settings.autoplayHoverPause&&this._core.is('rotating')){
this.pause();
}}, this),
'touchend.owl.core': $.proxy(function(){
if(this._core.settings.autoplayHoverPause){
this.play();
}}, this)
};
this._core.$element.on(this._handlers);
this._core.options=$.extend({}, Autoplay.Defaults, this._core.options);
};
Autoplay.Defaults={
autoplay: false,
autoplayTimeout: 5000,
autoplayHoverPause: false,
autoplaySpeed: false
};
Autoplay.prototype._next=function(speed){
this._call=window.setTimeout($.proxy(this._next, this, speed),(this._timeout *(Math.round(this.read() / this._timeout) + 1)) - this.read());
if(this._core.is('interacting')||document.hidden){
return;
}
this._core.next(speed||this._core.settings.autoplaySpeed);
};
Autoplay.prototype.read=function(){
return new Date().getTime() - this._time;
};
Autoplay.prototype.play=function(timeout, speed){
var elapsed;
if(! this._core.is('rotating')){
this._core.enter('rotating');
}
timeout=timeout||this._core.settings.autoplayTimeout;
elapsed=Math.min(this._time %(this._timeout||timeout), timeout);
if(this._paused){
this._time=this.read();
this._paused=false;
}else{
window.clearTimeout(this._call);
}
this._time +=(this.read() % timeout) - elapsed;
this._timeout=timeout;
this._call=window.setTimeout($.proxy(this._next, this, speed), timeout - elapsed);
};
Autoplay.prototype.stop=function(){
if(this._core.is('rotating')){
this._time=0;
this._paused=true;
window.clearTimeout(this._call);
this._core.leave('rotating');
}};
Autoplay.prototype.pause=function(){
if(this._core.is('rotating')&&! this._paused){
this._time=this.read();
this._paused=true;
window.clearTimeout(this._call);
}};
Autoplay.prototype.destroy=function(){
var handler, property;
this.stop();
for(handler in this._handlers){
if(handler){
this._core.$element.off(handler, this._handlers[ handler ]);
}}
for(property in Object.getOwnPropertyNames(this)){
if(typeof this[ property ]!=='function'){
this[ property ]=null;
}}
};
$.fn.tmowlCarousel.Constructor.Plugins.autoplay=Autoplay;
}(window.Zepto||window.jQuery, window, document));
(function($){
'use strict';
var Navigation=function(carousel){
this._core=carousel;
this._initialized=false;
this._pages=[];
this._controls={};
this._templates=[];
this.$element=this._core.$element;
this._overrides={
next: this._core.next,
prev: this._core.prev,
to: this._core.to
};
this._handlers={
'prepared.owl.carousel': $.proxy(function(e){
if(e.namespace&&this._core.settings.dotsData){
this._templates.push('<div class="' + this._core.settings.dotClass + '">' + $(e.content).find('[data-dot]').addBack('[data-dot]').attr('data-dot') + '</div>');
}}, this),
'added.owl.carousel': $.proxy(function(e){
if(e.namespace&&this._core.settings.dotsData){
this._templates.splice(e.position, 0, this._templates.pop());
}}, this),
'remove.owl.carousel': $.proxy(function(e){
if(e.namespace&&this._core.settings.dotsData){
this._templates.splice(e.position, 1);
}}, this),
'changed.owl.carousel': $.proxy(function(e){
if(e.namespace&&e.property.name==='position'){
this.draw();
}}, this),
'initialized.owl.carousel': $.proxy(function(e){
if(e.namespace&&! this._initialized){
this._core.trigger('initialize', null, 'navigation');
this.initialize();
this.update();
this.draw();
this._initialized=true;
this._core.trigger('initialized', null, 'navigation');
}}, this),
'refreshed.owl.carousel': $.proxy(function(e){
if(e.namespace&&this._initialized){
this._core.trigger('refresh', null, 'navigation');
this.update();
this.draw();
this._core.trigger('refreshed', null, 'navigation');
}}, this)
};
this._core.options=$.extend({}, Navigation.Defaults, this._core.options);
this.$element.on(this._handlers);
};
Navigation.Defaults={
nav: false,
navText: [ '<span aria-label="' + 'Previous' + '">&#x2039;</span>', '<span aria-label="' + 'Next' + '">&#x203a;</span>' ],
navSpeed: false,
navElement: 'button type="button" role="presentation"',
navContainer: false,
navContainerClass: 'owl-nav',
navClass: [ 'owl-prev', 'owl-next' ],
slideBy: 1,
dotClass: 'owl-dot',
dotsClass: 'owl-dots',
dots: true,
dotsEach: false,
dotsData: false,
dotsSpeed: false,
dotsContainer: false
};
Navigation.prototype.initialize=function(){
var override,
settings=this._core.settings;
this._controls.$relative=(settings.navContainer ? $(settings.navContainer):$('<div>').addClass(settings.navContainerClass).appendTo(this.$element)).addClass('disabled');
this._controls.$previous=$('<' + settings.navElement + '>')
.addClass(settings.navClass[ 0 ])
.html(settings.navText[ 0 ])
.prependTo(this._controls.$relative)
.on('click',
$.proxy(function(){
this.prev(settings.navSpeed);
}, this)
);
this._controls.$next=$('<' + settings.navElement + '>')
.addClass(settings.navClass[ 1 ])
.html(settings.navText[ 1 ])
.appendTo(this._controls.$relative)
.on('click',
$.proxy(function(){
this.next(settings.navSpeed);
}, this)
);
if(! settings.dotsData){
this._templates=[ $('<button role="button">').addClass(settings.dotClass).append($('<span>')).prop('outerHTML') ];
}
this._controls.$absolute=(settings.dotsContainer ? $(settings.dotsContainer):$('<div>').addClass(settings.dotsClass).appendTo(this.$element)).addClass('disabled');
this._controls.$absolute.on('click',
'button',
$.proxy(function(e){
var index=$(e.target).parent().is(this._controls.$absolute) ? $(e.target).index():$(e.target).parent().index();
e.preventDefault();
this.to(index, settings.dotsSpeed);
}, this)
);
/*$el.on('focusin', function(){
$(document).off(".carousel");
$(document).on('keydown.carousel', function(e){
if(e.keyCode==37){
$el.trigger('prev.owl')
}
if(e.keyCode==39){
$el.trigger('next.owl')
}});
});*/
for(override in this._overrides){
if(override){
this._core[ override ]=$.proxy(this[ override ], this);
}}
};
Navigation.prototype.destroy=function(){
var handler, control, property, override, settings;
settings=this._core.settings;
for(handler in this._handlers){
if(handler){
this.$element.off(handler, this._handlers[ handler ]);
}}
for(control in this._controls){
if(control==='$relative'&&settings.navContainer){
this._controls[ control ].html('');
}else{
this._controls[ control ].remove();
}}
for(override in this.overides){
if(override){
this._core[ override ]=this._overrides[ override ];
}}
for(property in Object.getOwnPropertyNames(this)){
if(typeof this[ property ]!=='function'){
this[ property ]=null;
}}
};
Navigation.prototype.update=function(){
var i,
j,
lower=this._core.clones().length / 2,
upper=lower + this._core.items().length,
maximum=this._core.maximum(true),
settings=this._core.settings,
size=settings.center||settings.autoWidth||settings.dotsData ? 1:settings.dotsEach||settings.items;
if(settings.slideBy!=='page'){
settings.slideBy=Math.min(settings.slideBy, settings.items);
}
if(settings.dots||settings.slideBy==='page'){
this._pages=[];
for(i=lower, j=0; i < upper; i +=1){
if(j >=size||j===0){
this._pages.push({
start: Math.min(maximum, i - lower),
end: i - lower + size - 1
});
if(Math.min(maximum, i - lower)===maximum){
break;
}
j=0;
}
j +=this._core.mergers(this._core.relative(i));
}}
};
Navigation.prototype.draw=function(){
var difference,
settings=this._core.settings,
disabled=this._core.items().length <=settings.items,
index=this._core.relative(this._core.current()),
loop=settings.loop||settings.rewind;
this._controls.$relative.toggleClass('disabled', ! settings.nav||disabled);
if(settings.nav){
this._controls.$previous.toggleClass('disabled', ! loop&&index <=this._core.minimum(true));
this._controls.$next.toggleClass('disabled', ! loop&&index >=this._core.maximum(true));
}
this._controls.$absolute.toggleClass('disabled', ! settings.dots||disabled);
if(settings.dots){
difference=this._pages.length - this._controls.$absolute.children().length;
if(settings.dotsData&&difference!==0){
this._controls.$absolute.html(this._templates.join(''));
}else if(difference > 0){
this._controls.$absolute.append(new Array(difference + 1).join(this._templates[ 0 ]));
}else if(difference < 0){
this._controls.$absolute.children().slice(difference).remove();
}
this._controls.$absolute.find('.active').removeClass('active');
this._controls.$absolute.children().eq($.inArray(this.current(), this._pages)).addClass('active');
}};
Navigation.prototype.onTrigger=function(event){
var settings=this._core.settings;
event.page={
index: $.inArray(this.current(), this._pages),
count: this._pages.length,
size: settings&&(settings.center||settings.autoWidth||settings.dotsData ? 1:settings.dotsEach||settings.items)
};};
Navigation.prototype.current=function(){
var current=this._core.relative(this._core.current());
return $.grep(this._pages,
$.proxy(function(page){
return page.start <=current&&page.end >=current;
}, this)
).pop();
};
Navigation.prototype.getPosition=function(successor){
var position,
length,
settings=this._core.settings;
if(settings.slideBy==='page'){
position=$.inArray(this.current(), this._pages);
length=this._pages.length;
if(successor){
position=position + 1;
}else{
position=position - 1;
}
position=this._pages[(( position % length) + length) % length ].start;
}else{
position=this._core.relative(this._core.current());
length=this._core.items().length;
if(successor){
position +=settings.slideBy;
}else{
position -=settings.slideBy;
}}
return position;
};
Navigation.prototype.next=function(speed){
$.proxy(this._overrides.to, this._core)(this.getPosition(true), speed);
};
Navigation.prototype.prev=function(speed){
$.proxy(this._overrides.to, this._core)(this.getPosition(false), speed);
};
Navigation.prototype.to=function(position, speed, standard){
var length;
if(! standard&&this._pages.length){
length=this._pages.length;
$.proxy(this._overrides.to, this._core)(this._pages[(( position % length) + length) % length ].start, speed);
}else{
$.proxy(this._overrides.to, this._core)(position, speed);
}};
$.fn.tmowlCarousel.Constructor.Plugins.Navigation=Navigation;
}(window.Zepto||window.jQuery));
(function($, window){
'use strict';
var Hash=function(carousel){
this._core=carousel;
this._hashes={};
this.$element=this._core.$element;
this._handlers={
'initialized.owl.carousel': $.proxy(function(e){
if(e.namespace&&this._core.settings.startPosition==='URLHash'){
$(window).trigger('hashchange.owl.navigation');
}}, this),
'prepared.owl.carousel': $.proxy(function(e){
var hash;
if(e.namespace){
hash=$(e.content).find('[data-hash]').addBack('[data-hash]').attr('data-hash');
if(! hash){
return;
}
this._hashes[ hash ]=e.content;
}}, this),
'changed.owl.carousel': $.proxy(function(e){
var current;
var hash;
if(e.namespace&&e.property.name==='position'){
current=this._core.items(this._core.relative(this._core.current()));
hash=$.map(this._hashes, function(item, thishash){
return item===current ? thishash:null;
}).join();
if(! hash||window.location.hash.slice(1)===hash){
return;
}
window.location.hash=hash;
}}, this)
};
this._core.options=$.extend({}, Hash.Defaults, this._core.options);
this.$element.on(this._handlers);
$(window).on('hashchange.owl.navigation',
$.proxy(function(){
var hash=window.location.hash.substring(1),
items=this._core.$stage.children(),
position=this._hashes[ hash ]&&items.index(this._hashes[ hash ]);
if(position===undefined||position===this._core.current()){
return;
}
this._core.to(this._core.relative(position), false, true);
}, this)
);
};
Hash.Defaults={
URLhashListener: false
};
Hash.prototype.destroy=function(){
var handler, property;
$(window).off('hashchange.owl.navigation');
for(handler in this._handlers){
if(handler){
this._core.$element.off(handler, this._handlers[ handler ]);
}}
for(property in Object.getOwnPropertyNames(this)){
if(typeof this[ property ]!=='function'){
this[ property ]=null;
}}
};
$.fn.tmowlCarousel.Constructor.Plugins.Hash=Hash;
}(window.Zepto||window.jQuery, window));
(function($){
'use strict';
var style=$('<support>').get(0).style,
prefixes='Webkit Moz O ms'.split(' '),
events={
transition: {
end: {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd',
transition: 'transitionend'
}},
animation: {
end: {
WebkitAnimation: 'webkitAnimationEnd',
MozAnimation: 'animationend',
OAnimation: 'oAnimationEnd',
animation: 'animationend'
}}
},
tests;
function test(property, thisprefixed){
var result=false,
upper=property.charAt(0).toUpperCase() + property.slice(1);
$.each(( property + ' ' + prefixes.join(upper + ' ') + upper).split(' '), function(i, thisproperty){
if(style[ thisproperty ]!==undefined){
result=thisprefixed ? thisproperty:true;
return false;
}});
return result;
}
function prefixed(property){
return test(property, true);
}
tests={
csstransforms: function(){
return !! test('transform');
},
csstransforms3d: function(){
return !! test('perspective');
},
csstransitions: function(){
return !! test('transition');
},
cssanimations: function(){
return !! test('animation');
}};
if(tests.csstransitions()){
$.support.transition=new String(prefixed('transition'));
$.support.transition.end=events.transition.end[ $.support.transition ];
}
if(tests.cssanimations()){
$.support.animation=new String(prefixed('animation'));
$.support.animation.end=events.animation.end[ $.support.animation ];
}
if(tests.csstransforms()){
$.support.transform=new String(prefixed('transform'));
$.support.transform3d=tests.csstransforms3d();
}}(window.Zepto||window.jQuery));
(function($){
'use strict';
var localStorage=$.epoAPI.util.getStorage('localStorage');
var confirm=window.confirm;
var Tabs=function(dom, options){
this.elements=$(dom);
this.last=[];
this.current=[];
this.enableEvents=true;
this.backup=[];
this.options=$.extend({}, $.fn.tcTabs.defaults, options);
if(this.elements.length > 0){
this.init();
return this;
}
return false;
};
Tabs.prototype={
constructor: Tabs,
set: function(options){
this.options=$.extend({}, this.options, options);
this.init(true);
},
addHeaderEvents: function(t, index, tc, header, theaderswrap, theaders, scrollLeftButton, scrollRightButton, state){
var additional_events='';
var ithis=this;
header.off('closetab.tmtabs').on('closetab.tmtabs', function(){
var $this=$(this);
var _tab=t.find($this.data('tab'));
$this.removeClass('closed open').addClass('closed');
$this
.find('.tm-arrow')
.removeClass(ithis.options.classdown + ' ' + ithis.options.classup)
.addClass(ithis.options.classdown);
if(ithis.options.useclasstohide){
_tab.addClass('tm-hide').removeClass('tm-show');
}else{
_tab.hide();
}
_tab.removeClass('tm-animated ' + ithis.options.animationclass);
$(window).trigger('tc-closetab.tmtabs', {
header: $this,
tab: _tab
});
});
header.off('opentab.tmtabs').on('opentab.tmtabs', function(){
var $this=$(this);
var _tab=t.find($this.data('tab'));
$this.removeClass('closed open').addClass('open');
$this
.find('.tm-arrow')
.removeClass(ithis.options.classdown + ' ' + ithis.options.classup)
.addClass(ithis.options.classup);
if(ithis.options.useclasstohide){
_tab.removeClass('tm-hide').addClass('tm-show');
}else{
_tab.show();
}
_tab.removeClass('tm-animated ' + ithis.options.animationclass).addClass('tm-animated ' + ithis.options.animationclass);
ithis.current[ index ]=$this.data('tab');
$(window).trigger('tc-opentab.tmtabs', {
header: $this,
tab: ithis.current[ index ],
table: _tab
});
ithis.scrollIntoView(t, $this, state);
});
if(ithis.options.showonhover===true||typeof ithis.options.showonhover==='function'){
additional_events=' mouseover';
}
header.off('keydown.tmtabs').on('keydown.tmtabs', function(e){
var $this=$(this);
var prevnext;
if(e.keyCode===13){
$this.trigger('click.tmtabs');
}
if(e.keyCode===40){
prevnext=$this.closest('.tm-box').next().find('.' + ithis.options.header);
}
if(e.keyCode===38){
prevnext=$this.closest('.tm-box').prev().find('.' + ithis.options.header);
}
if(prevnext&&prevnext.length){
$this.trigger('blur');
prevnext.trigger(' focus').trigger('click');
e.preventDefault();
}});
header.off('click.tmtabs').on('click.tmtabs' + additional_events, function(e){
var $this=$(this);
e.preventDefault();
if(e.type==='mouseover'&&typeof ithis.options.showonhover==='function'&&! ithis.options.showonhover.call()){
return;
}
if(ithis.current[ index ]===$this.data('tab')){
$(window).trigger('tc-isopentab.tmtabs', {
header: $this,
tab: ithis.current[ index ],
table: t.find(ithis.current[ index ])
});
return;
}
if(ithis.last[ index ]){
$(ithis.last[ index ]).trigger('closetab.tmtabs');
}
$this.trigger('opentab.tmtabs');
ithis.last[ index ]=$this;
if(localStorage){
localStorage.setItem('tmadmintab-' + tc, $this.attr(ithis.options.dataopenattribute));
}
$(window).trigger('tc-tmtabs-clicked', {
tc: tc,
options: ithis.options,
header: $this,
tab: ithis.current[ index ],
table: t.find(ithis.current[ index ])
});
});
if(this.options.deletebutton){
header.append(this.options.deletebuttonhtml);
header
.find('.' + this.options.deleteheader)
.off('click.tmtabs')
.on('click.tmtabs', function(e){
var $t=$(this);
var $tmbox=$t.closest('.tm-box');
var $header=$tmbox.find('.' + ithis.options.header);
var $tab=t.find('.' + $header.attr(ithis.options.dataattribute));
e.stopPropagation();
if(t.find('.' + ithis.options.headers + ' ' + '.' + ithis.options.header).length < 2){
return;
}
if(ithis.options.deleteconfirm){
if(! confirm(window.TMEPOGLOBALADMINJS.i18n_builder_delete)){
return;
}}
if(typeof ithis.options.beforedeletetab==='function'){
ithis.options.beforedeletetab.call(t, $t, $tab);
}
$tab.remove();
if($header.is('.open')){
if($tmbox.next().find('.' + ithis.options.header).is('.closed')){
$tmbox.next().find('.' + ithis.options.header).trigger('click.tmtabs');
}else if($tmbox.prev().find('.' + ithis.options.header).is('.closed')){
$tmbox.prev().find('.' + ithis.options.header).trigger('click.tmtabs');
}}
$tmbox.remove();
ithis.checkSize(theaderswrap, theaders, scrollLeftButton, scrollRightButton, state, true);
if(typeof ithis.options.afterdeletetab==='function'){
ithis.options.afterdeletetab.call(t);
}});
}else{
header.find('.' + this.options.deleteheader).remove();
}
if(this.options.editbutton){
header.append(ithis.options.editbuttonhtml);
header
.find('.' + ithis.options.editheader)
.off('click.tmtabs')
.on('click.tmtabs', function(event){
var $t;
var $tab;
if(ithis.enableEvents&&typeof ithis.options.oneditbutton==='function'){
event.stopPropagation();
$t=$(this);
$tab=t.find('.' + $t.closest('.tm-box').find('.' + ithis.options.header).attr(ithis.options.dataattribute));
ithis.options.oneditbutton.call(t, $t, $tab);
}});
}else{
header.find('.' + this.options.editheader).remove();
}},
initHeader: function(header, t, index, theaderswrap, theaders, scrollLeftButton, scrollRightButton, state){
var id;
var init_open=0;
var tc=t.attr('class');
header=$(header);
id='.' + header.attr(this.options.dataattribute);
header.data('tab', id);
if(this.options.useclasstohide){
t.find(id).addClass('tm-hide').removeClass('tm-show');
}else{
t.find(id).hide();
}
t.find(id).data('state', 'closed');
if(! init_open&&header.is('.open')){
header.removeClass('closed open').addClass('open').data('state', 'open');
header
.find('.tm-arrow')
.removeClass(this.options.classdown + ' ' + this.options.classup)
.addClass(this.options.classup);
if(this.options.useclasstohide){
t.find(id).removeClass('tm-hide').addClass('tm-show');
}else{
t.find(id).show();
}
t.find(id).data('state', 'open');
init_open=1;
this.current[ index ]=id;
this.last[ index ]=header;
}else{
header.removeClass('closed open').addClass('closed').data('state', 'closed');
}
this.addHeaderEvents(t, index, tc, header, theaderswrap, theaders, scrollLeftButton, scrollRightButton, state);
},
checkSize: function(theaderswrap, theaders, scrollLeftButton, scrollRightButton, state, setScrollWidth){
var panelWidth;
var openedHeader;
var props=[];
var hiddenParents=theaders.parents().addBack().not(':visible');
hiddenParents.each(function(){
var $this=$(this);
var styleDisplay=this.style.display;
var cssDisplay=$this.css('display');
var styleVisibility=this.style.visibility;
var cssVisibility=$this.css('visibility');
var obj;
var did=false;
obj={
styleDisplay: styleDisplay,
cssDisplay: cssDisplay,
styleVisibility: styleVisibility,
cssVisibility: cssVisibility,
display: null,
visibility: null,
element: $this
};
if(styleDisplay==='none'){
this.style.display='';
obj.display=true;
if($this.css('display')==='none'){
this.style.display='block';
}
did=true;
}
if(styleVisibility==='hidden'){
this.style.visibility='';
obj.visibility=true;
if($this.css('visibility')==='hidden'){
this.style.visibility='visible';
}
did=true;
}
if(did){
props.push(obj);
}});
panelWidth=Math.round(theaders.outerWidth());
if(theaders.is('.has-scroll-arrows')){
theaders.removeClass('.has-scroll-arrows');
panelWidth=Math.round(theaderswrap.outerWidth());
}
if(setScrollWidth){
openedHeader=theaders.find('.' + this.options.header + '.open');
if(openedHeader.length){
openedHeader.removeClass('open');
}
state.scrollWidth=theaders[ 0 ].scrollWidth;
if(openedHeader.length){
openedHeader.addClass('open');
}}
if(state.scrollWidth > panelWidth){
scrollRightButton.addClass('scroll-arrow-show');
scrollLeftButton.addClass('scroll-arrow-show');
theaders.addClass('has-scroll-arrows');
if(state.scrollWidth - panelWidth===theaders.scrollLeft()){
scrollRightButton.addClass('scroll-arrow-disabled scroll-arrow-right-disabled');
}else{
scrollRightButton.removeClass('scroll-arrow-disabled scroll-arrow-right-disabled');
}
if(theaders.scrollLeft()===0){
scrollLeftButton.addClass('scroll-arrow-disabled scroll-arrow-left-disabled');
}else{
scrollLeftButton.removeClass('scroll-arrow-disabled scroll-arrow-left-disabled');
}}else{
scrollRightButton.removeClass('scroll-arrow-show');
scrollLeftButton.removeClass('scroll-arrow-show');
theaders[ 0 ].scrollLeft=0;
theaders.removeClass('has-scroll-arrows');
}
props.forEach(function(o){
if(o.display){
o.element[ 0 ].style.display=o.styleDisplay;
}
if(o.visibility){
o.element[ 0 ].style.visibility=o.styleVisibility;
}});
},
scrollIntoView: function(t, header, state){
var left=state.scrollPos;
var theaders=t.find('.' + this.options.headers);
var scrollWidth=theaders.width();
if(theaders.is('.has-scroll-arrows')&&header&&typeof(header)!=='undefined'&&header.position()&&typeof(header.position())!=='undefined'){
if(header.position().left < 0){
state.scrollPos=Math.max(left + header.position().left + 1, 0);
theaders.animate({ scrollLeft:(state.scrollPos + 1) + 'px' }, this.options.scrollDuration);
}else if(( header.position().left + header.outerWidth()) > scrollWidth){
state.scrollPos=Math.min(left +(( header.position().left + header.outerWidth()) - scrollWidth), theaders[ 0 ].scrollWidth - theaders.outerWidth());
theaders.animate({ scrollLeft:(state.scrollPos - 1) + 'px' }, this.options.scrollDuration);
}}
},
initElement: function(t, index, state, uniqid){
var ithis=this;
var tc=t.attr('class');
var theaders;
var theaderswrap;
var scrollLeftButton;
var scrollRightButton;
var headers=t.find('.' + this.options.headers + ' ' + '.' + this.options.header);
var ohp=0;
var ohpid='';
var _selected_tab;
var vars={};
var initialIndex;
var pressHoldTimeout;
if(headers.length===0){
return;
}
theaders=t.find('.' + this.options.headers);
theaders.wrap('<div class="' + this.options.headersWrap + '"></div>');
theaderswrap=t.find('.' + this.options.headersWrap);
if(this.options.scroll){
theaderswrap.html('<div class="tc-scroll-left-arrow"></div>' + theaderswrap.html() + '<div class="tc-scroll-right-arrow"></div>');
headers=t.find('.' + this.options.headers + ' ' + '.' + this.options.header);
theaders=t.find('.' + this.options.headers);
scrollLeftButton=t.find('.tc-scroll-left-arrow');
scrollRightButton=t.find('.tc-scroll-right-arrow');
if(typeof $.fn.mousewheel==='function'){
theaders.mousewheel(function(event, delta){
if(scrollRightButton.css('display')!=='none'){
this.scrollLeft -=(delta * 30);
state.scrollPos=this.scrollLeft;
event.preventDefault();
}});
}
theaders.animate({ scrollLeft: state.scrollPos + 'px' }, 0);
this.checkSize(theaderswrap, theaders, scrollLeftButton, scrollRightButton, state, true);
$(window).off('resize.tmtabs' + uniqid).on('resize.tmtabs' + uniqid, function(){
ithis.checkSize(theaderswrap, theaders, scrollLeftButton, scrollRightButton, state, true);
});
t.off('refresh.tmtabs' + uniqid).on('refresh.tmtabs' + uniqid, function(){
ithis.checkSize(theaderswrap, theaders, scrollLeftButton, scrollRightButton, state, true);
});
$(function(){
ithis.checkSize(theaderswrap, theaders, scrollLeftButton, scrollRightButton, state, true);
});
scrollRightButton.off('mousedown.tmtabs mouseup.tmtabs mouseleave.tmtabs mouseover.tmtabs mouseout.tmtabs')
.on('mousedown.tmtabs', function(e){
var scrollRightFunc=function(){
var left=theaders.scrollLeft();
state.scrollPos=Math.min(left + ithis.options.scrollDistance, state.scrollWidth - theaders.outerWidth());
theaders.animate({
scrollLeft: state.scrollPos + 'px'
},
ithis.options.scrollDuration,
function(){
ithis.checkSize(theaderswrap, theaders, scrollLeftButton, scrollRightButton, state);
}
);
};
e.stopPropagation();
scrollRightFunc();
pressHoldTimeout=setInterval(function(){
scrollRightFunc();
}, ithis.options.scrollDuration);
}).on('mouseup.tmtabs mouseleave.tmtabs', function(){
clearInterval(pressHoldTimeout);
}).on('mouseover.tmtabs', function(){
$(this).addClass('scroll-arrow-over scroll-arrow-right-over');
}).on('mouseout.tmtabs', function(){
$(this).removeClass('scroll-arrow-over scroll-arrow-right-over');
});
scrollLeftButton.off('mousedown.tmtabs mouseup.tmtabs mouseleave.tmtabs mouseover.tmtabs mouseout.tmtabs')
.on('mousedown.tmtabs', function(e){
var scrollLeftFunc=function(){
var left=theaders.scrollLeft();
state.scrollPos=Math.max(left - ithis.options.scrollDistance, 0);
theaders.animate({
scrollLeft: state.scrollPos + 'px'
},
ithis.options.scrollDuration,
function(){
ithis.checkSize(theaderswrap, theaders, scrollLeftButton, scrollRightButton, state);
}
);
};
e.stopPropagation();
scrollLeftFunc();
pressHoldTimeout=setInterval(function(){
scrollLeftFunc();
}, ithis.options.scrollDuration);
}).on('mouseup.tmtabs mouseleave.tmtabs', function(){
clearInterval(pressHoldTimeout);
}).on('mouseover.tmtabs', function(){
$(this).addClass('scroll-arrow-over scroll-arrow-left-over');
}).on('mouseout.tmtabs', function(){
$(this).removeClass('scroll-arrow-over scroll-arrow-left-over');
});
}
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value){
vars[ key ]=value;
});
this.last[ index ]=false;
this.current[ index ]='';
t.data('tm-has-tmtabs', 1);
headers.each(function(i, header){
ithis.initHeader(header, t, index, theaderswrap, theaders, scrollLeftButton, scrollRightButton, state);
});
if(this.options.sortabletabs){
t.find('.' + this.options.headers + ':not(.section_elements ' + '.' + this.options.headers + ',.tm-settings-wrap ' + '.' + this.options.headers + ',.builder-element-wrap ' + '.' + this.options.headers + ')').sortable({
cursor: 'move',
items: '.tm-box:not(.tm-add-box)',
start: function(e, ui){
var $tab;
$tab=t.find('.' + ui.item.closest('.tm-box').find('.' + ithis.options.header).attr(ithis.options.dataattribute));
ohp=ui.item.index();
ohpid=ui.item.find('.' + ithis.options.header).attr(ithis.options.dataopenattribute);
initialIndex=$.tmEPOAdmin.find_index(true, $tab.find('.bitem').first());
if(typeof ithis.options.beforemovetab==='function'){
ithis.options.beforemovetab.call(this, ohp, $tab, initialIndex);
}
ithis.enableEvents=false;
},
stop: function(e, ui){
var original_item;
var new_index;
var replaced_item;
var $tab;
$tab=t.find('.' + ui.item.closest('.tm-box').find('.' + ithis.options.header).attr(ithis.options.dataattribute));
original_item=t.find('.' + ithis.options.slide + '.' + ohpid);
new_index=t
.find('.' + ithis.options.headers + ' ' + '.' + ithis.options.header + '[' + ithis.options.dataopenattribute + '=\'' + ohpid + '\']')
.parent()
.index();
replaced_item=t.find('.' + ithis.options.slide).eq(new_index);
if(new_index > ohp){
replaced_item.after(original_item);
}else if(new_index < ohp){
replaced_item.before(original_item);
}
if(typeof ithis.options.aftermovetab==='function'){
ithis.options.aftermovetab.call(this, new_index, ohp, $tab, initialIndex);
}
ithis.enableEvents=true;
},
cancel: '.tm-add-box',
forcePlaceholderSize: true,
revert: 200,
placeholder: 'tm-box pl',
tolerance: 'pointer'
});
}
if(this.options.addbutton){
theaderswrap.append(this.options.addbuttonhtml);
t.addClass('has-add-button').find('.' + this.options.addheader).off('click.tmtabs').on('click.tmtabs', function(e){
var allHeaders=t.find('.' + ithis.options.headers + ' ' + '.' + ithis.options.header);
var last_header=allHeaders.last();
var id=last_header.attr(ithis.options.dataattribute);
var last_tab=t.find('.' + id);
var new_header=last_header.tcClone().off('closetab.tmtabs opentab.tmtabs click.tmtabs');
var new_tab=last_tab.tcClone().empty();
var newid=ithis.options.slide + allHeaders.length;
e.preventDefault();
new_header
.html('<span class="tab-text">' +(t.find('.' + ithis.options.headers + ' ' + '.' + ithis.options.header).length + 1) + '</span>')
.removeClass('closed open')
.addClass('closed')
.data('tab', '.' + newid)
.data('state', 'closed')
.attr(ithis.options.dataattribute, newid);
new_tab.removeClass(id).addClass(newid);
if(ithis.options.useclasstohide){
new_tab.addClass('tm-hide').removeClass('.tm-show');
}else{
new_tab.hide();
}
new_tab.removeClass('tm-animated ' + ithis.options.animationclass);
last_header.closest('.tm-box').after(new_header);
new_header.wrap('<div class="tm-box"></div>');
ithis.addHeaderEvents(t, index, tc, new_header, theaderswrap, theaders, scrollLeftButton, scrollRightButton, state);
last_tab.after(new_tab);
if(ithis.options.scroll){
theaders.animate({
scrollLeft: new_header.width() + 'px'
},
ithis.options.scrollDuration,
function(){
ithis.checkSize(theaderswrap, theaders, scrollLeftButton, scrollRightButton, state, true);
}
);
}
if(typeof ithis.options.afteraddtab==='function'){
ithis.options.afteraddtab.call(this, new_header, new_tab);
}});
}else{
theaderswrap.find('.' + this.options.addheader).remove();
}
if(this.options.selectedtab==='auto'){
if(localStorage){
_selected_tab=localStorage.getItem('tmadmintab-' + tc);
}
if(vars.selected_tab!==undefined){
_selected_tab=vars.selected_tab;
}
if(vars.menu!==undefined){
_selected_tab=vars.menu;
}
if(_selected_tab===undefined||_selected_tab===null){
_selected_tab=t.find('.' + this.options.header).eq(0).attr(this.options.dataopenattribute);
}
if(! t.find('.' + this.options.header + '[' + this.options.dataopenattribute + '="' + _selected_tab + '"]').is(':visible')){
t.find('.' + this.options.header).eq(0).trigger('click.tmtabs');
}else{
t.find('.' + this.options.header + '[' + this.options.dataopenattribute + '="' + _selected_tab + '"]').trigger('click.tmtabs');
}}else if(this.options.selectedtab!==false){
_selected_tab=parseInt(this.options.selectedtab, 10);
t.find('.' + this.options.header + ':eq(' + _selected_tab + ')').trigger('click.tmtabs');
}},
init: function(nobackup){
var ithis=this;
this.elements.each(function(index){
var t=$(this);
var display;
var state={};
var backup=t.html();
if(! nobackup&&ithis.backup[ index ]){
t.html(ithis.backup[ index ]);
}else{
ithis.backup[ index ]=backup;
}
state.scrollPos=0;
state.scrollWidth=0;
display=t.css('display');
t.show();
ithis.initElement(t, index, state, $.epoAPI.math.uniqueid(''));
t.css('display', display);
});
}};
$.fn.tcTabs=function(option){
var methodReturn;
var targets=$(this);
var data=targets.data('tctabs');
var options;
var ret;
var args=$.makeArray(arguments);
args.splice(0, 1);
if(typeof option==='object'){
options=option;
}else{
options={};}
if(! data){
data=new Tabs(this, options);
targets.data('tctabs', data);
}
if(typeof option==='string'){
methodReturn=data[ option ].apply(data, args);
}
if(methodReturn===undefined){
ret=targets;
}else{
ret=methodReturn;
}
return ret;
};
$.fn.tcTabs.defaults={
headers: 'tm-tab-headers',
headersWrap: 'tc-tab-headers-wrap',
header: 'tab-header',
slide: 'tc-tab-slide',
classdown: 'tcfa-angle-down',
classup: 'tcfa-angle-up',
animationclass: 'appear',
dataattribute: 'data-id',
dataopenattribute: 'data-id',
selectedtab: 'auto',
showonhover: false,
useclasstohide: true,
sortabletabs: true,
addbutton: false,
addheader: 'tm-add-tab',
addbuttonhtml: '<div class="tm-add-tab"><span class="tmicon tcfa tcfa-plus"></span></div>',
afteraddtab: null,
beforemovetab: null,
aftermovetab: null,
deletebutton: false,
deletebuttonhtml: '<div class="tm-del-tab"><span class="tcfa tcfa-times"></span></div>',
deleteheader: 'tm-del-tab',
deleteconfirm: false,
beforedeletetab: null,
afterdeletetab: null,
editbutton: false,
editbuttonhtml: '<span class="tm-edit-tab"><span class="tcfa tcfa-edit"></span></span>',
editheader: 'tm-edit-tab',
oneditbutton: null,
scroll: true,
scrollDistance: 300,
scrollDuration: 300
};
$.fn.tcTabs.Constructor=Tabs;
$.fn.tmtabs=$.fn.tcTabs;
}(window.jQuery));
(function(Math){
'use strict';
var trimLeft=/^\s+/,
trimRight=/\s+$/,
tinyCounter=0,
mathRound=Math.round,
mathMin=Math.min,
mathMax=Math.max,
mathRandom=Math.random;
var names={
aliceblue: 'f0f8ff',
antiquewhite: 'faebd7',
aqua: '0ff',
aquamarine: '7fffd4',
azure: 'f0ffff',
beige: 'f5f5dc',
bisque: 'ffe4c4',
black: '000',
blanchedalmond: 'ffebcd',
blue: '00f',
blueviolet: '8a2be2',
brown: 'a52a2a',
burlywood: 'deb887',
burntsienna: 'ea7e5d',
cadetblue: '5f9ea0',
chartreuse: '7fff00',
chocolate: 'd2691e',
coral: 'ff7f50',
cornflowerblue: '6495ed',
cornsilk: 'fff8dc',
crimson: 'dc143c',
cyan: '0ff',
darkblue: '00008b',
darkcyan: '008b8b',
darkgoldenrod: 'b8860b',
darkgray: 'a9a9a9',
darkgreen: '006400',
darkgrey: 'a9a9a9',
darkkhaki: 'bdb76b',
darkmagenta: '8b008b',
darkolivegreen: '556b2f',
darkorange: 'ff8c00',
darkorchid: '9932cc',
darkred: '8b0000',
darksalmon: 'e9967a',
darkseagreen: '8fbc8f',
darkslateblue: '483d8b',
darkslategray: '2f4f4f',
darkslategrey: '2f4f4f',
darkturquoise: '00ced1',
darkviolet: '9400d3',
deeppink: 'ff1493',
deepskyblue: '00bfff',
dimgray: '696969',
dimgrey: '696969',
dodgerblue: '1e90ff',
firebrick: 'b22222',
floralwhite: 'fffaf0',
forestgreen: '228b22',
fuchsia: 'f0f',
gainsboro: 'dcdcdc',
ghostwhite: 'f8f8ff',
gold: 'ffd700',
goldenrod: 'daa520',
gray: '808080',
green: '008000',
greenyellow: 'adff2f',
grey: '808080',
honeydew: 'f0fff0',
hotpink: 'ff69b4',
indianred: 'cd5c5c',
indigo: '4b0082',
ivory: 'fffff0',
khaki: 'f0e68c',
lavender: 'e6e6fa',
lavenderblush: 'fff0f5',
lawngreen: '7cfc00',
lemonchiffon: 'fffacd',
lightblue: 'add8e6',
lightcoral: 'f08080',
lightcyan: 'e0ffff',
lightgoldenrodyellow: 'fafad2',
lightgray: 'd3d3d3',
lightgreen: '90ee90',
lightgrey: 'd3d3d3',
lightpink: 'ffb6c1',
lightsalmon: 'ffa07a',
lightseagreen: '20b2aa',
lightskyblue: '87cefa',
lightslategray: '789',
lightslategrey: '789',
lightsteelblue: 'b0c4de',
lightyellow: 'ffffe0',
lime: '0f0',
limegreen: '32cd32',
linen: 'faf0e6',
magenta: 'f0f',
maroon: '800000',
mediumaquamarine: '66cdaa',
mediumblue: '0000cd',
mediumorchid: 'ba55d3',
mediumpurple: '9370db',
mediumseagreen: '3cb371',
mediumslateblue: '7b68ee',
mediumspringgreen: '00fa9a',
mediumturquoise: '48d1cc',
mediumvioletred: 'c71585',
midnightblue: '191970',
mintcream: 'f5fffa',
mistyrose: 'ffe4e1',
moccasin: 'ffe4b5',
navajowhite: 'ffdead',
navy: '000080',
oldlace: 'fdf5e6',
olive: '808000',
olivedrab: '6b8e23',
orange: 'ffa500',
orangered: 'ff4500',
orchid: 'da70d6',
palegoldenrod: 'eee8aa',
palegreen: '98fb98',
paleturquoise: 'afeeee',
palevioletred: 'db7093',
papayawhip: 'ffefd5',
peachpuff: 'ffdab9',
peru: 'cd853f',
pink: 'ffc0cb',
plum: 'dda0dd',
powderblue: 'b0e0e6',
purple: '800080',
rebeccapurple: '663399',
red: 'f00',
rosybrown: 'bc8f8f',
royalblue: '4169e1',
saddlebrown: '8b4513',
salmon: 'fa8072',
sandybrown: 'f4a460',
seagreen: '2e8b57',
seashell: 'fff5ee',
sienna: 'a0522d',
silver: 'c0c0c0',
skyblue: '87ceeb',
slateblue: '6a5acd',
slategray: '708090',
slategrey: '708090',
snow: 'fffafa',
springgreen: '00ff7f',
steelblue: '4682b4',
tan: 'd2b48c',
teal: '008080',
thistle: 'd8bfd8',
tomato: 'ff6347',
turquoise: '40e0d0',
violet: 'ee82ee',
wheat: 'f5deb3',
white: 'fff',
whitesmoke: 'f5f5f5',
yellow: 'ff0',
yellowgreen: '9acd32'
};
var flip=function(o){
var flipped={};
var i;
for(i in o){
if(Object.prototype.hasOwnProperty.call(o, i)){
flipped[ o[ i ] ]=i;
}}
return flipped;
};
var hexNames=flip(names);
var matchers=(function(){
var CSS_INTEGER='[-\\+]?\\d+%?';
var CSS_NUMBER='[-\\+]?\\d*\\.\\d+%?';
var CSS_UNIT='(?:' + CSS_NUMBER + ')|(?:' + CSS_INTEGER + ')';
var PERMISSIVE_MATCH3='[\\s|\\(]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')\\s*\\)?';
var PERMISSIVE_MATCH4='[\\s|\\(]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')\\s*\\)?';
return {
CSS_UNIT: new RegExp(CSS_UNIT),
rgb: new RegExp('rgb' + PERMISSIVE_MATCH3),
rgba: new RegExp('rgba' + PERMISSIVE_MATCH4),
hsl: new RegExp('hsl' + PERMISSIVE_MATCH3),
hsla: new RegExp('hsla' + PERMISSIVE_MATCH4),
hsv: new RegExp('hsv' + PERMISSIVE_MATCH3),
hsva: new RegExp('hsva' + PERMISSIVE_MATCH4),
hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
};}());
function isValidCSSUnit(color){
return !! matchers.CSS_UNIT.exec(color);
}
function parseIntFromHex(val){
return parseInt(val, 16);
}
function convertHexToDecimal(h){
return parseIntFromHex(h) / 255;
}
function stringInputToObject(color){
var named=false;
var match;
color=color.replace(trimLeft, '').replace(trimRight, '').toLowerCase();
if(names[ color ]){
color=names[ color ];
named=true;
}else if(color==='transparent'){
return { r: 0, g: 0, b: 0, a: 0, format: 'name' };}
if(( match=matchers.rgb.exec(color))){
return { r: match[ 1 ], g: match[ 2 ], b: match[ 3 ] };}
if(( match=matchers.rgba.exec(color))){
return { r: match[ 1 ], g: match[ 2 ], b: match[ 3 ], a: match[ 4 ] };}
if(( match=matchers.hsl.exec(color))){
return { h: match[ 1 ], s: match[ 2 ], l: match[ 3 ] };}
if(( match=matchers.hsla.exec(color))){
return { h: match[ 1 ], s: match[ 2 ], l: match[ 3 ], a: match[ 4 ] };}
if(( match=matchers.hsv.exec(color))){
return { h: match[ 1 ], s: match[ 2 ], v: match[ 3 ] };}
if(( match=matchers.hsva.exec(color))){
return { h: match[ 1 ], s: match[ 2 ], v: match[ 3 ], a: match[ 4 ] };}
if(( match=matchers.hex8.exec(color))){
return {
r: parseIntFromHex(match[ 1 ]),
g: parseIntFromHex(match[ 2 ]),
b: parseIntFromHex(match[ 3 ]),
a: convertHexToDecimal(match[ 4 ]),
format: named ? 'name':'hex8'
};}
if(( match=matchers.hex6.exec(color))){
return {
r: parseIntFromHex(match[ 1 ]),
g: parseIntFromHex(match[ 2 ]),
b: parseIntFromHex(match[ 3 ]),
format: named ? 'name':'hex'
};}
if(( match=matchers.hex4.exec(color))){
return {
r: parseIntFromHex(match[ 1 ] + '' + match[ 1 ]),
g: parseIntFromHex(match[ 2 ] + '' + match[ 2 ]),
b: parseIntFromHex(match[ 3 ] + '' + match[ 3 ]),
a: convertHexToDecimal(match[ 4 ] + '' + match[ 4 ]),
format: named ? 'name':'hex8'
};}
if(( match=matchers.hex3.exec(color))){
return {
r: parseIntFromHex(match[ 1 ] + '' + match[ 1 ]),
g: parseIntFromHex(match[ 2 ] + '' + match[ 2 ]),
b: parseIntFromHex(match[ 3 ] + '' + match[ 3 ]),
format: named ? 'name':'hex'
};}
return false;
}
function validateWCAG2Parms(parms){
var level, size;
parms=parms||{ level: 'AA', size: 'small' };
level=(parms.level||'AA').toUpperCase();
size=(parms.size||'small').toLowerCase();
if(level!=='AA'&&level!=='AAA'){
level='AA';
}
if(size!=='small'&&size!=='large'){
size='small';
}
return { level: level, size: size };}
function boundAlpha(a){
a=parseFloat(a);
if(isNaN(a)||a < 0||a > 1){
a=1;
}
return a;
}
function isPercentage(n){
return typeof n==='string'&&n.indexOf('%')!==-1;
}
function isOnePointZero(n){
return typeof n==='string'&&n.indexOf('.')!==-1&&parseFloat(n)===1;
}
function bound01(n, max){
var processPercent;
if(isOnePointZero(n)){
n='100%';
}
processPercent=isPercentage(n);
n=mathMin(max, mathMax(0, parseFloat(n)));
if(processPercent){
n=parseInt(n * max, 10) / 100;
}
if(Math.abs(n - max) < 0.000001){
return 1;
}
return(n % max) / parseFloat(max);
}
function clamp01(val){
return mathMin(1, mathMax(0, val));
}
function pad2(c){
return c.length===1 ? '0' + c:'' + c;
}
function convertToPercentage(n){
if(n <=1){
n=(n * 100) + '%';
}
return n;
}
function convertDecimalToHex(d){
return Math.round(parseFloat(d) * 255).toString(16);
}
function rgbToRgb(r, g, b){
return {
r: bound01(r, 255) * 255,
g: bound01(g, 255) * 255,
b: bound01(b, 255) * 255
};}
function rgbToHsl(r, g, b){
var max;
var min;
var h;
var s;
var l;
var d;
r=bound01(r, 255);
g=bound01(g, 255);
b=bound01(b, 255);
max=mathMax(r, g, b);
min=mathMin(r, g, b);
l=(max + min) / 2;
if(max===min){
h=s = 0;
}else{
d=max - min;
s=l > 0.5 ? d /(2 - max - min):d /(max + min);
switch(max){
case r:
h=(( g - b) / d) +(g < b ? 6:0);
break;
case g:
h=(( b - r) / d) + 2;
break;
case b:
h=(( r - g) / d) + 4;
break;
}
h /=6;
}
return { h: h, s: s, l: l };}
function hslToRgb(h, s, l){
var r;
var g;
var b;
var q;
var p;
h=bound01(h, 360);
s=bound01(s, 100);
l=bound01(l, 100);
function hue2rgb(pp, qq, t){
if(t < 0){
t +=1;
}
if(t > 1){
t -=1;
}
if(t < 1 / 6){
return pp +(( qq - pp) * 6 * t);
}
if(t < 1 / 2){
return qq;
}
if(t < 2 / 3){
return pp +(( qq - pp) *(( 2 / 3) - t) * 6);
}
return pp;
}
if(s===0){
r=g = b=l;
}else{
q=l < 0.5 ? l *(1 + s):l + s -(l * s);
p=(2 * l) - q;
r=hue2rgb(p, q, h +(1 / 3));
g=hue2rgb(p, q, h);
b=hue2rgb(p, q, h -(1 / 3));
}
return { r: r * 255, g: g * 255, b: b * 255 };}
function rgbToHsv(r, g, b){
var max;
var min;
var h;
var s;
var v;
var d;
r=bound01(r, 255);
g=bound01(g, 255);
b=bound01(b, 255);
max=mathMax(r, g, b);
min=mathMin(r, g, b);
v=max;
d=max - min;
s=max===0 ? 0:d / max;
if(max===min){
h=0;
}else{
switch(max){
case r:
h=(( g - b) / d) +(g < b ? 6:0);
break;
case g:
h=(( b - r) / d) + 2;
break;
case b:
h=(( r - g) / d) + 4;
break;
}
h /=6;
}
return { h: h, s: s, v: v };}
function hsvToRgb(h, s, v){
var i;
var f;
var p;
var q;
var t;
var mod;
var r;
var g;
var b;
h=bound01(h, 360) * 6;
s=bound01(s, 100);
v=bound01(v, 100);
i=Math.floor(h);
f=h - i;
p=v *(1 - s);
q=v *(1 -(f * s));
t=v *(1 -(( 1 - f) * s));
mod=i % 6;
r=[ v, q, p, p, t, v ][ mod ];
g=[ t, v, v, q, p, p ][ mod ];
b=[ p, p, t, v, v, q ][ mod ];
return { r: r * 255, g: g * 255, b: b * 255 };}
function rgbToHex(r, g, b, allow3Char){
var hex=[ pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16)) ];
if(allow3Char&&hex[ 0 ].charAt(0)===hex[ 0 ].charAt(1)&&hex[ 1 ].charAt(0)===hex[ 1 ].charAt(1)&&hex[ 2 ].charAt(0)===hex[ 2 ].charAt(1)){
return hex[ 0 ].charAt(0) + hex[ 1 ].charAt(0) + hex[ 2 ].charAt(0);
}
return hex.join('');
}
function rgbaToHex(r, g, b, a, allow4Char){
var hex=[ pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16)), pad2(convertDecimalToHex(a)) ];
if(allow4Char&&hex[ 0 ].charAt(0)===hex[ 0 ].charAt(1)&&hex[ 1 ].charAt(0)===hex[ 1 ].charAt(1)&&hex[ 2 ].charAt(0)===hex[ 2 ].charAt(1)&&hex[ 3 ].charAt(0)===hex[ 3 ].charAt(1)){
return hex[ 0 ].charAt(0) + hex[ 1 ].charAt(0) + hex[ 2 ].charAt(0) + hex[ 3 ].charAt(0);
}
return hex.join('');
}
function rgbaToArgbHex(r, g, b, a){
var hex=[ pad2(convertDecimalToHex(a)), pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16)) ];
return hex.join('');
}
function inputToRGB(color){
var rgb={ r: 0, g: 0, b: 0 };
var a=1;
var s=null;
var v=null;
var l=null;
var ok=false;
var format=false;
if(typeof color==='string'){
color=stringInputToObject(color);
}
if(typeof color==='object'){
if(isValidCSSUnit(color.r)&&isValidCSSUnit(color.g)&&isValidCSSUnit(color.b)){
rgb=rgbToRgb(color.r, color.g, color.b);
ok=true;
format=String(color.r).substring(String(color.r).length - 1)==='%' ? 'prgb':'rgb';
}else if(isValidCSSUnit(color.h)&&isValidCSSUnit(color.s)&&isValidCSSUnit(color.v)){
s=convertToPercentage(color.s);
v=convertToPercentage(color.v);
rgb=hsvToRgb(color.h, s, v);
ok=true;
format='hsv';
}else if(isValidCSSUnit(color.h)&&isValidCSSUnit(color.s)&&isValidCSSUnit(color.l)){
s=convertToPercentage(color.s);
l=convertToPercentage(color.l);
rgb=hslToRgb(color.h, s, l);
ok=true;
format='hsl';
}
if(Object.prototype.hasOwnProperty.call(color, 'a')){
a=color.a;
}}
a=boundAlpha(a);
return {
ok: ok,
format: color.format||format,
r: mathMin(255, mathMax(rgb.r, 0)),
g: mathMin(255, mathMax(rgb.g, 0)),
b: mathMin(255, mathMax(rgb.b, 0)),
a: a
};}
function TinyColor(color, opts){
var rgb;
color=color ? color:'';
opts=opts||{};
if(color instanceof TinyColor){
return color;
}
if(!(this instanceof TinyColor)){
return new TinyColor(color, opts);
}
rgb=inputToRGB(color);
this._originalInput=color;
this._r=rgb.r;
this._g=rgb.g;
this._b=rgb.b;
this._a=rgb.a;
this._roundA=mathRound(100 * this._a) / 100;
if(opts.format){
this._format=opts.format;
}else{
this._format=rgb.format;
}
this._gradientType=opts.gradientType;
if(this._r < 1){
this._r=mathRound(this._r);
}
if(this._g < 1){
this._g=mathRound(this._g);
}
if(this._b < 1){
this._b=mathRound(this._b);
}
this._ok=rgb.ok;
tinyCounter=tinyCounter + 1;
this._tc_id=tinyCounter;
}
function newTinyColor(color, opts){
return new TinyColor(color, opts);
}
function desaturate(color, amount){
var hsl;
amount=amount===0 ? 0:amount||10;
hsl=newTinyColor(color).toHsl();
hsl.s -=amount / 100;
hsl.s=clamp01(hsl.s);
return newTinyColor(hsl);
}
function saturate(color, amount){
var hsl;
amount=amount===0 ? 0:amount||10;
hsl=newTinyColor(color).toHsl();
hsl.s +=amount / 100;
hsl.s=clamp01(hsl.s);
return newTinyColor(hsl);
}
function greyscale(color){
return newTinyColor(color).desaturate(100);
}
function lighten(color, amount){
var hsl;
amount=amount===0 ? 0:amount||10;
hsl=newTinyColor(color).toHsl();
hsl.l +=amount / 100;
hsl.l=clamp01(hsl.l);
return newTinyColor(hsl);
}
function brighten(color, amount){
var rgb;
amount=amount===0 ? 0:amount||10;
rgb=newTinyColor(color).toRgb();
rgb.r=mathMax(0, mathMin(255, rgb.r - mathRound(255 * -(amount / 100))));
rgb.g=mathMax(0, mathMin(255, rgb.g - mathRound(255 * -(amount / 100))));
rgb.b=mathMax(0, mathMin(255, rgb.b - mathRound(255 * -(amount / 100))));
return newTinyColor(rgb);
}
function darken(color, amount){
var hsl;
amount=amount===0 ? 0:amount||10;
hsl=newTinyColor(color).toHsl();
hsl.l -=amount / 100;
hsl.l=clamp01(hsl.l);
return newTinyColor(hsl);
}
function spin(color, amount){
var hsl=newTinyColor(color).toHsl();
var hue=(hsl.h + amount) % 360;
hsl.h=hue < 0 ? 360 + hue:hue;
return newTinyColor(hsl);
}
function complement(color){
var hsl=newTinyColor(color).toHsl();
hsl.h=(hsl.h + 180) % 360;
return newTinyColor(hsl);
}
function triad(color){
var hsl=newTinyColor(color).toHsl();
var h=hsl.h;
return [ newTinyColor(color), newTinyColor({ h:(h + 120) % 360, s: hsl.s, l: hsl.l }), newTinyColor({ h:(h + 240) % 360, s: hsl.s, l: hsl.l }) ];
}
function tetrad(color){
var hsl=newTinyColor(color).toHsl();
var h=hsl.h;
return [ newTinyColor(color), newTinyColor({ h:(h + 90) % 360, s: hsl.s, l: hsl.l }), newTinyColor({ h:(h + 180) % 360, s: hsl.s, l: hsl.l }), newTinyColor({ h:(h + 270) % 360, s: hsl.s, l: hsl.l }) ];
}
function splitcomplement(color){
var hsl=newTinyColor(color).toHsl();
var h=hsl.h;
return [ newTinyColor(color), newTinyColor({ h:(h + 72) % 360, s: hsl.s, l: hsl.l }), newTinyColor({ h:(h + 216) % 360, s: hsl.s, l: hsl.l }) ];
}
TinyColor.prototype={
isDark: function(){
return this.getBrightness() < 128;
},
isLight: function(){
return ! this.isDark();
},
isValid: function(){
return this._ok;
},
getOriginalInput: function(){
return this._originalInput;
},
getFormat: function(){
return this._format;
},
getAlpha: function(){
return this._a;
},
getBrightness: function(){
var rgb=this.toRgb();
return(( rgb.r * 299) +(rgb.g * 587) +(rgb.b * 114)) / 1000;
},
getLuminance: function(){
var rgb=this.toRgb();
var RsRGB, GsRGB, BsRGB, R, G, B;
RsRGB=rgb.r / 255;
GsRGB=rgb.g / 255;
BsRGB=rgb.b / 255;
if(RsRGB <=0.03928){
R=RsRGB / 12.92;
}else{
R=Math.pow(( RsRGB + 0.055) / 1.055, 2.4);
}
if(GsRGB <=0.03928){
G=GsRGB / 12.92;
}else{
G=Math.pow(( GsRGB + 0.055) / 1.055, 2.4);
}
if(BsRGB <=0.03928){
B=BsRGB / 12.92;
}else{
B=Math.pow(( BsRGB + 0.055) / 1.055, 2.4);
}
return(0.2126 * R) +(0.7152 * G) +(0.0722 * B);
},
setAlpha: function(value){
this._a=boundAlpha(value);
this._roundA=mathRound(100 * this._a) / 100;
return this;
},
toHsv: function(){
var hsv=rgbToHsv(this._r, this._g, this._b);
return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };},
toHsvString: function(){
var hsv=rgbToHsv(this._r, this._g, this._b);
var h=mathRound(hsv.h * 360),
s=mathRound(hsv.s * 100),
v=mathRound(hsv.v * 100);
return this._a===1 ? 'hsv(' + h + ', ' + s + '%, ' + v + '%)':'hsva(' + h + ', ' + s + '%, ' + v + '%, ' + this._roundA + ')';
},
toHsl: function(){
var hsl=rgbToHsl(this._r, this._g, this._b);
return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };},
toHslString: function(){
var hsl=rgbToHsl(this._r, this._g, this._b);
var h=mathRound(hsl.h * 360),
s=mathRound(hsl.s * 100),
l=mathRound(hsl.l * 100);
return this._a===1 ? 'hsl(' + h + ', ' + s + '%, ' + l + '%)':'hsla(' + h + ', ' + s + '%, ' + l + '%, ' + this._roundA + ')';
},
toHex: function(allow3Char){
return rgbToHex(this._r, this._g, this._b, allow3Char);
},
toHexString: function(allow3Char){
return '#' + this.toHex(allow3Char);
},
toHex8: function(allow4Char){
return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
},
toHex8String: function(allow4Char){
return '#' + this.toHex8(allow4Char);
},
toRgb: function(){
return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };},
toRgbString: function(){
return this._a===1 ? 'rgb(' + mathRound(this._r) + ', ' + mathRound(this._g) + ', ' + mathRound(this._b) + ')':'rgba(' + mathRound(this._r) + ', ' + mathRound(this._g) + ', ' + mathRound(this._b) + ', ' + this._roundA + ')';
},
toPercentageRgb: function(){
return {
r: mathRound(bound01(this._r, 255) * 100) + '%',
g: mathRound(bound01(this._g, 255) * 100) + '%',
b: mathRound(bound01(this._b, 255) * 100) + '%',
a: this._a
};},
toPercentageRgbString: function(){
return this._a===1 ? 'rgb(' + mathRound(bound01(this._r, 255) * 100) + '%, ' + mathRound(bound01(this._g, 255) * 100) + '%, ' + mathRound(bound01(this._b, 255) * 100) + '%)'
: 'rgba(' + mathRound(bound01(this._r, 255) * 100) + '%, ' + mathRound(bound01(this._g, 255) * 100) + '%, ' + mathRound(bound01(this._b, 255) * 100) + '%, ' + this._roundA + ')';
},
toName: function(){
if(this._a===0){
return 'transparent';
}
if(this._a < 1){
return false;
}
return hexNames[ rgbToHex(this._r, this._g, this._b, true) ]||false;
},
toFilter: function(secondColor){
var hex8String='#' + rgbaToArgbHex(this._r, this._g, this._b, this._a);
var secondHex8String=hex8String;
var gradientType=this._gradientType ? 'GradientType=1, ':'';
var s;
if(secondColor){
s=newTinyColor(secondColor);
secondHex8String='#' + rgbaToArgbHex(s._r, s._g, s._b, s._a);
}
return 'progid:DXImageTransform.Microsoft.gradient(' + gradientType + 'startColorstr=' + hex8String + ',endColorstr=' + secondHex8String + ')';
},
toString: function(format){
var formatSet = !! format;
var formattedString;
var hasAlpha;
var needsAlphaFormat;
format=format||this._format;
formattedString=false;
hasAlpha=this._a < 1&&this._a >=0;
needsAlphaFormat = ! formatSet&&hasAlpha&&(format==='hex'||format==='hex6'||format==='hex3'||format==='hex4'||format==='hex8'||format==='name');
if(needsAlphaFormat){
if(format==='name'&&this._a===0){
return this.toName();
}
return this.toRgbString();
}
if(format==='rgb'){
formattedString=this.toRgbString();
}
if(format==='prgb'){
formattedString=this.toPercentageRgbString();
}
if(format==='hex'||format==='hex6'){
formattedString=this.toHexString();
}
if(format==='hex3'){
formattedString=this.toHexString(true);
}
if(format==='hex4'){
formattedString=this.toHex8String(true);
}
if(format==='hex8'){
formattedString=this.toHex8String();
}
if(format==='name'){
formattedString=this.toName();
}
if(format==='hsl'){
formattedString=this.toHslString();
}
if(format==='hsv'){
formattedString=this.toHsvString();
}
return formattedString||this.toHexString();
},
clone: function(){
return newTinyColor(this.toString());
},
_applyModification: function(fn, args){
var color=fn.apply(null, [ this ].concat([].slice.call(args)));
this._r=color._r;
this._g=color._g;
this._b=color._b;
this.setAlpha(color._a);
return this;
},
lighten: function(){
return this._applyModification(lighten, arguments);
},
brighten: function(){
return this._applyModification(brighten, arguments);
},
darken: function(){
return this._applyModification(darken, arguments);
},
desaturate: function(){
return this._applyModification(desaturate, arguments);
},
saturate: function(){
return this._applyModification(saturate, arguments);
},
greyscale: function(){
return this._applyModification(greyscale, arguments);
},
spin: function(){
return this._applyModification(spin, arguments);
},
_applyCombination: function(fn, args){
return fn.apply(null, [ this ].concat([].slice.call(args)));
},
complement: function(){
return this._applyCombination(complement, arguments);
},
splitcomplement: function(){
return this._applyCombination(splitcomplement, arguments);
},
triad: function(){
return this._applyCombination(triad, arguments);
},
tetrad: function(){
return this._applyCombination(tetrad, arguments);
}};
TinyColor.fromRatio=function(color, opts){
var newColor;
var i;
if(typeof color==='object'){
newColor={};
for(i in color){
if(Object.prototype.hasOwnProperty.call(color, i)){
if(i==='a'){
newColor[ i ]=color[ i ];
}else{
newColor[ i ]=convertToPercentage(color[ i ]);
}}
}
color=newColor;
}
return newTinyColor(color, opts);
};
TinyColor.equals=function(color1, color2){
if(! color1||! color2){
return false;
}
return newTinyColor(color1).toRgbString()===newTinyColor(color2).toRgbString();
};
TinyColor.random=function(){
return TinyColor.fromRatio({
r: mathRandom(),
g: mathRandom(),
b: mathRandom()
});
};
TinyColor.mix=function(color1, color2, amount){
var rgb1;
var rgb2;
var p;
var rgba;
amount=amount===0 ? 0:amount||50;
rgb1=newTinyColor(color1).toRgb();
rgb2=newTinyColor(color2).toRgb();
p=amount / 100;
rgba={
r:(( rgb2.r - rgb1.r) * p) + rgb1.r,
g:(( rgb2.g - rgb1.g) * p) + rgb1.g,
b:(( rgb2.b - rgb1.b) * p) + rgb1.b,
a:(( rgb2.a - rgb1.a) * p) + rgb1.a
};
return newTinyColor(rgba);
};
TinyColor.readability=function(color1, color2){
var c1=newTinyColor(color1);
var c2=newTinyColor(color2);
return(Math.max(c1.getLuminance(), c2.getLuminance()) + 0.05) /(Math.min(c1.getLuminance(), c2.getLuminance()) + 0.05);
};
TinyColor.isReadable=function(color1, color2, wcag2){
var readability=TinyColor.readability(color1, color2);
var wcag2Parms, out;
out=false;
wcag2Parms=validateWCAG2Parms(wcag2);
switch(wcag2Parms.level + wcag2Parms.size){
case 'AAsmall':
case 'AAAlarge':
out=readability >=4.5;
break;
case 'AAlarge':
out=readability >=3;
break;
case 'AAAsmall':
out=readability >=7;
break;
}
return out;
};
TinyColor.mostReadable=function(baseColor, colorList, args){
var bestColor=null;
var bestScore=0;
var readability;
var includeFallbackColors;
var level;
var size;
var i;
args=args||{};
includeFallbackColors=args.includeFallbackColors;
level=args.level;
size=args.size;
for(i=0; i < colorList.length; i +=1){
readability=TinyColor.readability(baseColor, colorList[ i ]);
if(readability > bestScore){
bestScore=readability;
bestColor=newTinyColor(colorList[ i ]);
}}
if(TinyColor.isReadable(baseColor, bestColor, { level: level, size: size })||! includeFallbackColors){
return bestColor;
}
args.includeFallbackColors=false;
return TinyColor.mostReadable(baseColor, [ '#fff', '#000' ], args);
};
TinyColor.names=names;
TinyColor.hexNames=hexNames;
if(typeof window.module!=='undefined'&&window.module.exports){
window.module.exports=TinyColor;
}else if(typeof window.define==='function'&&window.define.amd){
window.define(function(){
return TinyColor;
});
}else{
window.tinycolor=TinyColor;
}}(Math));
(function(factory){
'use strict';
if(typeof window.define==='function'&&window.define.amd){
window.define([ 'jquery' ], factory);
}else if(typeof exports==='object'&&typeof module==='object'){
window.module.exports=factory(window.require('jquery'));
}else{
factory(window.jQuery);
}}(function($){
'use strict';
var dataID='spectrum.id';
var tinycolor=window.tinycolor;
var defaultOpts={
beforeShow: noop,
move: noop,
change: noop,
show: noop,
hide: noop,
color: false,
flat: false,
type: 'color',
showInput: false,
allowEmpty: false,
showButtons: true,
clickoutFiresChange: true,
showInitial: false,
showPalette: false,
showPaletteOnly: false,
hideAfterPaletteSelect: false,
togglePaletteOnly: false,
showSelectionPalette: true,
localStorageKey: false,
appendTo: 'body',
maxSelectionSize: 8,
locale: 'en',
cancelText: 'cancel',
chooseText: 'choose',
togglePaletteMoreText: 'more',
togglePaletteLessText: 'less',
clearText: 'Clear Color Selection',
preferredFormat: 'hex',
className: '',
containerClassName: '',
replacerClassName: '',
showAlpha: false,
theme: 'epo',
palette: [
[ '#000000', '#444444', '#5b5b5b', '#999999', '#bcbcbc', '#eeeeee', '#f3f6f4', '#ffffff' ],
[ '#f44336', '#744700', '#ce7e00', '#8fce00', '#2986cc', '#16537e', '#6a329f', '#c90076' ],
[ '#f4cccc', '#fce5cd', '#fff2cc', '#d9ead3', '#d0e0e3', '#cfe2f3', '#d9d2e9', '#ead1dc' ],
[ '#ea9999', '#f9cb9c', '#ffe599', '#b6d7a8', '#a2c4c9', '#9fc5e8', '#b4a7d6', '#d5a6bd' ],
[ '#e06666', '#f6b26b', '#ffd966', '#93c47d', '#76a5af', '#6fa8dc', '#8e7cc3', '#c27ba0' ],
[ '#cc0000', '#e69138', '#f1c232', '#6aa84f', '#45818e', '#3d85c6', '#674ea7', '#a64d79' ],
[ '#990000', '#b45f06', '#bf9000', '#38761d', '#134f5c', '#0b5394', '#351c75', '#741b47' ],
[ '#660000', '#783f04', '#7f6000', '#274e13', '#0c343d', '#073763', '#20124d', '#4c1130' ]
],
selectionPalette: [],
disabled: false,
offset: null
},
spectrums=[],
IE = !! /msie/i.exec(window.navigator.userAgent),
rgbaSupport=(function(){
var contains=function(str, substr){
return('' + str).indexOf(substr)!==1;
};
var elem=document.createElement('div');
var style=elem.style;
style.cssText='background-color:rgba(0,0,0,.5)';
return contains(style.backgroundColor, 'rgba')||contains(style.backgroundColor, 'hsla');
}()),
replaceInput=[
'<button type="button" class="sp-replacer">',
'<span class="sp-preview"><span class="sp-preview-inner"></span></span>',
'<span class="sp-dd">&#9660;</span>',
'</button>'
].join(''),
markup=(function(){
var i;
var gradientFix='';
if(IE){
for(i=1; i <=6; i++){
gradientFix +="<div class='sp-" + i + "'></div>";
}}
return [
"<div class='sp-container sp-hidden'>",
"<div class='sp-palette-container'>",
"<div class='sp-palette sp-thumb sp-cf'></div>",
"<div class='sp-palette-button-container sp-cf'>",
"<button type='button' class='sp-palette-toggle'></button>",
'</div>',
'</div>',
"<div class='sp-picker-container'>",
"<div class='sp-top sp-cf'>",
"<div class='sp-fill'></div>",
"<div class='sp-top-inner'>",
"<div class='sp-color'>",
"<div class='sp-sat'>",
"<div class='sp-val'>",
"<div class='sp-dragger' tabindex='0'></div>",
'</div>',
'</div>',
'</div>',
"<div class='sp-clear sp-clear-display'>",
'</div>',
"<div class='sp-hue'>",
"<div class='sp-slider' tabindex='0'></div>",
gradientFix,
'</div>',
'</div>',
"<div class='sp-alpha'><div class='sp-alpha-inner'><div class='sp-alpha-handle' tabindex='0'></div></div></div>",
'</div>',
"<div class='sp-input-container sp-cf'>",
"<input class='sp-input' type='text' spellcheck='false'>",
'</div>',
"<div class='sp-initial sp-thumb sp-cf'></div>",
"<div class='sp-button-container sp-cf'>",
"<button type='button' class='sp-cancel'></button>",
"<button type='button' class='sp-choose'></button>",
'</div>',
'</div>',
'</div>'
].join('');
}());
function paletteTemplate(p, color, className, opts){
var html=[];
var i;
var current;
var tiny;
var c;
var formattedString;
var swatchStyle;
for(i=0; i < p.length; i++){
current=p[ i ];
if(current){
tiny=tinycolor(current);
c=tiny.toHsl().l < 0.5 ? 'sp-thumb-el sp-thumb-dark':'sp-thumb-el sp-thumb-light';
c +=tinycolor.equals(color, current) ? ' sp-thumb-active':'';
formattedString=tiny.toString(opts.preferredFormat||'rgb');
swatchStyle=rgbaSupport ? 'background-color:' + tiny.toRgbString():'filter:' + tiny.toFilter();
html.push('<span title="' + formattedString + '" data-color="' + tiny.toRgbString() + '" class="' + c + '" role="button" tabindex="0"><span class="sp-thumb-inner" style="' + swatchStyle + ';"></span></span>');
}else{
html.push('<span class="sp-thumb-el sp-clear-display" role="button" tabindex="0"><span class="sp-clear-palette-only" style="background-color: transparent;"></span></span>');
}}
return "<div class='sp-cf " + className + "'>" + html.join('') + '</div>';
}
function hideAll(){
var i;
for(i=0; i < spectrums.length; i++){
if(spectrums[ i ]){
spectrums[ i ].hide();
}}
}
function instanceOptions(o, callbackContext){
var opts;
o.locale=o.locale||window.navigator.language;
if(o.locale){
o.locale=o.locale.split('-')[ 0 ].toLowerCase();
}
if(o.locale!=='en'&&$.spectrum.localization[ o.locale ]){
o=$.extend({}, $.spectrum.localization[ o.locale ], o);
}
opts=$.extend({}, defaultOpts, o);
opts.callbacks={
move: bind(opts.move, callbackContext),
change: bind(opts.change, callbackContext),
show: bind(opts.show, callbackContext),
hide: bind(opts.hide, callbackContext),
beforeShow: bind(opts.beforeShow, callbackContext)
};
return opts;
}
function spectrum(element, o){
var spect;
var opts=instanceOptions(o, element),
type=opts.type,
flat=type==='flat',
showSelectionPalette=opts.showSelectionPalette,
localStorageKey=opts.localStorageKey,
theme=opts.theme,
callbacks=opts.callbacks,
resize=throttle(reflow, 10),
visible=false,
isDragging=false,
dragWidth=0,
dragHeight=0,
dragHelperHeight=0,
slideHeight=0,
alphaWidth=0,
alphaSlideHelperWidth=0,
slideHelperHeight=0,
currentHue=0,
currentSaturation=0,
currentValue=0,
currentAlpha=1,
palette=[],
paletteArray=[],
paletteLookup={},
selectionPalette=opts.selectionPalette.slice(0),
maxSelectionSize=opts.maxSelectionSize,
draggingClass='sp-dragging',
abortNextInputChange=false,
shiftMovementDirection=null;
var doc=element.ownerDocument,
boundElement=$(element),
disabled=false,
container=$(markup, doc).addClass(theme),
pickerContainer=container.find('.sp-picker-container'),
dragger=container.find('.sp-color'),
dragHelper=container.find('.sp-dragger'),
slider=container.find('.sp-hue'),
slideHelper=container.find('.sp-slider'),
alphaSliderInner=container.find('.sp-alpha-inner'),
alphaSlider=container.find('.sp-alpha'),
alphaSlideHelper=container.find('.sp-alpha-handle'),
textInput=container.find('.sp-input'),
paletteContainer=container.find('.sp-palette'),
initialColorContainer=container.find('.sp-initial'),
cancelButton=container.find('.sp-cancel'),
clearButton=container.find('.sp-clear'),
chooseButton=container.find('.sp-choose'),
toggleButton=container.find('.sp-palette-toggle'),
isInput=boundElement.is('input'),
shouldReplace=isInput&&type==='color',
replacer=shouldReplace ? $(replaceInput).addClass(theme).addClass(opts.className).addClass(opts.replacerClassName):$([]),
offsetElement=shouldReplace ? replacer:boundElement,
previewElement=replacer.find('.sp-preview-inner'),
initialColor=opts.color||(isInput&&boundElement.val()),
colorOnShow=false,
currentPreferredFormat=opts.preferredFormat,
clickoutFiresChange = ! opts.showButtons||opts.clickoutFiresChange,
isEmpty = ! initialColor,
allowEmpty=opts.allowEmpty;
var originalInputContainer=null,
colorizeElement=null,
colorizeElementInitialColor=null,
colorizeElementInitialBackground=null;
var thisId=boundElement.attr('id');
var label;
if(thisId!==undefined&&thisId.length > 0){
label=$('label[for="' + thisId + '"]');
if(label.length){
label.on('click', function(e){
e.preventDefault();
boundElement.spectrum('show');
return false;
});
}}
function applyOptions(){
var i;
var j;
var rgb;
if(opts.showPaletteOnly){
opts.showPalette=true;
}
toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText:opts.togglePaletteLessText);
if(opts.palette){
palette=opts.palette.slice(0);
paletteArray=Array.isArray(palette[ 0 ]) ? palette:[ palette ];
paletteLookup={};
for(i=0; i < paletteArray.length; i++){
for(j=0; j < paletteArray[ i ].length; j++){
rgb=tinycolor(paletteArray[ i ][ j ]).toRgbString();
paletteLookup[ rgb ]=true;
}}
if(opts.showPaletteOnly&&! initialColor){
initialColor=palette[ 0 ][ 0 ]==='' ? palette[ 0 ][ 0 ]:Object.keys(paletteLookup)[ 0 ];
}}
container.toggleClass('sp-flat', flat);
container.toggleClass('sp-input-disabled', ! opts.showInput);
container.toggleClass('sp-alpha-enabled', opts.showAlpha);
container.toggleClass('sp-clear-enabled', allowEmpty);
container.toggleClass('sp-buttons-disabled', ! opts.showButtons);
container.toggleClass('sp-palette-buttons-disabled', ! opts.togglePaletteOnly);
container.toggleClass('sp-palette-disabled', ! opts.showPalette);
container.toggleClass('sp-palette-only', opts.showPaletteOnly);
container.toggleClass('sp-initial-disabled', ! opts.showInitial);
container.addClass(opts.className).addClass(opts.containerClassName);
reflow();
}
function initialize(){
var addOn;
var appendTo;
var paletteEvent;
if(IE){
container.find('*:not(input)').attr('unselectable', 'on');
}
applyOptions();
originalInputContainer=$('<span class="sp-original-input-container"></span>');
[ 'margin' ].forEach(function(cssProp){
originalInputContainer.css(cssProp, boundElement.css(cssProp));
});
if(boundElement.css('display')==='block'){
originalInputContainer.css('display', 'flex');
}
if(shouldReplace){
boundElement.after(replacer).hide();
}else if(type==='text'){
originalInputContainer.addClass('sp-colorize-container');
boundElement.addClass('spectrum sp-colorize').wrap(originalInputContainer);
}else if(type==='component'){
boundElement.addClass('spectrum').wrap(originalInputContainer);
addOn=$([ "<div class='sp-colorize-container sp-add-on'>", "<div class='sp-colorize'></div> ", '</div>' ].join(''));
addOn
.width(boundElement.outerHeight() + 'px')
.css('border-radius', boundElement.css('border-radius'))
.css('border', boundElement.css('border'));
boundElement.addClass('with-add-on').before(addOn);
}
colorizeElement=boundElement.parent().find('.sp-colorize');
colorizeElementInitialColor=colorizeElement.css('color');
colorizeElementInitialBackground=colorizeElement.css('background-color');
if(! allowEmpty){
clearButton.hide();
}
if(flat){
boundElement.after(container).hide();
}else{
appendTo=opts.appendTo==='parent' ? boundElement.parent():$(opts.appendTo);
if(appendTo.length!==1){
appendTo=$('body');
}
appendTo.append(container);
}
updateSelectionPaletteFromStorage();
offsetElement.on('click.spectrum touchstart.spectrum', function(e){
if(! disabled){
show();
}
e.stopPropagation();
if(! $(e.target).is('input')){
e.preventDefault();
}});
if(boundElement.is(':disabled')||opts.disabled===true){
disable();
}
container.on('click', stopPropagation);
container.on('keydown', 'div[role="button"]', function(e){
if(e.keyCode===13){
e.preventDefault();
$(this).click();
}});
[ textInput, boundElement ].forEach(function(input){
input.on('change', function(){
setFromTextInput(input.val());
});
input.on('paste', function(){
setTimeout(function(){
setFromTextInput(input.val());
}, 1);
});
input.on('keydown', function(e){
if(e.keyCode===13){
setFromTextInput($(input).val());
if(input==boundElement){
hide();
}}
});
});
cancelButton.text(opts.cancelText);
cancelButton.on('click.spectrum', function(e){
e.stopPropagation();
e.preventDefault();
revert();
hide();
});
clearButton.attr('title', opts.clearText);
clearButton.on('click.spectrum', function(e){
e.stopPropagation();
e.preventDefault();
isEmpty=true;
move();
if(flat){
updateOriginalInput(true);
}});
chooseButton.text(opts.chooseText);
chooseButton.on('click.spectrum', function(e){
e.stopPropagation();
e.preventDefault();
if(IE&&textInput.is(':focus')){
textInput.trigger('change');
}
if(isValid()){
updateOriginalInput(true);
hide();
}});
toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText:opts.togglePaletteLessText);
toggleButton.on('click.spectrum', function(e){
e.stopPropagation();
e.preventDefault();
opts.showPaletteOnly = ! opts.showPaletteOnly;
if(! opts.showPaletteOnly&&! flat){
container.css('left', '-=' +(pickerContainer.outerWidth(true) + 5));
}
applyOptions();
});
draggable(
alphaSlider,
function(dragX, dragY, e){
currentAlpha=dragX / alphaWidth;
isEmpty=false;
if(e.shiftKey){
currentAlpha=Math.round(currentAlpha * 10) / 10;
}
move();
},
dragStart,
dragStop
);
draggable(
slider,
function(dragX, dragY){
currentHue=parseFloat(dragY / slideHeight);
isEmpty=false;
if(! opts.showAlpha){
currentAlpha=1;
}
move();
},
dragStart,
dragStop
);
draggable(
dragger,
function(dragX, dragY, e){
var oldDragX;
var oldDragY;
var furtherFromX;
var setSaturation;
var setValue;
if(! e.shiftKey){
shiftMovementDirection=null;
}else if(! shiftMovementDirection){
oldDragX=currentSaturation * dragWidth;
oldDragY=dragHeight -(currentValue * dragHeight);
furtherFromX=Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY);
shiftMovementDirection=furtherFromX ? 'x':'y';
}
setSaturation = ! shiftMovementDirection||shiftMovementDirection==='x';
setValue = ! shiftMovementDirection||shiftMovementDirection==='y';
if(setSaturation){
currentSaturation=parseFloat(dragX / dragWidth);
}
if(setValue){
currentValue=parseFloat(( dragHeight - dragY) / dragHeight);
}
isEmpty=false;
if(! opts.showAlpha){
currentAlpha=1;
}
move();
},
dragStart,
dragStop
);
if(initialColor!==false&&initialColor!==''){
set(initialColor);
updateUI();
currentPreferredFormat=tinycolor(initialColor).format||opts.preferredFormat;
addColorToSelectionPalette(initialColor);
}else if(initialColor===''){
set(initialColor);
updateUI();
}else{
updateUI();
}
if(flat){
show();
}
function paletteElementClick(e){
if(e.data&&e.data.ignore){
set($(e.target).closest('.sp-thumb-el').data('color'));
move();
}else{
set($(e.target).closest('.sp-thumb-el').data('color'));
move();
if(opts.hideAfterPaletteSelect){
updateOriginalInput(true);
hide();
}else{
updateOriginalInput();
}}
return false;
}
paletteEvent=IE ? 'mousedown.spectrum':'click.spectrum touchstart.spectrum';
paletteContainer.on(paletteEvent, '.sp-thumb-el', paletteElementClick);
initialColorContainer.on(paletteEvent, '.sp-thumb-el:nth-child(1)', { ignore: true }, paletteElementClick);
}
function updateSelectionPaletteFromStorage(){
var localStorage;
var oldPalette;
if(localStorageKey){
try {
localStorage=window.localStorage;
oldPalette=localStorage[ localStorageKey ].split(',#');
if(oldPalette.length > 1){
delete localStorage[ localStorageKey ];
$.each(oldPalette, function(i, c){
addColorToSelectionPalette(c);
});
}} catch(e){
window.console.log(e);
}
try {
selectionPalette=window.localStorage[ localStorageKey ].split(';');
} catch(e){
window.console.log(e);
}}
}
function addColorToSelectionPalette(color){
var rgb;
if(showSelectionPalette){
rgb=tinycolor(color).toRgbString();
if(! paletteLookup[ rgb ]&&$.inArray(rgb, selectionPalette)===-1){
selectionPalette.push(rgb);
while(selectionPalette.length > maxSelectionSize){
selectionPalette.shift();
}}
if(localStorageKey){
try {
window.localStorage[ localStorageKey ]=selectionPalette.join(';');
} catch(e){
window.console.log(e);
}}
}}
function getUniqueSelectionPalette(){
var unique=[];
var i;
var rgb;
if(opts.showPalette){
for(i=0; i < selectionPalette.length; i++){
rgb=tinycolor(selectionPalette[ i ]).toRgbString();
if(! paletteLookup[ rgb ]){
unique.push(selectionPalette[ i ]);
}}
}
return unique.reverse().slice(0, opts.maxSelectionSize);
}
function drawPalette(){
var currentColor=get();
var html=$.map(paletteArray, function(thispalette, i){
return paletteTemplate(thispalette, currentColor, 'sp-palette-row sp-palette-row-' + i, opts);
});
updateSelectionPaletteFromStorage();
if(selectionPalette){
html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, 'sp-palette-row sp-palette-row-selection', opts));
}
paletteContainer.html(html.join(''));
}
function drawInitial(){
var initial;
var current;
if(opts.showInitial){
initial=colorOnShow;
current=get();
initialColorContainer.html(paletteTemplate([ initial, current ], current, 'sp-palette-row-initial', opts));
}}
function dragStart(){
if(dragHeight <=0||dragWidth <=0||slideHeight <=0){
reflow();
}
isDragging=true;
container.addClass(draggingClass);
shiftMovementDirection=null;
boundElement.trigger('dragstart.spectrum', [ get() ]);
}
function dragStop(){
isDragging=false;
container.removeClass(draggingClass);
boundElement.trigger('dragstop.spectrum', [ get() ]);
}
function setFromTextInput(value){
var tiny;
if(abortNextInputChange){
abortNextInputChange=false;
return;
}
if(( value===null||value==='')&&allowEmpty){
set(null);
move();
updateOriginalInput();
}else{
tiny=tinycolor(value);
if(tiny.isValid()){
set(tiny);
move();
updateOriginalInput();
}else{
textInput.addClass('sp-validation-error');
}}
}
function toggle(){
if(visible){
hide();
}else{
show();
}}
function show(){
var event=$.Event('beforeShow.spectrum');
if(visible){
reflow();
return;
}
boundElement.trigger(event, [ get() ]);
if(callbacks.beforeShow(get())===false||event.isDefaultPrevented()){
return;
}
hideAll();
visible=true;
$(doc).on('keydown.spectrum', onkeydown);
$(doc).on('click.spectrum', clickout);
$(window).on('resize.spectrum', resize);
replacer.attr('aria-expanded', true);
replacer.addClass('sp-active');
container.removeClass('sp-hidden');
reflow();
updateUI();
colorOnShow=get();
drawInitial();
callbacks.show(colorOnShow);
boundElement.trigger('show.spectrum', [ colorOnShow ]);
}
function onkeydown(e){
if(e.keyCode===27){
hide();
}}
function clickout(e){
if(e.button===2){
return;
}
if(isDragging){
return;
}
if(clickoutFiresChange){
updateOriginalInput(true);
}else{
revert();
}
hide();
}
function hide(){
if(! visible||flat){
return;
}
visible=false;
$(doc).off('keydown.spectrum', onkeydown);
$(doc).off('click.spectrum', clickout);
$(window).off('resize.spectrum', resize);
replacer.attr('aria-expanded', false);
replacer.removeClass('sp-active');
container.addClass('sp-hidden');
callbacks.hide(get());
boundElement.trigger('hide.spectrum', [ get() ]);
}
function revert(){
set(colorOnShow, true);
updateOriginalInput(true);
}
function set(color, ignoreFormatChange){
var newColor, newHsv;
if(tinycolor.equals(color, get())){
updateUI();
return;
}
if(( ! color||color===undefined)&&allowEmpty){
isEmpty=true;
}else{
isEmpty=false;
newColor=tinycolor(color);
newHsv=newColor.toHsv();
currentHue=(newHsv.h % 360) / 360;
currentSaturation=newHsv.s;
currentValue=newHsv.v;
currentAlpha=newHsv.a;
}
updateUI();
if(newColor&&newColor.isValid()&&! ignoreFormatChange){
currentPreferredFormat=opts.preferredFormat||newColor.getFormat();
}}
function get(thisopts){
thisopts=thisopts||{};
if(allowEmpty&&isEmpty){
return null;
}
return tinycolor.fromRatio({
h: currentHue,
s: currentSaturation,
v: currentValue,
a: Math.round(currentAlpha * 1000) / 1000
},
{ format: thisopts.format||currentPreferredFormat }
);
}
function isValid(){
return ! textInput.hasClass('sp-validation-error');
}
function move(){
updateUI();
callbacks.move(get());
boundElement.trigger('move.spectrum', [ get() ]);
}
function updateUI(){
var flatColor;
var format;
var realColor;
var displayColor;
var realHex;
var realRgb;
var rgb;
var realAlpha;
var gradient;
var color;
var textColor;
textInput.removeClass('sp-validation-error');
updateHelperLocations();
flatColor=tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 });
dragger.css('background-color', flatColor.toHexString());
format=currentPreferredFormat;
if(currentAlpha < 1&&!(currentAlpha===0&&format==='name')){
if(format==='hex'||format==='hex3'||format==='hex6'||format==='name'){
format='rgb';
}}
realColor=get({ format: format });
displayColor='';
previewElement.removeClass('sp-clear-display');
previewElement.css('background-color', 'transparent');
if(! realColor&&allowEmpty){
previewElement.addClass('sp-clear-display');
}else{
realHex=realColor.toHexString();
realRgb=realColor.toRgbString();
if(rgbaSupport||realColor.alpha===1){
previewElement.css('background-color', realRgb);
}else{
previewElement.css('background-color', 'transparent');
previewElement.css('filter', realColor.toFilter());
}
if(opts.showAlpha){
rgb=realColor.toRgb();
rgb.a=0;
realAlpha=tinycolor(rgb).toRgbString();
gradient='linear-gradient(left, ' + realAlpha + ', ' + realHex + ')';
if(IE){
alphaSliderInner.css('filter', tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex));
}else{
alphaSliderInner.css('background', '-webkit-' + gradient);
alphaSliderInner.css('background', '-moz-' + gradient);
alphaSliderInner.css('background', '-ms-' + gradient);
alphaSliderInner.css('background', 'linear-gradient(to right, ' + realAlpha + ', ' + realHex + ')');
}}
displayColor=realColor.toString(format);
}
if(opts.showInput){
textInput.val(displayColor);
}
boundElement.val(displayColor);
if(opts.type==='text'||opts.type==='component'){
color=realColor;
if(color&&colorizeElement){
textColor=color.isLight()||color.getAlpha() < 0.4 ? 'black':'white';
colorizeElement.css('background-color', color.toRgbString()).css('color', textColor);
}else{
colorizeElement.css('background-color', colorizeElementInitialBackground).css('color', colorizeElementInitialColor);
}}
if(opts.showPalette){
drawPalette();
}
drawInitial();
}
function updateHelperLocations(){
var s=currentSaturation;
var v=currentValue;
var dragX;
var dragY;
var alphaX;
var slideY;
if(allowEmpty&&isEmpty){
alphaSlideHelper.hide();
slideHelper.hide();
dragHelper.hide();
}else{
alphaSlideHelper.show();
slideHelper.show();
dragHelper.show();
dragX=s * dragWidth;
dragY=dragHeight -(v * dragHeight);
dragX=Math.max(-dragHelperHeight, Math.min(dragWidth - dragHelperHeight, dragX - dragHelperHeight));
dragY=Math.max(-dragHelperHeight, Math.min(dragHeight - dragHelperHeight, dragY - dragHelperHeight));
dragHelper.css({
top: dragY + 'px',
left: dragX + 'px'
});
alphaX=currentAlpha * alphaWidth;
alphaSlideHelper.css({
left: alphaX -(alphaSlideHelperWidth / 2) + 'px'
});
slideY=currentHue * slideHeight;
slideHelper.css({
top: slideY - slideHelperHeight + 'px'
});
}}
function updateOriginalInput(fireCallback){
var color=get(),
hasChanged = ! tinycolor.equals(color, colorOnShow);
if(color){
addColorToSelectionPalette(color);
}
if(fireCallback&&hasChanged){
callbacks.change(color);
abortNextInputChange=true;
boundElement.trigger('change', [ color ]);
}}
function reflow(){
if(! visible){
return;
}
dragWidth=dragger.width();
dragHeight=dragger.height();
dragHelperHeight=dragHelper.height();
slideHeight=slider.height();
slideHelperHeight=slideHelper.height();
alphaWidth=alphaSlider.width();
alphaSlideHelperWidth=alphaSlideHelper.width();
if(! flat){
container.attr('aria-haspopup', true);
container.css('position', 'absolute');
if(opts.offset){
container.offset(opts.offset);
}else{
container.offset(getOffset(container, offsetElement));
}}
updateHelperLocations();
if(opts.showPalette){
drawPalette();
}
boundElement.trigger('reflow.spectrum');
}
function destroy(){
var oInputContainer;
boundElement.show().removeClass('spectrum with-add-on sp-colorize');
offsetElement.off('click.spectrum touchstart.spectrum');
container.remove();
replacer.remove();
if(colorizeElement){
colorizeElement.css('background-color', colorizeElementInitialBackground).css('color', colorizeElementInitialColor);
}
oInputContainer=boundElement.closest('.sp-original-input-container');
if(oInputContainer.length > 0){
oInputContainer.after(boundElement).remove();
}
spectrums[ spect.id ]=null;
}
function option(optionName, optionValue){
if(optionName===undefined){
return $.extend({}, opts);
}
if(optionValue===undefined){
return opts[ optionName ];
}
opts[ optionName ]=optionValue;
if(optionName==='preferredFormat'){
currentPreferredFormat=opts.preferredFormat;
}
applyOptions();
}
function enable(){
disabled=false;
boundElement.attr('disabled', false);
offsetElement.removeClass('sp-disabled');
}
function disable(){
hide();
disabled=true;
boundElement.attr('disabled', true);
offsetElement.addClass('sp-disabled');
}
function setOffset(coord){
opts.offset=coord;
reflow();
}
initialize();
spect={
show: show,
hide: hide,
toggle: toggle,
reflow: reflow,
option: option,
enable: enable,
disable: disable,
offset: setOffset,
set: function(c){
set(c);
updateOriginalInput();
},
get: get,
destroy: destroy,
container: container
};
spect.id=spectrums.push(spect) - 1;
return spect;
}
function getOffset(picker, input){
var extraY=0;
var dpWidth=picker.outerWidth();
var dpHeight=picker.outerHeight();
var inputHeight=input.outerHeight();
var doc=picker[ 0 ].ownerDocument;
var docElem=doc.documentElement;
var viewWidth=docElem.clientWidth + $(doc).scrollLeft();
var viewHeight=docElem.clientHeight + $(doc).scrollTop();
var offset=input.offset();
var offsetLeft=offset.left;
var offsetTop=offset.top;
offsetTop +=inputHeight;
offsetLeft -=Math.min(offsetLeft, offsetLeft + dpWidth > viewWidth&&viewWidth > dpWidth ? Math.abs(offsetLeft + dpWidth - viewWidth):0);
offsetTop -=Math.min(offsetTop, offsetTop + dpHeight > viewHeight&&viewHeight > dpHeight ? Math.abs(dpHeight + inputHeight - extraY):extraY);
return {
top: offsetTop,
bottom: offset.bottom,
left: offsetLeft,
right: offset.right,
width: offset.width,
height: offset.height
};}
function noop(){}
function stopPropagation(e){
e.stopPropagation();
}
function bind(func, obj){
var slice=Array.prototype.slice;
var args=slice.call(arguments, 2);
return function(){
return func.apply(obj, args.concat(slice.call(arguments)));
};}
function draggable(element, onmove, onstart, onstop){
var doc=document;
var dragging=false;
var offset={};
var maxHeight=0;
var maxWidth=0;
var hasTouch='ontouchstart' in window;
var duringDragEvents={};
onmove=onmove||function(){};
onstart=onstart||function(){};
onstop=onstop||function(){};
duringDragEvents.selectstart=prevent;
duringDragEvents.dragstart=prevent;
duringDragEvents[ 'touchmove mousemove' ]=move;
duringDragEvents[ 'touchend mouseup' ]=stop;
function prevent(e){
if(e.stopPropagation){
e.stopPropagation();
}
if(e.preventDefault){
e.preventDefault();
}
e.returnValue=false;
}
function move(e){
var t0;
var pageX;
var pageY;
var dragX;
var dragY;
if(dragging){
if(IE&&doc.documentMode < 9&&! e.button){
return stop();
}
t0=e.originalEvent&&e.originalEvent.touches&&e.originalEvent.touches[ 0 ];
pageX=(t0&&t0.pageX)||e.pageX;
pageY=(t0&&t0.pageY)||e.pageY;
dragX=Math.max(0, Math.min(pageX - offset.left, maxWidth));
dragY=Math.max(0, Math.min(pageY - offset.top, maxHeight));
if(hasTouch){
prevent(e);
}
onmove.apply(element, [ dragX, dragY, e ]);
}}
function start(e){
var rightclick=e.which ? e.which===3:e.button===2;
if(! rightclick&&! dragging){
if(onstart.apply(element, arguments)!==false){
dragging=true;
maxHeight=$(element).height();
maxWidth=$(element).width();
offset=$(element).offset();
$(doc).on(duringDragEvents);
$(doc.body).addClass('sp-dragging');
move(e);
prevent(e);
}}
}
function stop(){
if(dragging){
$(doc).off(duringDragEvents);
$(doc.body).removeClass('sp-dragging');
setTimeout(function(){
onstop.apply(element, arguments);
}, 0);
}
dragging=false;
}
$(element).on('touchstart mousedown', start);
}
function throttle(func, wait, debounce){
var timeout;
return function(){
var context=this,
args=arguments;
var throttler=function(){
timeout=null;
func.apply(context, args);
};
if(debounce){
clearTimeout(timeout);
}
if(debounce||! timeout){
timeout=setTimeout(throttler, wait);
}};}
function inputTypeColorSupport(){
return $.fn.spectrum.inputTypeColorSupport();
}
$.fn.spectrum=function(opts){
var returnValue;
var args;
var spect;
var method;
if(typeof opts==='string'){
returnValue=this;
args=Array.prototype.slice.call(arguments, 1);
this.each(function(){
spect=spectrums[ $(this).data(dataID) ];
if(spect){
method=spect[ opts ];
if(! method){
throw new Error("Spectrum: no such method: '" + opts + "'");
}
if(opts==='get'){
returnValue=spect.get();
}else if(opts==='container'){
returnValue=spect.container;
}else if(opts==='option'){
returnValue=spect.option.apply(spect, args);
}else if(opts==='destroy'){
spect.destroy();
$(this).removeData(dataID);
}else{
method.apply(spect, args);
}}
});
return returnValue;
}
return this.spectrum('destroy').each(function(){
var options=$.extend({}, $(this).data(), opts);
var thisspect;
if(! $(this).is('input')){
options.type='noInput';
}else if(options.flat||options.type==='flat'){
options.type='flat';
}else if($(this).attr('type')==='color'){
options.type='color';
}
thisspect=spectrum(this, options);
$(this).data(dataID, thisspect.id);
});
};
$.fn.spectrum.load=true;
$.fn.spectrum.loadOpts={};
$.fn.spectrum.draggable=draggable;
$.fn.spectrum.defaults=defaultOpts;
$.fn.spectrum.inputTypeColorSupport=function(){
var colorInput;
if(typeof inputTypeColorSupport._cachedResult==='undefined'){
colorInput=$("<input type='color'>")[ 0 ];
inputTypeColorSupport._cachedResult=colorInput.type==='color'&&colorInput.value!=='';
}
return inputTypeColorSupport._cachedResult;
};
$.spectrum={};
$.spectrum.localization={};
$.spectrum.palettes={};
$.fn.spectrum.processNativeColorInputs=function(){
var colorInputs=$('input[type=color]');
if(colorInputs.length&&! inputTypeColorSupport()){
colorInputs.spectrum({
preferredFormat: 'hex6'
});
}};
$(function(){
if($.fn.spectrum.load){
$.fn.spectrum.processNativeColorInputs();
}});
}));
(function(factory, jQuery, Zepto){
'use strict';
if(typeof define==='function'&&define.amd){
define([ 'jquery' ], factory);
}else if(typeof exports==='object'&&typeof Meteor==='undefined'){
window.module.exports=factory(window.require('jquery'));
}else{
factory(jQuery||Zepto);
}}(
function($){
'use strict';
var JSON=window.JSON;
var globals;
var Mask=function(el, mask, options){
var jMask=this;
var regexMask;
var oldValue;
var p={
invalid: [],
getCaret: function(){
var sel,
pos=0,
ctrl,
dSel,
cSelStart;
try {
ctrl=el.get(0);
dSel=document.selection;
cSelStart=ctrl.selectionStart;
if(dSel&&navigator.appVersion.indexOf('MSIE 10')===-1){
sel=dSel.createRange();
sel.moveStart('character', -p.val().length);
pos=sel.text.length;
}else if(cSelStart||cSelStart==='0'){
pos=cSelStart;
}
return pos;
} catch(err){
window.console.log(err);
}},
setCaret: function(pos){
var range;
var ctrl;
try {
if(el.is(':focus')){
ctrl=el.get(0);
if(ctrl.setSelectionRange){
ctrl.setSelectionRange(pos, pos);
}else{
range=ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}}
} catch(err){
window.console.log(err);
}},
events: function(){
el.on('keydown.mask', function(e){
el.data('mask-keycode', e.keyCode||e.which);
el.data('mask-previus-value', el.val());
el.data('mask-previus-caret-pos', p.getCaret());
p.maskDigitPosMapOld=p.maskDigitPosMap;
})
.on($.jMaskGlobals.useInput ? 'input.mask':'keyup.mask', p.behaviour)
.on('paste.mask drop.mask', function(){
setTimeout(function(){
el.keydown().keyup();
}, 100);
})
.on('change.mask', function(){
el.data('changed', true);
})
.on('blur.mask', function(){
if(oldValue!==p.val()&&! el.data('changed')){
el.trigger('change');
}
el.data('changed', false);
})
.on('blur.mask', function(){
oldValue=p.val();
})
.on('focus.mask', function(e){
if(options.selectOnFocus===true){
$(e.target).select();
}})
.on('focusout.mask', function(){
if(options.clearIfNotMatch&&! regexMask.test(p.val())){
p.val('');
}});
},
getRegexMask: function(){
var maskChunks=[],
translation,
pattern,
optional,
recursive,
oRecursive,
r;
var i;
for(i=0; i < mask.length; i +=1){
translation=jMask.translation[ mask.charAt(i) ];
if(translation){
pattern=translation.pattern.toString().replace(/.{1}$|^.{1}/g, '');
optional=translation.optional;
recursive=translation.recursive;
if(recursive){
maskChunks.push(mask.charAt(i));
oRecursive={
digit: mask.charAt(i),
pattern: pattern
};}else{
maskChunks.push(! optional&&! recursive ? pattern:pattern + '?');
}}else{
maskChunks.push(mask.charAt(i).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
}}
r=maskChunks.join('');
if(oRecursive){
r=r.replace(new RegExp('(' + oRecursive.digit + '(.*' + oRecursive.digit + ')?)'), '($1)?').replace(new RegExp(oRecursive.digit, 'g'), oRecursive.pattern);
}
return new RegExp(r);
},
destroyEvents: function(){
el.off([ 'input', 'keydown', 'keyup', 'paste', 'drop', 'blur', 'focusout', '' ].join('.mask '));
},
val: function(v){
var isInput=el.is('input'),
method=isInput ? 'val':'text',
r;
if(arguments.length > 0){
if(el[ method ]()!==v){
el[ method ](v);
}
r=el;
}else{
r=el[ method ]();
}
return r;
},
calculateCaretPosition: function(oldVal){
var newVal=p.getMasked(),
caretPosNew=p.getCaret();
var caretPosOld,
newValL,
oldValL,
maskDigitsBeforeCaret=0,
maskDigitsAfterCaret=0,
maskDigitsBeforeCaretAll=0,
maskDigitsBeforeCaretAllOld=0,
i=0;
var caretPos;
if(oldVal!==newVal){
caretPosOld=el.data('mask-previus-caret-pos')||0;
newValL=newVal.length;
oldValL=oldVal.length;
for(i=caretPosNew; i < newValL; i +=1){
if(! p.maskDigitPosMap[ i ]){
break;
}
maskDigitsAfterCaret=maskDigitsAfterCaret + 1;
}
for(i=caretPosNew - 1; i >=0; i -=1){
if(! p.maskDigitPosMap[ i ]){
break;
}
maskDigitsBeforeCaret=maskDigitsBeforeCaret + 1;
}
for(i=caretPosNew - 1; i >=0; i -=1){
if(p.maskDigitPosMap[ i ]){
maskDigitsBeforeCaretAll=maskDigitsBeforeCaretAll + 1;
}}
for(i=caretPosOld - 1; i >=0; i -=1){
if(p.maskDigitPosMapOld[ i ]){
maskDigitsBeforeCaretAllOld=maskDigitsBeforeCaretAllOld + 1;
}}
if(caretPosNew > oldValL){
caretPosNew=newValL * 10;
}else if(caretPosOld >=caretPosNew&&caretPosOld!==oldValL){
if(! p.maskDigitPosMapOld[ caretPosNew ]){
caretPos=caretPosNew;
caretPosNew -=maskDigitsBeforeCaretAllOld - maskDigitsBeforeCaretAll;
caretPosNew -=maskDigitsBeforeCaret;
if(p.maskDigitPosMap[ caretPosNew ]){
caretPosNew=caretPos;
}}
}else if(caretPosNew > caretPosOld){
caretPosNew +=maskDigitsBeforeCaretAll - maskDigitsBeforeCaretAllOld;
caretPosNew +=maskDigitsAfterCaret;
}}
return caretPosNew;
},
behaviour: function(e){
var keyCode=el.data('mask-keycode');
var newVal;
var oldVal;
var caretPos;
e=e||window.event;
p.invalid=[];
if($.inArray(keyCode, jMask.byPassKeys)===-1){
newVal=p.getMasked();
caretPos=p.getCaret();
oldVal=el.data('mask-previus-value')||'';
setTimeout(function(){
p.setCaret(p.calculateCaretPosition(oldVal));
}, $.jMaskGlobals.keyStrokeCompensation);
p.val(newVal);
p.setCaret(caretPos);
return p.callbacks(e);
}},
getMasked: function(skipMaskChars, val){
var buf=[],
value=val===undefined ? p.val():val + '',
m=0,
maskLen=mask.length,
v=0,
valLen=value.length,
offset=1,
addMethod='push',
resetPos=-1,
maskDigitCount=0,
maskDigitPosArr=[],
lastMaskChar,
check;
var lastUntranslatedMaskChar;
var maskDigit;
var valDigit;
var translation;
var lastMaskCharDigit;
var newVal;
if(options.reverse){
addMethod='unshift';
offset=-1;
lastMaskChar=0;
m=maskLen - 1;
v=valLen - 1;
check=function(){
return m > -1&&v > -1;
};}else{
lastMaskChar=maskLen - 1;
check=function(){
return m < maskLen&&v < valLen;
};}
while(check()){
maskDigit=mask.charAt(m);
valDigit=value.charAt(v);
translation=jMask.translation[ maskDigit ];
if(translation){
if(valDigit.match(translation.pattern)){
buf[ addMethod ](valDigit);
if(translation.recursive){
if(resetPos===-1){
resetPos=m;
}else if(m===lastMaskChar&&m!==resetPos){
m=resetPos - offset;
}
if(lastMaskChar===resetPos){
m -=offset;
}}
m +=offset;
}else if(valDigit===lastUntranslatedMaskChar){
maskDigitCount=maskDigitCount - 1;
lastUntranslatedMaskChar=undefined;
}else if(translation.optional){
m +=offset;
v -=offset;
}else if(translation.fallback){
buf[ addMethod ](translation.fallback);
m +=offset;
v -=offset;
}else{
p.invalid.push({
p: v,
v: valDigit,
e: translation.pattern
});
}
v +=offset;
}else{
if(! skipMaskChars){
buf[ addMethod ](maskDigit);
}
if(valDigit===maskDigit){
maskDigitPosArr.push(v);
v +=offset;
}else{
lastUntranslatedMaskChar=maskDigit;
maskDigitPosArr.push(v + maskDigitCount);
maskDigitCount=maskDigitCount + 1;
}
m +=offset;
}}
lastMaskCharDigit=mask.charAt(lastMaskChar);
if(maskLen===valLen + 1&&! jMask.translation[ lastMaskCharDigit ]){
buf.push(lastMaskCharDigit);
}
newVal=buf.join('');
p.mapMaskdigitPositions(newVal, maskDigitPosArr, valLen);
return newVal;
},
mapMaskdigitPositions: function(newVal, maskDigitPosArr, valLen){
var maskDiff=options.reverse ? newVal.length - valLen:0;
var i;
p.maskDigitPosMap={};
for(i=0; i < maskDigitPosArr.length; i +=1){
p.maskDigitPosMap[ maskDigitPosArr[ i ] + maskDiff ]=1;
}},
callbacks: function(e){
var val=p.val(),
changed=val!==oldValue,
defaultArgs=[ val, e, el, options ],
callback=function(name, criteria, args){
if(typeof options[ name ]==='function'&&criteria){
options[ name ].apply(this, args);
}};
callback('onChange', changed===true, defaultArgs);
callback('onKeyPress', changed===true, defaultArgs);
callback('onComplete', val.length===mask.length, defaultArgs);
callback('onInvalid', p.invalid.length > 0, [ val, e, el, p.invalid, options ]);
}};
el=$(el);
oldValue=p.val();
mask=typeof mask==='function' ? mask(p.val(), undefined, el, options):mask;
jMask.mask=mask;
jMask.options=options;
jMask.remove=function(){
var caret=p.getCaret();
if(jMask.options.placeholder){
el.removeAttr('placeholder');
}
if(el.data('mask-maxlength')){
el.removeAttr('maxlength');
}
p.destroyEvents();
p.val(jMask.getCleanVal());
p.setCaret(caret);
return el;
};
jMask.getCleanVal=function(){
return p.getMasked(true);
};
jMask.getMaskedVal=function(val){
return p.getMasked(false, val);
};
jMask.init=function(onlyMask){
var i;
var translation;
var caret;
var maxlength;
onlyMask=onlyMask||false;
options=options||{};
jMask.clearIfNotMatch=$.jMaskGlobals.clearIfNotMatch;
jMask.byPassKeys=$.jMaskGlobals.byPassKeys;
jMask.translation=$.extend({}, $.jMaskGlobals.translation, options.translation);
jMask=$.extend(true, {}, jMask, options);
regexMask=p.getRegexMask();
if(onlyMask){
p.events();
p.val(p.getMasked());
}else{
if(options.placeholder){
el.attr('placeholder', options.placeholder);
}
if(el.data('mask')){
el.attr('autocomplete', 'off');
}
for(i=0, maxlength=true; i < mask.length; i +=1){
translation=jMask.translation[ mask.charAt(i) ];
if(translation&&translation.recursive){
maxlength=false;
break;
}}
if(maxlength){
el.attr('maxlength', mask.length).data('mask-maxlength', true);
}
p.destroyEvents();
p.events();
caret=p.getCaret();
p.val(p.getMasked());
p.setCaret(caret);
}};
jMask.init(! el.is('input'));
};
var notSameMaskObject=function(field, mask, options){
var maskObject=$(field).data('mask'),
stringify=JSON.stringify,
value=$(field).val()||$(field).text();
options=options||{};
try {
if(typeof mask==='function'){
mask=mask(value);
}
return typeof maskObject!=='object'||stringify(maskObject.options)!==stringify(options)||maskObject.mask!==mask;
} catch(err){
window.console.log(err);
}},
HTMLAttributes=function(){
var input=$(this),
options={},
prefix='data-mask-',
mask=input.attr('data-mask');
if(input.attr(prefix + 'reverse')){
options.reverse=true;
}
if(input.attr(prefix + 'clearifnotmatch')){
options.clearIfNotMatch=true;
}
if(input.attr(prefix + 'selectonfocus')==='true'){
options.selectOnFocus=true;
}
if(notSameMaskObject(input, mask, options)){
return input.data('mask', new Mask(this, mask, options));
}},
eventSupported=function(eventName){
var el=document.createElement('div'),
isSupported;
eventName='on' + eventName;
isSupported=eventName in el;
if(! isSupported){
el.setAttribute(eventName, 'return;');
isSupported=typeof el[ eventName ]==='function';
}
el=null;
return isSupported;
};
$.maskWatchers={};
$.fn.mask=function(mask, options){
var selector=this.selector,
maskGlobals=$.jMaskGlobals,
interval=maskGlobals.watchInterval,
watchInputs,
maskFunction;
options=options||{};
watchInputs=options.watchInputs||maskGlobals.watchInputs;
maskFunction=function(){
if(notSameMaskObject(this, mask, options)){
return $(this).data('mask', new Mask(this, mask, options));
}};
$(this).each(maskFunction);
if(selector&&selector!==''&&watchInputs){
clearInterval($.maskWatchers[ selector ]);
$.maskWatchers[ selector ]=setInterval(function(){
$(document).find(selector).each(maskFunction);
}, interval);
}
return this;
};
$.fn.masked=function(val){
return this.data('mask').getMaskedVal(val);
};
$.fn.unmask=function(){
clearInterval($.maskWatchers[ this.selector ]);
delete $.maskWatchers[ this.selector ];
return this.each(function(){
var dataMask=$(this).data('mask');
if(dataMask){
dataMask.remove().removeData('mask');
}});
};
$.fn.cleanVal=function(){
return this.data('mask').getCleanVal();
};
$.applyDataMask=function(selector){
var $selector;
selector=selector||$.jMaskGlobals.maskElements;
$selector=selector instanceof $ ? selector:$(selector);
$selector.filter($.jMaskGlobals.dataMaskAttr).each(HTMLAttributes);
};
globals={
maskElements: 'input,td,span,div',
dataMaskAttr: '*[data-mask]',
dataMask: true,
watchInterval: 300,
watchInputs: true,
keyStrokeCompensation: 10,
useInput: ! /Chrome\/[2-4][0-9]|SamsungBrowser/.test(window.navigator.userAgent)&&eventSupported('input'),
watchDataMask: false,
byPassKeys: [ 9, 16, 17, 18, 36, 37, 38, 39, 40, 91 ],
translation: {
0: { pattern: /\d/ },
9: { pattern: /\d/, optional: true },
'#': { pattern: /\d/, recursive: true },
A: { pattern: /[a-zA-Z0-9]/ },
S: { pattern: /[a-zA-Z]/ }}
};
$.jMaskGlobals=$.jMaskGlobals||{};
globals=$.jMaskGlobals=$.extend(true, {}, globals, $.jMaskGlobals);
if(globals.dataMask){
$.applyDataMask();
}
setInterval(function(){
if($.jMaskGlobals.watchDataMask){
$.applyDataMask();
}}, globals.watchInterval);
},
window.jQuery,
window.Zepto
));
(function($, window, document){
'use strict';
var VariationForm=function($form, element, currentCart, variableProductContainers, epoObject){
var self=this;
self.field=element;
self.currentCart=currentCart;
self.variableProductContainers=variableProductContainers;
self.epoObject=epoObject;
self.$form=$form;
self.$wrap=$form.closest('.tc-epo-element-product-container-wrap');
self.$attributeFields=$form.find('.tc-epo-variable-product-selector');
self.$singleVariation=$form.find('.tc-epo-element-single-variation');
self.$resetVariations=$form.find('.tc-epo-element-variable-reset-variations');
self.variationData=$form.data('product_variations');
self.useAjax=false===self.variationData;
self.xhr=false;
self.loading=true;
self.variationId=$form.closest('.tc-epo-element-product-li-container').find('.tc-epo-element-product-container-variation-id input.product-variation-id');
self.getChosenAttributes=self.getChosenAttributes.bind(self);
self.findMatchingVariations=self.findMatchingVariations.bind(self);
self.isMatch=self.isMatch.bind(self);
self.toggleResetLink=self.toggleResetLink.bind(self);
$form.on('click.tc-variation-form', '.tc-epo-element-variable-reset-variations', { variationForm: self }, self.onReset);
$form.on('tc_hide_variation', { variationForm: self }, self.onHide);
$form.on('tc_show_variation', { variationForm: self }, self.onShow);
$form.on('tc_reset_data', { variationForm: self }, self.onResetDisplayedVariation);
$form.on('tc_reset_image', { variationForm: self }, self.onResetImage);
$form.on('change.tc-variation-form', '.tc-epo-variable-product-selector', { variationForm: self }, self.onChange);
$form.on('tc_found_variation.tc-variation-form', { variationForm: self }, self.onFoundVariation);
$form.on('tc_check_variations.tc-variation-form', { variationForm: self }, self.onFindVariation);
$form.on('tc_update_variation_values.tc-variation-form', { variationForm: self }, self.onUpdateAttributes);
$form.on('refresh.tc-variation-form', { variationForm: self }, self.onRefreshContainer);
$form.on('update_field.tc-variation-form', { variationForm: self }, self.onUpdateField);
self.variationId.val('');
setTimeout(function(){
$form.trigger('refresh');
$form.trigger('tc_variation_form');
self.loading=false;
}, 100);
};
VariationForm.prototype.onRefreshContainer=function(event){
var form=event.data.variationForm;
form.variableProductContainers.find('.tc-epo-element-product-container').removeClass('variations_form');
form.$form.addClass('variations_form');
form.$form.trigger('tc_check_variations.tc-variation-form');
};
VariationForm.prototype.onUpdateField=function(event, variation){
var form=event.data.variationForm;
var field;
var associatedSetter;
var associatedPrice;
var associatedRawPrice;
var associatedOriginalPrice;
var associatedRawOriginalPrice;
event.preventDefault();
if(! variation){
field=form.field;
associatedSetter=field;
if(field.is('select')){
associatedSetter=field.find('option:selected');
}
associatedPrice=0;
associatedRawPrice=0;
associatedOriginalPrice=0;
associatedRawOriginalPrice=0;
field.data('price_set', 1);
associatedSetter.data('associated_price_set', 1);
associatedSetter.data('price_set', 1);
associatedSetter.data('raw_price', associatedRawPrice);
associatedSetter.data('raw_original_price', associatedRawOriginalPrice);
associatedSetter.data('price', associatedPrice);
associatedSetter.data('original_price', associatedOriginalPrice);
field.data('price-changed', 1);
form.$form.trigger({
type: 'tm-epo-update',
norules: 2
});
form.currentCart.trigger({
type: 'tm-epo-update',
norules: 2
});
}};
VariationForm.prototype.onReset=function(event){
event.preventDefault();
event.data.variationForm.$attributeFields.val('').trigger('change');
event.data.variationForm.$form.trigger('tc_reset_data');
};
VariationForm.prototype.onHide=function(event){
event.preventDefault();
};
VariationForm.prototype.onShow=function(event){
event.preventDefault();
};
VariationForm.prototype.onResetDisplayedVariation=function(event){
var form=event.data.variationForm;
form.$form.find('.product-meta').find('.tc-product-sku').tc_reset_content();
form.$form.trigger('tc_reset_image');
form.$singleVariation.slideUp(200).trigger('tc_hide_variation');
};
VariationForm.prototype.onResetImage=function(event){
event.data.variationForm.$form.tc_variations_image_update(false);
};
VariationForm.prototype.onFindVariation=function(event){
var form=event.data.variationForm;
var attributes=form.getChosenAttributes();
var currentAttributes=attributes.data;
var cpfElement;
var matching_variations;
var variation;
if(attributes.count===attributes.chosenCount){
if(form.useAjax){
if(typeof wc_add_to_cart_variation_params==='undefined'){
return;
}
if(form.xhr){
form.xhr.abort();
}
cpfElement=form.$form.closest('.cpf-type-product');
form.$form.block({ message: null, overlayCSS: { background: '#fff', opacity: 0.6 }});
currentAttributes.product_id=parseInt(form.$form.data('product_id'), 10);
currentAttributes.discount=cpfElement.attr('data-discount');
currentAttributes.discount_type=cpfElement.attr('data-discount-type');
currentAttributes.discount_exclude_addons=cpfElement.attr('data-discount-exclude-addons');
form.xhr=$.ajax({
url: wc_add_to_cart_variation_params.wc_ajax_url.toString().replace('%%endpoint%%', 'get_variation'),
type: 'POST',
data: currentAttributes,
success: function(svariation){
if(svariation){
form.$form.trigger('tc_found_variation', [ svariation ]);
}else{
form.$form.trigger('tc_reset_data');
attributes.chosenCount=0;
if(! form.loading){
form.$form.find('.tc-epo-element-single-variation').after('<p class="wc-no-matching-variations woocommerce-info">' + wc_add_to_cart_variation_params.i18n_no_matching_variations_text + '</p>');
form.$form.find('.wc-no-matching-variations').slideDown(200);
form.$form.trigger('update_field', []);
}}
},
complete: function(){
form.$form.unblock();
}});
}else{
form.$form.trigger('tc_update_variation_values');
matching_variations=form.findMatchingVariations(form.variationData, currentAttributes);
variation=matching_variations.shift();
if(variation){
form.$form.trigger('tc_found_variation', [ variation ]);
}else{
form.$form.trigger('tc_reset_data');
attributes.chosenCount=0;
if(! form.loading){
form.$form.find('.tc-epo-element-single-variation').after('<p class="wc-no-matching-variations woocommerce-info">' + wc_add_to_cart_variation_params.i18n_no_matching_variations_text + '</p>');
form.$form.find('.wc-no-matching-variations').slideDown(200);
}}
}}else{
form.variationId.val('').trigger('change');
form.$form.trigger('update_field', []);
form.$form.trigger('tc_update_variation_values');
form.$form.trigger('tc_reset_data');
}
form.toggleResetLink(attributes.chosenCount > 0);
};
VariationForm.prototype.onFoundVariation=function(event, variation){
var form=event.data.variationForm,
$sku=form.$form.find('.product-meta').find('.tc-product-sku'),
$qtyWrap=form.$wrap.find('.tm-quantity-alt'),
$qty=$qtyWrap.find('input.tm-qty-alt'),
qtyMin=$.epoAPI.math.toInt($qty.attr('data-min')),
qtyMax=$.epoAPI.math.toInt($qty.attr('data-max')),
dataQtyMax=$qty.attr('data-max'),
purchasable=true,
template=false,
$template_html='';
if(variation.sku){
$sku.tc_set_content(variation.sku);
}else{
$sku.tc_reset_content();
}
form.$form.tc_variations_image_update(variation);
if(! variation.variation_is_visible){
template=wpTemplate('unavailable-variation-template');
}else{
template=wpTemplate('variation-template');
}
if(form.field.attr('data-no-price')){
variation.display_price='';
variation.display_regular_price='';
variation.price_html='';
}
form.$form.find('.tc-epo-element-product-container-cart').find('.stock').remove();
$template_html=template({
variation: variation
});
$template_html=$template_html.replace('', '');
$template_html=$template_html.replace('/*]]>*/', '');
form.$singleVariation.html($template_html);
form.variationId.val(variation.variation_id).trigger('change');
if(variation.is_sold_individually==='yes'){
$qty.val('1').attr('min', '1').attr('max', '1');
$qtyWrap.hide();
}else{
if(variation.min_qty!==''&&variation.min_qty > qtyMin&&qtyMin > 0){
qtyMin=variation.min_qty;
}
if(variation.max_qty!==''&&variation.max_qty < qtyMax){
qtyMax=variation.max_qty;
}
if(qtyMin!==''){
$qty.attr('min', qtyMin);
}else{
$qty.removeAttr('min');
}
if(dataQtyMax!==''){
$qty.attr('max', qtyMax);
}else{
$qty.removeAttr('max');
}
if(qtyMax&&$.epoAPI.math.toInt($qty.val()) > qtyMax){
$qty.val(qtyMax);
}
if(qtyMin > $.epoAPI.math.toInt($qty.val())){
$qty.val(qtyMin);
}
$qtyWrap.show();
}
if(! variation.is_purchasable||! variation.is_in_stock||! variation.variation_is_visible){
purchasable=false;
$qty.val('0').attr('min', '0').attr('max', '0');
$qtyWrap.hide();
}
$qty.trigger('change');
if($.epoAPI.util.trim(form.$singleVariation.text())){
form.$singleVariation.slideDown(200).trigger('tc_show_variation', [ variation, purchasable ]);
}else{
form.$singleVariation.show().trigger('tc_show_variation', [ variation, purchasable ]);
}
form.$form.trigger('update_field', [ variation ]);
};
VariationForm.prototype.onChange=function(event){
var form=event.data.variationForm;
var field=form.field;
form.variationId.val('').trigger('change');
form.$form.find('.wc-no-matching-variations').remove();
if(form.useAjax){
form.$form.trigger('tc_check_variations');
}else{
form.$form.trigger('woocommerce_variation_select_change');
form.$form.trigger('tc_check_variations');
}
form.$form.trigger('woocommerce_variation_has_changed');
setTimeout(function(){
field.closest('.tcowl-carousel').trigger('refresh.owl.carousel');
}, 50);
};
VariationForm.prototype.onUpdateAttributes=function(event){
var form=event.data.variationForm,
attributes=form.getChosenAttributes(),
currentAttributes=attributes.data;
if(form.useAjax){
return;
}
form.$attributeFields.each(function(index, el){
var current_attr_select=$(el);
var current_attr_name=current_attr_select.data('attribute_name')||current_attr_select.attr('name');
var show_option_none=$(el).data('show_option_none');
var option_gt_filter=':gt(0)';
var attached_options_count=0;
var new_attr_select=$('<select/>');
var selected_attr_val=current_attr_select.val()||'';
var selected_attr_val_valid=true;
var refSelect;
var checkAttributes;
var variations;
var num;
var i;
var len;
var variationAttributes;
var attr_name;
var attr_val;
var variation_active;
var $option_elements;
var $option_element;
var option_value;
if(! current_attr_select.data('attribute_html')){
refSelect=current_attr_select.clone();
refSelect.find('option').prop('disabled', false).prop('selected', false).removeAttr('attached');
current_attr_select.data('attribute_options', refSelect.find('option' + option_gt_filter).get());
current_attr_select.data('attribute_html', refSelect.html());
}
new_attr_select.html(current_attr_select.data('attribute_html'));
checkAttributes=$.extend(true, {}, currentAttributes);
checkAttributes[ current_attr_name ]='';
variations=form.findMatchingVariations(form.variationData, checkAttributes);
for(num in variations){
if(typeof variations[ num ]!=='undefined'){
variationAttributes=variations[ num ].attributes;
for(attr_name in variationAttributes){
if(Object.prototype.hasOwnProperty.call(variationAttributes, attr_name)){
attr_val=variationAttributes[ attr_name ];
variation_active='';
if(attr_name===current_attr_name){
if(variations[ num ].variation_is_active){
variation_active='enabled';
}
if(attr_val){
attr_val=$('<div/>').html(attr_val).text();
$option_elements=new_attr_select.find('option');
if($option_elements.length){
for(i=0, len=$option_elements.length; i < len; i++){
$option_element=$($option_elements[ i ]);
option_value=$option_element.val();
if(attr_val===option_value){
$option_element.addClass('attached ' + variation_active);
break;
}}
}}else{
new_attr_select.find('option:gt(0)').addClass('attached ' + variation_active);
}}
}}
}}
attached_options_count=new_attr_select.find('option.attached').length;
if(selected_attr_val){
selected_attr_val_valid=false;
if(0!==attached_options_count){
new_attr_select.find('option.attached.enabled').each(function(){
var thisVal=$(this).val();
if(selected_attr_val===thisVal){
selected_attr_val_valid=true;
return false;
}});
}}
if(attached_options_count > 0&&selected_attr_val&&selected_attr_val_valid&&'no'===show_option_none){
new_attr_select.find('option:first').remove();
option_gt_filter='';
}
new_attr_select.find('option' + option_gt_filter + ':not(.attached)').remove();
current_attr_select.html(new_attr_select.html());
current_attr_select.find('option' + option_gt_filter + ':not(.enabled)').prop('disabled', true);
if(selected_attr_val){
if(selected_attr_val_valid){
current_attr_select.val(selected_attr_val);
}else{
current_attr_select.val('').trigger('change');
}}else{
current_attr_select.val('');
}});
form.$form.trigger('woocommerce_update_variation_values');
};
VariationForm.prototype.getChosenAttributes=function(){
var data={};
var count=0;
var chosen=0;
this.$attributeFields.each(function(){
var attribute_name=$(this).data('attribute_name')||$(this).attr('name');
var value=$(this).val()||'';
if(value.length > 0){
chosen++;
}
count++;
data[ attribute_name ]=value;
});
return {
count: count,
chosenCount: chosen,
data: data
};};
VariationForm.prototype.findMatchingVariations=function(variations, attributes){
var matching=[];
var i;
var variation;
for(i=0; i < variations.length; i++){
variation=variations[ i ];
if(this.isMatch(variation.attributes, attributes)){
matching.push(variation);
}}
return matching;
};
VariationForm.prototype.isMatch=function(variation_attributes, attributes){
var match=true;
var val1;
var val2;
var attr_name;
for(attr_name in variation_attributes){
if(Object.prototype.hasOwnProperty.call(variation_attributes, attr_name)){
val1=variation_attributes[ attr_name ];
val2=attributes[ attr_name ];
if(val1!==undefined&&val2!==undefined&&val1.length!==0&&val2.length!==0&&val1!==val2){
match=false;
}}
}
return match;
};
VariationForm.prototype.toggleResetLink=function(on){
if(on){
if(this.$resetVariations.css('visibility')==='hidden'){
this.$resetVariations.css('visibility', 'visible').hide().fadeIn();
}}else{
this.$resetVariations.css('visibility', 'hidden');
}};
$.fn.tc_product_variation_form=function(element, currentCart, variableProductContainers, thisEpoObject){
new VariationForm(this, element, currentCart, variableProductContainers, thisEpoObject);
this.trigger('tc_product_variation_form');
return this;
};
$.fn.tc_set_content=function(content){
if(undefined===this.attr('data-o_content')){
this.attr('data-o_content', this.text());
}
this.text(content);
};
$.fn.tc_reset_content=function(){
if(undefined!==this.attr('data-o_content')){
this.text(this.attr('data-o_content'));
}};
$.fn.tc_set_variation_attr=function(attr, value){
if(undefined===this.attr('data-o_' + attr)){
this.attr('data-o_' + attr, ! this.attr(attr) ? '':this.attr(attr));
}
if(false===value){
this.removeAttr(attr);
}else{
this.attr(attr, value);
}};
$.fn.tc_reset_variation_attr=function(attr){
if(undefined!==this.attr('data-o_' + attr)){
this.attr(attr, this.attr('data-o_' + attr));
}};
$.fn.tc_variations_image_update=function(variation){
var $form=this,
$product_img_wrap=$form.find('.tc-product-image, .woocommerce-product-gallery__image, .woocommerce-product-gallery__image--placeholder').eq(0),
$product_img=$product_img_wrap.find('.wp-post-image'),
$product_link=$product_img_wrap.find('a').eq(0);
if(variation&&variation.image&&variation.image.src&&variation.image.src.length > 1){
$product_img.tc_set_variation_attr('src', variation.image.src);
$product_img.tc_set_variation_attr('height', variation.image.src_h);
$product_img.tc_set_variation_attr('width', variation.image.src_w);
$product_img.tc_set_variation_attr('srcset', variation.image.srcset);
$product_img.tc_set_variation_attr('sizes', variation.image.sizes);
$product_img.tc_set_variation_attr('title', variation.image.title);
$product_img.tc_set_variation_attr('data-caption', variation.image.caption);
$product_img.tc_set_variation_attr('alt', variation.image.alt);
$product_img.tc_set_variation_attr('data-src', variation.image.full_src);
$product_img.tc_set_variation_attr('data-large_image', variation.image.full_src);
$product_img.tc_set_variation_attr('data-large_image_width', variation.image.full_src_w);
$product_img.tc_set_variation_attr('data-large_image_height', variation.image.full_src_h);
$product_img_wrap.tc_set_variation_attr('data-thumb', variation.image.src);
$product_link.tc_set_variation_attr('href', variation.image.full_src);
}else{
$form.tc_variations_image_reset();
}};
$.fn.tc_variations_image_reset=function(){
var $form=this,
$product_img_wrap=$form.find('.tc-product-image, .woocommerce-product-gallery__image, .woocommerce-product-gallery__image--placeholder').eq(0),
$product_img=$product_img_wrap.find('.wp-post-image'),
$product_link=$product_img_wrap.find('a').eq(0);
$product_img.tc_reset_variation_attr('src');
$product_img.tc_reset_variation_attr('width');
$product_img.tc_reset_variation_attr('height');
$product_img.tc_reset_variation_attr('srcset');
$product_img.tc_reset_variation_attr('sizes');
$product_img.tc_reset_variation_attr('title');
$product_img.tc_reset_variation_attr('data-caption');
$product_img.tc_reset_variation_attr('alt');
$product_img.tc_reset_variation_attr('data-src');
$product_img.tc_reset_variation_attr('data-large_image');
$product_img.tc_reset_variation_attr('data-large_image_width');
$product_img.tc_reset_variation_attr('data-large_image_height');
$product_img_wrap.tc_reset_variation_attr('data-thumb');
$product_link.tc_reset_variation_attr('href');
};
function wpTemplate(templateId){
var html=document.getElementById('tmpl-' + templateId).textContent;
var hard=false;
hard=hard||/<#\s?data\./.test(html);
hard=hard||/{{{?\s?data\.(?!variation\.).+}}}?/.test(html);
hard=hard||/{{{?\s?data\.variation\.[\w-]*[^\s}]/.test(html);
if(hard){
return window.wp.template(templateId);
}
return function template(data){
var variation=data.variation||{};
var replacement;
return html.replace(/({{{?)\s?data\.variation\.([\w-]*)\s?(}}}?)/g, function(_, open, key, close){
if(open.length!==close.length){
return '';
}
replacement=variation[ key ]||'';
if(open.length===2){
return window.escape(replacement);
}
return replacement;
});
};}}(window.jQuery, window, document));
(function(window){
'use strict';
var empty=function(mixedVar){
var undef;
var key;
var i;
var len;
var emptyValues=[ undef, null, false, 0, '', '0' ];
for(i=0, len=emptyValues.length; i < len; i++){
if(mixedVar===emptyValues[ i ]){
return true;
}}
if(typeof mixedVar==='object'){
for(key in mixedVar){
if(mixedVar.hasOwnProperty(key)){
return false;
}}
return true;
}
return false;
};
var array_key_exists=function(key, search){
if(! search||(search.constructor!==Array&&search.constructor!==Object)){
return false;
}
return key in search;
};
var getNumberOfParameters=function(func){
const ARROW=true;
const FUNC_ARGS=ARROW ? /^(function)?\s*[^\(]*\(\s*([^\)]*)\)/m:/^(function)\s*[^\(]*\(\s*([^\)]*)\)/m;
const FUNC_ARG_SPLIT=/,/;
const FUNC_ARG=/^\s*(_?)(.+?)\1\s*$/;
const STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
return(( func||'')
.toString()
.replace(STRIP_COMMENTS, '')
.match(FUNC_ARGS)||[ '', '', '' ])[ 2 ]
.split(FUNC_ARG_SPLIT)
.map(function(arg){
return arg.replace(FUNC_ARG, function(all, underscore, name){
return name.split('=')[ 0 ].trim();
});
})
.filter(String)
.length;
};
var getNumberOfRequiredParameters=function(func){
return func.length;
};
var is_scalar=function(mixedVar){
return(/boolean|number|string/).test(typeof mixedVar);
};
var gettype=function(obj){
return {}.toString.call(obj).split(' ')[ 1 ].slice(0, -1).toLowerCase();
};
var floatval=function(s, d){
var n;
if(!(typeof s==='string'||typeof s==='number')||isNaN(s)){
if(d!==undefined){
return d;
}
return 0;
}
n=parseFloat(s);
if(isNaN(n)){
if(d!==undefined){
return d;
}
return s;
}
return n;
};
var strcmp=function(str1, str2){
return(( str1===str2) ? 0:(( str1 > str2) ? 1:-1));
};
var bindec=function(binaryString){
binaryString=(binaryString + '').replace(/[^01]/gi, '');
return parseInt(binaryString, 2);
};
var decbin=function(number){
if(number < 0){
number=0xFFFFFFFF + number + 1;
}
return parseInt(number, 10).toString(2);
};
var dechex=function(number){
if(number < 0){
number=0xFFFFFFFF + number + 1;
}
return parseInt(number, 10).toString(16);
};
var decoct=function(number){
if(number < 0){
number=0xFFFFFFFF + number + 1;
}
return parseInt(number, 10).toString(8);
};
var deg2rad=function(angle){
return angle * 0.017453292519943295;
};
var roundWithPrecision=function(num, dec=0){
var num_sign=num >=0 ? 1:-1;
return dec===0 ? Math.round(num):parseFloat(( Math.round(( num * Math.pow(10, dec)) +(num_sign * 0.0001)) / Math.pow(10, dec)).toFixed(dec));
};
var hexdec=function(hexString){
hexString=(hexString + '').replace(/[^a-f0-9]/gi, '');
return parseInt(hexString, 16);
};
var octdec=function(octString){
octString=(octString + '').replace(/[^0-7]/gi, '');
return parseInt(octString, 8);
};
var hypot=function(x, y){
var t;
x=Math.abs(x);
y=Math.abs(y);
t=Math.min(x, y);
x=Math.max(x, y);
t=t / x;
return x * Math.sqrt(1 +(t * t))||null;
};
var THEMECOMPLETE_EPO_MATH={
variables: {},
on_var_not_found: undefined,
on_var_validation: undefined,
operators: {},
functions: {},
cache: {},
construct: function(){
this.add_defaults();
this.set_division_by_zero_to_zero();
return this;
},
add_operator: function($operator){
this.operators[ $operator.operator ]=$operator;
return this;
},
evaluate: function($expression, $cache=true){
return this.execute($expression, $cache);
},
parse: function($expression){
var $tokens;
var result;
var $calculator;
var count=0;
var char;
for(char of $expression){
if(char==='('){
count++;
}else if(char===')'){
count--;
}
if(count < 0){
return false;
}}
if(count!==0){
return false;
}
$tokens=new THEMECOMPLETE_EPO_MATH_Tokenizer($expression, this.operators);
$tokens=$tokens.tokenize().build_reverse_polish_notation();
$calculator=new THEMECOMPLETE_EPO_MATH_Calculator(this.functions, this.operators);
result=$calculator.calculate($tokens, this.variables, this.on_var_not_found, this);
if('number'!==gettype(result)||isNaN(result)){
return false;
}
return result;
},
execute: function($expression, $cache=true){
var $cache_key=$expression;
var $calculator;
var $tokens;
var result;
if(! array_key_exists($cache_key, this.cache)){
$tokens=new THEMECOMPLETE_EPO_MATH_Tokenizer($expression, this.operators);
$tokens=$tokens.tokenize().build_reverse_polish_notation();
if($cache){
this.cache[ $cache_key ]=$tokens;
}}else{
$tokens=this.cache[ $cache_key ];
}
$calculator=new THEMECOMPLETE_EPO_MATH_Calculator(this.functions, this.operators);
result=$calculator.calculate($tokens, this.variables, this.on_var_not_found, this);
if('number'!==gettype(result)||isNaN(result)){
result=0;
}
return result;
},
add_function: function($name, $function){
this.functions[ $name ]=new THEMECOMPLETE_EPO_MATH_CustomFunction($name, $function);
return this;
},
get_vars: function(){
return this.variables;
},
get_var: function($variable){
if(! array_key_exists($variable, this.variables)){
if(this.on_var_not_found&&'function'===typeof this.on_var_not_found){
this.on_var_not_found($variable);
}
return THEMECOMPLETE_EPO_MATH_Error.trigger('Variable (' + $variable + ') not set', 'UnknownVariableError', 0);
}
return this.variables[ $variable ];
},
set_var: function($variable, $value){
if(this.on_var_validation&&'function'===typeof this.on_var_validation){
$value=this.on_var_validation($variable, $value);
}
this.variables[ $variable ]=$value;
return this;
},
var_exists: function($variable){
return array_key_exists($variable, this.variables);
},
set_vars: function($variables, $clear=true){
var $this=this;
if($clear){
this.remove_vars();
}
$variables.forFach(function($value, $name){
$this.set_var($name, $value);
});
return this;
},
set_var_not_found_handler: function($handler){
this.on_var_not_found=$handler;
return this;
},
set_var_validation_handler: function($handler){
this.on_var_validation=$handler;
return this;
},
remove_var: function($variable){
delete this.variables[ $variable ];
return this;
},
remove_vars: function(){
this.variables={};
this.on_var_not_found=null;
return this;
},
get_operators: function(){
return this.operators;
},
get_functions: function(){
return this.functions;
},
remove_operator: function($operator){
delete this.operators[ $operator ];
},
set_division_by_zero_to_zero: function(){
this.add_operator(new THEMECOMPLETE_EPO_MATH_Operator(
'/',
false,
180,
function($a, $b){
$a=Number($a);
$b=Number($b);
return 0==$b ? 0:$a / $b;
}
)
);
return this;
},
get_cache: function(){
return this.cache;
},
clear_cache: function(){
this.cache=[];
},
add_defaults: function(){
var $this=this;
var default_operators=this.default_operators();
var default_functions=this.default_functions();
Object.keys(default_operators).forEach(function($name){
var $operator=default_operators[ $name ];
$this.add_operator(new THEMECOMPLETE_EPO_MATH_Operator($name, $operator[ 2 ], $operator[ 1 ], $operator[ 0 ]));
});
Object.keys(default_functions).forEach(function($name){
var $callable=default_functions[ $name ];
$this.add_function($name, $callable);
});
this.on_var_validation=this.default_var_validation;
this.variables=this.default_vars();
return this;
},
default_operators: function(){
return {
'+': [
function($a, $b){
$a=floatval($a, 0);
$b=floatval($b, 0);
return $a + $b;
},
170,
false
],
'-': [
function($a, $b){
$a=floatval($a, 0);
$b=floatval($b, 0);
return $a - $b;
},
170,
false
],
uPos: [
function($a){
$a=floatval($a, 0);
return $a;
},
200,
false
],
uNeg: [
function($a){
$a=floatval($a, 0);
return 0 - $a;
},
200,
false
],
'*': [
function($a, $b){
$a=floatval($a, 0);
$b=floatval($b, 0);
return $a * $b;
},
180,
false
],
'/': [
function($a, $b){
$a=floatval($a, 0);
$b=floatval($b, 0);
if(empty($b)){
return THEMECOMPLETE_EPO_MATH_Error.trigger('Division By Zero', 'DivisionByZeroError', 0);
}
return $a / $b;
},
180,
false
],
'^': [
function($a, $b){
$a=floatval($a, 0);
$b=floatval($b, 0);
return Math.pow($a, $b);
},
220,
true
],
'%': [
function($a, $b){
$a=floatval($a, 0);
$b=floatval($b, 0);
return $a % $b;
},
180,
false
],
'&&': [
function($a, $b){
$a=String($a);
$b=String($b);
if($a.isNumeric()){
$a=floatval($a, 0);
}
if($b.isNumeric()){
$b=floatval($b, 0);
}
return $a&&$b ? 1:0;
},
100,
false
],
'||': [
function($a, $b){
$a=String($a);
$b=String($b);
if($a.isNumeric()){
$a=floatval($a, 0);
}
if($b.isNumeric()){
$b=floatval($b, 0);
}
return $a||$b ? 1:0;
},
90,
false
],
'==': [
function($a, $b){
$a=String($a);
$b=String($b);
if($a.isNumeric()&&$b.isNumeric()){
return floatval($a)===floatval($b) ? 1:0;
}
return 0===strcmp($a, $b) ? 1:0;
},
140,
false
],
'!=': [
function($a, $b){
$a=String($a);
$b=String($b);
if($a.isNumeric()&&$b.isNumeric()){
return floatval($a)!==floatval($b) ? 1:0;
}
return 0!==strcmp($a, $b) ? 1:0;
},
140,
false
],
'>=': [
function($a, $b){
$a=String($a);
$b=String($b);
if($a.isNumeric()){
$a=floatval($a, 0);
}
if($b.isNumeric()){
$b=floatval($b, 0);
}
return $a >=$b ? 1:0;
},
150,
false
],
'>': [
function($a, $b){
$a=String($a);
$b=String($b);
if($a.isNumeric()){
$a=floatval($a, 0);
}
if($b.isNumeric()){
$b=floatval($b, 0);
}
return $a > $b ? 1:0;
},
150,
false
],
'<=': [
function($a, $b){
$a=String($a);
$b=String($b);
if($a.isNumeric()){
$a=floatval($a, 0);
}
if($b.isNumeric()){
$b=floatval($b, 0);
}
return $a <=$b ? 1:0;
},
150,
false
],
'<': [
function($a, $b){
$a=String($a);
$b=String($b);
if($a.isNumeric()){
$a=floatval($a, 0);
}
if($b.isNumeric()){
$b=floatval($b, 0);
}
return $a < $b ? 1:0;
},
150,
false
]
};},
default_functions: function(){
var $this=this;
return {
abs: Math.abs,
acos: Math.acos,
acosh: Math.acosh,
arcsin: Math.asin,
arcctg: function($arg){
return(Math.PI / 2) - Math.atan($arg);
},
arccot: function($arg){
return(Math.PI / 2) - Math.atan($arg);
},
arccotan: function($arg){
return(Math.PI / 2) - Math.atan($arg);
},
arcsec: function($arg){
return Math.acos(1 / $arg);
},
arccosec: function($arg){
return Math.asin(1 / $arg);
},
arccsc: function($arg){
return Math.asin(1 / $arg);
},
arccos: Math.acos,
arctan: Math.atan,
arctg: Math.atan,
array: function(...$args){
return $args;
},
asin: Math.asin,
atan: Math.atan,
atan2: Math.atan2,
atanh: Math.atanh,
atn: Math.atan,
avg: function($arg1, ...$args){
var sum;
if(Array.isArray($arg1)){
if(0===$arg1.length){
return THEMECOMPLETE_EPO_MATH_Error.trigger('Array must contain at least one element!', 'InvalidArgumentError', 0);
}}
$args=[].concat.apply([], [ $arg1, ...$args ]);
sum=$args.reduce(function(previousValue, currentValue){
return floatval(currentValue, 0) + floatval(previousValue, 0);
});
return sum / $args.length;
},
average: function($arg1, ...$args){
var sum;
if(Array.isArray($arg1)){
if(0===$arg1.length){
return THEMECOMPLETE_EPO_MATH_Error.trigger('Array must contain at least one element!', 'InvalidArgumentError', 0);
}}
$args=[].concat.apply([], [ $arg1, ...$args ]);
sum=$args.reduce(function(previousValue, currentValue){
return floatval(currentValue, 0) + floatval(previousValue, 0);
});
return sum / $args.length;
},
bindec: bindec,
ceil: Math.ceil,
cos: Math.cos,
cosec: function($arg){
return Math.sin(1 / $arg);
},
csc: function($arg){
return Math.sin(1 / $arg);
},
cosh: Math.cosh,
ctg: function($arg){
return Math.cos($arg) / Math.sin($arg);
},
cot: function($arg){
return Math.cos($arg) / Math.sin($arg);
},
cotan: function($arg){
return Math.cos($arg) / Math.sin($arg);
},
cotg: function($arg){
return Math.cos($arg) / Math.sin($arg);
},
ctn: function($arg){
return Math.cos($arg) / Math.sin($arg);
},
decbin: decbin,
dechex: dechex,
decoct: decoct,
deg2rad: deg2rad,
exp: Math.exp,
expm1: Math.expm1,
floor: Math.floor,
int: Math.floor,
fmod: function($arg1, $arg2){
return $arg1 % $arg2;
},
hexdec: hexdec,
hypot: hypot,
if: function($expr, $trueval, $falseval){
var $exres;
if(0===$expr||1===$expr||true===$expr||false===$expr){
$exres=$expr;
}else{
$exres=$this.execute($expr);
}
if($exres){
return $this.execute($trueval);
}
return $this.execute($falseval);
},
intdiv: function($arg1, $arg2){
return Math.trunc(Math.trunc($arg1) / Math.trunc($arg2));
},
ln: Math.log,
lg: Math.log10,
log: Math.log,
log1p: Math.log1p,
max: function($arg1, ...$args){
var $array;
if(Array.isArray($arg1)&&0===$arg1.length){
return THEMECOMPLETE_EPO_MATH_Error.trigger('Array must contain at least one element!', 'InvalidArgumentError', 0);
}
$array=Array.isArray($arg1) ? $arg1:[ $arg1, ...$args ];
$array=$array.map(floatval);
return Math.max(...$array);
},
min: function($arg1, ...$args){
var $array;
if(Array.isArray($arg1)&&0===$arg1.length){
return THEMECOMPLETE_EPO_MATH_Error.trigger('Array must contain at least one element!', 'InvalidArgumentError', 0);
}
$array=Array.isArray($arg1) ? $arg1:[ $arg1, ...$args ];
$array=$array.map(floatval);
return Math.min(...$array);
},
octdec: octdec,
pi: function(){
return Math.PI;
},
pow: Math.pow,
rad2deg: function(angle){
return angle * 57.29577951308232;
},
round: roundWithPrecision,
sin: Math.sin,
sinh: Math.sinh,
sec: function($arg){
return 1 / Math.cos($arg);
},
sqrt: Math.sqrt,
tan: Math.tan,
tanh: Math.tanh,
tn: Math.tan,
tg: Math.tan,
lookuptable: function(field, lookupTableId){
var lookupTables;
var x;
var y;
var table;
var xColumn;
var price=0;
var tableNum=0;
var TMEPOJS=window.TMEPOJS;
if(TMEPOJS){
lookupTables=window&&window.jQuery&&window.jQuery.epoAPI&&window.jQuery.epoAPI.util.parseJSON(TMEPOJS.lookupTables);
if(lookupTables){
if(Array.isArray(lookupTableId)){
tableNum=lookupTableId[ 1 ];
lookupTableId=lookupTableId[ 0 ];
}
if(empty(lookupTableId)){
return 0;
}
if(empty(tableNum)){
tableNum=0;
}
if(Array.isArray(field)){
x=String(field[ 0 ]);
y=String(field[ 1 ]);
}else{
x=String(field);
y='';
}
table=lookupTables[ lookupTableId ];
if(table){
table=table[ tableNum ];
if(table){
table=table.data;
xColumn=table[ x ];
if(xColumn===undefined&&x && x!==undefined){
if(x.isNumeric()&&floatval(x)===0){
xColumn=table[ Object.keys(table)[ 0 ] ];
}else if(x){
x=$this.find_lookup_table_index(x, table);
xColumn=table[ x ];
}}
if(xColumn!==undefined){
if(y&&y!==undefined){
y=$this.find_lookup_table_index(y, xColumn);
}else{
y=Object.keys(xColumn)[ 0 ];
}
if(y==='max'){
price=floatval(xColumn[ Object.keys(xColumn)[ Object.keys(xColumn).length - 1 ] ]);
}else{
price=floatval(xColumn[ y ]);
}}
}}
}}
return price;
},
concat: function($arg1, ...$args){
var $array;
if(Array.isArray($arg1)&&0===$arg1.length){
return THEMECOMPLETE_EPO_MATH_Error.trigger('Array must contain at least one element!', 'InvalidArgumentError', 0);
}
$array=Array.isArray($arg1) ? $arg1:[ $arg1, ...$args ];
return $array.join('');
}};},
find_lookup_table_index: function(value, table){
var r;
var keys=Object.keys(table);
var hasNumericValuesOrMaxLast=function(arr){
var lastElement=arr[ arr.length - 1 ];
var areAllNumericValues=arr.every(function(val){
return String(val).isNumeric();
});
return areAllNumericValues||lastElement==='max';
};
if(hasNumericValuesOrMaxLast(keys)){
value=String(value).isNumeric() ? floatval(value):value;
r=keys.map(function(n){
return String(n).isNumeric() ? floatval(n):n;
}).reduce(function(a, b){
if(b==='max'&&value > a){
return b;
}
if(a==='max'&&value > b){
return a;
}
if(a < b){
if(value > a&&value <=b){
return b;
}}else{
if(( value > b&&value <=a)||(value > a||b==='max')){
return a;
}
return b;
}
if(value > b){
return b;
}
return a;
});
keys=keys.map(function(n){
return String(n).isNumeric() ? floatval(n):n;
});
if(value > Math.max(...keys)||value < Math.min(...keys)){
return false;
}}else{
r=value;
}
return r;
},
default_vars: function(){
return {
pi: 3.141592653589793,
e: 2.718281828459045
};},
default_var_validation: function($variable, $value){
if(! is_scalar($value)&&! Array.isArray($value)&&undefined!==$value){
return THEMECOMPLETE_EPO_MATH_Error.trigger('Variable (' + $variable + ') type (' + gettype($value) + ') is not scalar or array!', 0);
}
return $value;
}};
var THEMECOMPLETE_EPO_MATH_Tokenizer=function($input, $operators){
var node={
tokens: [],
input: '',
operators: {},
number_buffer: '',
string_buffer: '',
allow_negative: true,
in_single_quoted_string: false,
in_double_quoted_string: false,
is_number: function(ch){
return ch >='0'&&ch <='9';
},
is_alpha: function(ch){
return(ch >='a'&&ch <='z')||(ch >='A'&&ch <='Z')||'_'===ch;
},
is_dot: function(ch){
return '.'===ch;
},
is_lp: function(ch){
return '('===ch;
},
is_rp: function(ch){
return ')'===ch;
},
is_comma: function(ch){
return ','===ch;
},
empty_number_buffer_as_literal: function(){
if(this.number_buffer.length){
this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.LITERAL, this.number_buffer));
this.number_buffer='';
}},
empty_str_buffer_as_variable: function(){
if(''!==this.string_buffer){
this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.VARIABLE, this.string_buffer));
this.string_buffer='';
}},
tokenize: function(){
var is_last_char_escape=false;
var $this=this;
var $token_test=[];
this.tokens=[];
this.input.toString().split('').forEach(function(ch){
switch(true){
case $this.in_single_quoted_string:
if('\\'===ch){
if(is_last_char_escape){
$this.string_buffer +='\\';
is_last_char_escape=false;
}else{
is_last_char_escape=true;
}
break;
}else if("'"===ch){
if(is_last_char_escape){
$this.string_buffer +="'";
is_last_char_escape=false;
}else{
$this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.STRING, $this.string_buffer));
$this.in_single_quoted_string=false;
$this.string_buffer='';
}
break;
}
if(is_last_char_escape){
$this.string_buffer +='\\';
is_last_char_escape=false;
}
$this.string_buffer +=ch;
break;
case $this.in_double_quoted_string:
if('\\'===ch){
if(is_last_char_escape){
$this.string_buffer +='\\';
is_last_char_escape=false;
}else{
is_last_char_escape=true;
}
break;
}else if('"'===ch){
if(is_last_char_escape){
$this.string_buffer +='"';
is_last_char_escape=false;
}else{
$this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.STRING, $this.string_buffer));
$this.in_double_quoted_string=false;
$this.string_buffer='';
}
break;
}
if(is_last_char_escape){
$this.string_buffer +='\\';
is_last_char_escape=false;
}
$this.string_buffer +=ch;
break;
case '['===ch:
$this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.FUNCTION, 'array'));
$this.allow_negative=true;
$this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.LEFTPARENTHESIS, ''));
break;
case ' '===ch||'\n'===ch||'\r'===ch||'\t'===ch:
break;
case $this.is_number(ch):
if(''!==$this.string_buffer){
$this.string_buffer +=ch;
break;
}
$this.number_buffer +=ch;
$this.allow_negative=false;
break;
case 'e'===ch.toLowerCase():
if($this.number_buffer.length&&-1!==$this.number_buffer.indexOf('.')){
$this.number_buffer +='e';
$this.allow_negative=false;
break;
}
case $this.is_alpha(ch):
if($this.number_buffer.length){
$this.empty_number_buffer_as_literal();
$this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.OPERATOR, '*'));
}
$this.allow_negative=false;
$this.string_buffer +=ch;
break;
case '"'===ch:
$this.in_double_quoted_string=true;
break;
case "'"===ch:
$this.in_single_quoted_string=true;
break;
case $this.is_dot(ch):
$this.number_buffer +=ch;
$this.allow_negative=false;
break;
case $this.is_lp(ch):
if(''!==$this.string_buffer){
$this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.FUNCTION, $this.string_buffer));
$this.string_buffer='';
}else if($this.number_buffer.length){
$this.empty_number_buffer_as_literal();
$this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.OPERATOR, '*'));
}
$this.allow_negative=true;
$this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.LEFTPARENTHESIS, ch));
break;
case $this.is_rp(ch)||']'===ch :
$this.empty_number_buffer_as_literal();
$this.empty_str_buffer_as_variable();
$this.allow_negative=false;
$this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.RIGHTPARENTHESIS, ch));
break;
case $this.is_comma(ch):
$this.empty_number_buffer_as_literal();
$this.empty_str_buffer_as_variable();
$this.allow_negative=true;
$this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.PARAMSEPARATOR, ch));
break;
default:
if('-'===ch||'+'===ch){
if($this.allow_negative){
$this.allow_negative=false;
$this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.OPERATOR, '-'===ch ? 'uNeg':'uPos'));
break;
}
if($this.number_buffer&&'e'===$this.number_buffer[ $this.number_buffer.length - 1 ]){
$this.number_buffer +=ch;
break;
}}
$this.empty_number_buffer_as_literal();
$this.empty_str_buffer_as_variable();
if('$'!==ch){
if($this.tokens.length > 0){
if(THEMECOMPLETE_EPO_MATH_Constants.OPERATOR===$this.tokens[ $this.tokens.length - 1 ].type){
$this.tokens[ $this.tokens.length - 1 ].value +=ch;
}else{
$this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.OPERATOR, ch));
}}else{
$this.tokens.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.OPERATOR, ch));
}}
$this.allow_negative=true;
}});
this.empty_number_buffer_as_literal();
this.empty_str_buffer_as_variable();
this.tokens.forEach(function($token, $key){
$token_test[ $key ]=$token.type;
});
$token_test.forEach(function($type, $key){
if($key > 0&&'space'===$type&&'variable'===$token_test[ $key + 1 ]&&'variable'===$token_test[ $key - 1 ]){
$this.tokens[ $key ]=new THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.LITERAL, 0);
$this.tokens.splice($key + 1, 1);
$this.tokens.splice($key - 1, 1);
}});
return this;
},
build_reverse_polish_notation: function(){
var $tokens=[];
var $stack=[];
var $param_counter=[];
var $ctoken;
var $f;
var $op1;
var $op2;
var $this=this;
try {
this.tokens.forEach(function($token){
switch($token.type){
case THEMECOMPLETE_EPO_MATH_Constants.LITERAL:
case THEMECOMPLETE_EPO_MATH_Constants.VARIABLE:
case THEMECOMPLETE_EPO_MATH_Constants.STRING:
$tokens.push($token);
if($param_counter.length > 0&&0===$param_counter[ $param_counter.length - 1 ]){
$param_counter.push($param_counter.pop() + 1);
}
break;
case THEMECOMPLETE_EPO_MATH_Constants.FUNCTION:
if($param_counter.length > 0&&0===$param_counter[ $param_counter.length - 1 ]){
$param_counter.push($param_counter.pop() + 1);
}
$stack.push($token);
$param_counter.push(0);
break;
case THEMECOMPLETE_EPO_MATH_Constants.LEFTPARENTHESIS:
$stack.push($token);
break;
case THEMECOMPLETE_EPO_MATH_Constants.PARAMSEPARATOR:
while(THEMECOMPLETE_EPO_MATH_Constants.LEFTPARENTHESIS!==$stack[ $stack.length - 1 ].type){
if(0===$stack.length){
return THEMECOMPLETE_EPO_MATH_Error.trigger('Incorrect Brackets', 'IncorrectBracketsError', $tokens);
}
$tokens.push($stack.pop());
}
$param_counter.push($param_counter.pop() + 1);
break;
case THEMECOMPLETE_EPO_MATH_Constants.OPERATOR:
if(! array_key_exists($token.value, $this.operators)){
return THEMECOMPLETE_EPO_MATH_Error.trigger($token.value, 'UnknownOperatorError', $tokens);
}
$op1=$this.operators[ $token.value ];
while($stack.length > 0&&THEMECOMPLETE_EPO_MATH_Constants.OPERATOR===$stack[ $stack.length - 1 ].type){
if(! array_key_exists($stack[ $stack.length - 1 ].value, $this.operators)){
return THEMECOMPLETE_EPO_MATH_Error.trigger($stack[ $stack.length - 1 ].value, 'UnknownOperatorError', $tokens);
}
$op2=$this.operators[ $stack[ $stack.length - 1 ].value ];
if($op2.priority >=$op1.priority){
$tokens.push($stack.pop());
continue;
}
break;
}
$stack.push($token);
break;
case THEMECOMPLETE_EPO_MATH_Constants.RIGHTPARENTHESIS:
while(true){
try {
$ctoken=$stack.pop();
if(THEMECOMPLETE_EPO_MATH_Constants.LEFTPARENTHESIS===$ctoken.type){
break;
}
$tokens.push($ctoken);
} catch($e){
return THEMECOMPLETE_EPO_MATH_Error.trigger('Incorrect Brackets', 'IncorrectBracketsError', $tokens);
}}
if($stack.length > 0&&THEMECOMPLETE_EPO_MATH_Constants.FUNCTION===$stack[ $stack.length - 1 ].type){
$f=$stack.pop();
$f.param_count=$param_counter.pop();
$tokens.push($f);
}
break;
case THEMECOMPLETE_EPO_MATH_Constants.SPACE:
}});
} catch($e){
$tokens=[];
return THEMECOMPLETE_EPO_MATH_Error.trigger($e, 'Error', $tokens);
}
while(0!==$stack.length){
if(THEMECOMPLETE_EPO_MATH_Constants.LEFTPARENTHESIS===$stack[ $stack.length - 1 ].type||THEMECOMPLETE_EPO_MATH_Constants.RIGHTPARENTHESIS===$stack[ $stack.length - 1 ].type){
return THEMECOMPLETE_EPO_MATH_Error.trigger('Incorrect Brackets', 'IncorrectBracketsError', $tokens);
}
if(THEMECOMPLETE_EPO_MATH_Constants.SPACE===$stack[ $stack.length - 1 ].type){
$stack.pop();
continue;
}
$tokens.push($stack.pop());
}
return $tokens;
}};
node.input=$input;
node.operators=$operators;
return node;
};
var THEMECOMPLETE_EPO_MATH_Constants={
LITERAL: 'literal',
VARIABLE: 'variable',
OPERATOR: 'operator',
LEFTPARENTHESIS: 'LP',
RIGHTPARENTHESIS: 'RP',
FUNCTION: 'function',
PARAMSEPARATOR: 'separator',
STRING: 'string',
SPACE: 'space'
};
var THEMECOMPLETE_EPO_MATH_Token=function($type, $value, $name){
var node={
type: THEMECOMPLETE_EPO_MATH_Constants.LITERAL,
value: undefined,
name: undefined,
param_count: null
};
node.type=$type;
node.value=$value;
node.name=$name;
return node;
};
var THEMECOMPLETE_EPO_MATH_Operator=function($operator, $is_right_assoc, $priority, $function){
var node={
operator: '',
is_right_assoc: false,
priority: 0,
function: null,
places: 0
};
node.operator=$operator;
node.is_right_assoc=$is_right_assoc;
node.priority=$priority;
node.function=$function;
node.places=getNumberOfParameters($function);
node.execute=function($stack){
var $args=[];
var $i;
var $result;
if($stack.length < this.places){
$stack.splice(0, $stack.length);
return THEMECOMPLETE_EPO_MATH_Error.trigger('Incorrect Expression', 'IncorrectExpressionError', new THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.LITERAL, 0));
}
for($i=0; $i < this.places; $i++){
$args.unshift($stack.pop().value);
}
$result=this.function.apply(null, $args);
if('number'!==gettype($result)&&'string'!==gettype($result)){
$result=0;
}
return new THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.LITERAL, $result);
};
return node;
};
var THEMECOMPLETE_EPO_MATH_CustomFunction=function($name, $function){
var node={
name: '',
function: undefined,
required_param_count: undefined
};
node.name=$name;
node.function=$function;
node.required_param_count=getNumberOfRequiredParameters($function);
node.execute=function($stack, $param_count_in_stack){
var $args=[];
var $i;
var $argument;
var $result;
if($param_count_in_stack < this.required_param_count){
$param_count_in_stack=this.required_param_count;
}
if($param_count_in_stack < this.required_param_count){
$stack.splice(0, $stack.length);
return THEMECOMPLETE_EPO_MATH_Error.trigger(this.name, 'IncorrectNumberOfFunctionParametersError', new THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.LITERAL, 0));
}
if($param_count_in_stack > 0){
for($i=0; $i < $param_count_in_stack; $i++){
$argument=$stack.length ? $stack.pop().value:0;
if(null===$argument){
$argument='0';
$args.push($argument);
}else{
$args.unshift($argument);
}}
}
$result=this.function.apply(null, $args);
if($result===Infinity||$result===-Infinity){
$result=0;
}
return THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.LITERAL, $result);
};
return node;
};
var THEMECOMPLETE_EPO_MATH_Calculator=function($functions, $operators){
var node={
functions: {},
operators: {}};
node.functions=$functions;
node.operators=$operators;
node.calculate=function($tokens, $variables, $on_var_not_found=null, $math_object=false){
var $this=this;
var $stack=[];
var $result;
if(empty($tokens)){
return 0;
}
try {
$tokens.forEach(function($token){
var $variable;
var $value;
if(THEMECOMPLETE_EPO_MATH_Constants.LITERAL===$token.type||THEMECOMPLETE_EPO_MATH_Constants.STRING===$token.type){
$stack.push($token);
}else if(THEMECOMPLETE_EPO_MATH_Constants.VARIABLE===$token.type){
$variable=$token.value;
$value=null;
if(array_key_exists($variable, $variables)){
$value=$variables[ $variable ];
}else if($on_var_not_found&&'function'===typeof $on_var_not_found){
$value=$on_var_not_found($variable);
}else{
$value=$variable;
$math_object.variables[ $variable ]=$value;
$variables[ $variable ]=$value;
}
$stack.push(THEMECOMPLETE_EPO_MATH_Token(THEMECOMPLETE_EPO_MATH_Constants.LITERAL, $value, $variable));
}else if(THEMECOMPLETE_EPO_MATH_Constants.FUNCTION===$token.type){
if(! array_key_exists($token.value, $this.functions)){
$math_object.add_function($token.value,
function(){
return 0;
}
);
$this.functions=$math_object.functions;
if(! array_key_exists($token.value, $this.functions)){
return THEMECOMPLETE_EPO_MATH_Error.trigger($token.value, 'UnknownFunctionError', 0);
}
THEMECOMPLETE_EPO_MATH_Error.trigger($token.value, 'UnknownFunctionError', 0);
}
$stack.push($this.functions[ $token.value ].execute($stack, $token.param_count));
}else if(THEMECOMPLETE_EPO_MATH_Constants.OPERATOR===$token.type){
if(! array_key_exists($token.value, $this.operators)){
return THEMECOMPLETE_EPO_MATH_Error.trigger($token.value, 'UnknownOperatorError', 0);
}
$stack.push($this.operators[ $token.value ].execute($stack));
}});
} catch($e){
if(window.TMEPOJS&&window.TMEPOJS.WP_DEBUG){
window.console.log($e);
}}
$result=$stack.pop();
if(null===$result||! empty($stack)){
return THEMECOMPLETE_EPO_MATH_Error.trigger('Stack must be empty', 'IncorrectExpressionError', 0);
}
if(false===$result.value){
$result.value=0;
}
if(true===$result.value){
$result.value=1;
}
if('string'===gettype($result.value)&&$result.value.isNumeric()){
$result.value=floatval($result.value);
}
return $result.value;
};
return node;
};
var THEMECOMPLETE_EPO_MATH_Error={
trigger: function($msg, $code='', $return=false){
if(window.TMEPOJS&&window.TMEPOJS.WP_DEBUG){
window.console.log($code + '\n' + $msg);
window.console.trace();
}
if(window.TMEPOGLOBALADMINJS&&window.TMEPOGLOBALADMINJS.WP_DEBUG){
return $msg;
}
return $return;
}};
window.tcmexp=THEMECOMPLETE_EPO_MATH.construct();
}(window));
(function(window, document, $){
'use strict';
var tcAPI={};
var TMEPOJS=window.TMEPOJS;
var wp=window.wp;
var TMEPOQTRANSLATEXJS=window.TMEPOQTRANSLATEXJS;
var noUiSlider=window.noUiSlider;
var ClipboardEvent=window.ClipboardEvent;
var DataTransfer=window.DataTransfer;
var lateVariationEvent=[];
var latecpflogicactions=[];
var tmLazyloadContainer=false;
var variationsFormIsLoaded=false;
var jBody=$('body');
var jWindow=$(window);
var jDocument=$(document);
var errorObject;
var FloatingTotalsBox;
var currentAjaxButton;
var errorContainer=$(window);
var tcmexp=window.tcmexp;
var _=window._;
var priceCache=false;
var getLocalInputDecimalSeparator=function(){
if(TMEPOJS.tm_epo_global_input_decimal_separator===''){
return TMEPOJS.currency_format_decimal_sep;
}
return $.epoAPI.locale.getSystemDecimalSeparator();
};
var getLocalDecimalSeparator=function(){
if(TMEPOJS.tm_epo_global_displayed_decimal_separator===''){
return TMEPOJS.currency_format_decimal_sep;
}
return $.epoAPI.locale.getSystemDecimalSeparator();
};
var getLocalThousandSeparator=function(){
if(TMEPOJS.tm_epo_global_displayed_decimal_separator===''){
return TMEPOJS.currency_format_thousand_sep;
}
return $.epoAPI.locale.getSystemDecimalSeparator();
};
var getEpoDelay=function(){
if(TMEPOJS.tm_epo_start_animation_delay){
return TMEPOJS.tm_epo_start_animation_delay;
}else if(window.tc_epo_delay){
return window.tc_epo_delay;
}
return 500;
};
var getEpoAnimationDelay=function(){
if(TMEPOJS.tm_epo_animation_delay){
return TMEPOJS.tm_epo_start_animation_delay;
}else if(window.tc_epo_animation_delay){
return window.tc_epo_animation_delay;
}
return 500;
};
var originalVal=$.fn.val;
if(! TMEPOJS||! wp){
return;
}
$.fn.val=function(){
var result=originalVal.apply(this, arguments);
if(arguments.length > 0){
if($(this).is('.input-text.qty')){
$(this).trigger('change.cpf');
}}
return result;
};
if(TMEPOJS.tm_epo_no_lazy_load==='no'&&$.lazyLoadXT){
$.extend($.lazyLoadXT, {
autoInit: false,
updateEvent: $.lazyLoadXT.updateEvent + ' tmlazy'
});
}
tcAPI.localInputDecimalSeparator=getLocalInputDecimalSeparator();
tcAPI.localDecimalSeparator=getLocalDecimalSeparator();
tcAPI.localThousandSeparator=getLocalThousandSeparator();
tcAPI.epoDelay=getEpoDelay();
tcAPI.epoAnimationDelay=getEpoAnimationDelay();
tcAPI.getElementFromFieldCache=[];
tcAPI.epoSelector='.tc-extra-product-options';
tcAPI.associatedEpoSelector='.tc-extra-product-options-inline';
tcAPI.associatedEpoCart='.tc-epo-element-product-container-cart';
tcAPI.addToCartSelector="input[name='add-to-cart']";
tcAPI.tcAddToCartSelector='input.tc-add-to-cart';
tcAPI.qtySelector="input.qty,input[name='quantity'],select.qty,.drop-down-button #qty,.plus-minus-button #qty,.slider-input #amount";
tcAPI.associateQtySelector='input.tm-qty-alt';
tcAPI.addToCartButtonSelector='.add_to_cart_button, .single_add_to_cart_button';
tcAPI.compositeSelector='.bto_item,.component';
tcAPI.nativeProductPriceSelector='.woocommerce .product p.price';
tcAPI.associatedNativeProductPriceSelector='.product-price .associated-price';
tcAPI.templateEngine=$.epoAPI.applyFilter('tc_adjust_templateEngine', {
price: wp.template('tc-price'),
sale_price: wp.template('tc-sale-price'),
tc_chars_remanining: wp.template('tc-chars-remanining'),
tc_final_totals: wp.template('tc-final-totals'),
tc_floating_box: wp.template('tc-floating-box'),
tc_floating_box_nks: wp.template('tc-floating-box-nks'),
tc_formatted_price: wp.template('tc-formatted-price'),
tc_formatted_sale_price: wp.template('tc-formatted-sale-price'),
tc_lightbox: wp.template('tc-lightbox'),
tc_lightbox_zoom: wp.template('tc-lightbox-zoom'),
tc_section_pop_link: wp.template('tc-section-pop-link'),
tc_upload_messages: wp.template('tc-upload-messages')
});
$.tcAPI=function(){
return tcAPI;
};
$.tcAPIGet=function(name){
return tcAPI[ name ];
};
$.tcAPISet=function(name, value){
tcAPI[ name ]=value;
};
if($.tc_validator){
$.extend($.tc_validator.messages, {
required: TMEPOJS.tm_epo_global_validator_messages.required,
email: TMEPOJS.tm_epo_global_validator_messages.email,
url: TMEPOJS.tm_epo_global_validator_messages.url,
number: TMEPOJS.tm_epo_global_validator_messages.number,
digits: TMEPOJS.tm_epo_global_validator_messages.digits,
maxlengthsingle: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.maxlengthsingle),
maxlength: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.maxlength),
minlengthsingle: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.minlengthsingle),
minlength: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.minlength),
max: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.max),
min: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.min),
step: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.step),
lettersonly: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.lettersonly),
lettersspaceonly: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.lettersspaceonly),
alphanumeric: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.alphanumeric),
alphanumericunicode: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.alphanumericunicode),
alphanumericunicodespace: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.alphanumericunicodespace),
repeaterminrows: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.repeaterminrows),
repeatermaxrows: $.tc_validator.format(TMEPOJS.tm_epo_global_validator_messages.repeatermaxrows)
});
$.tc_validator.addMethod('alphanumeric',
function(value, element){
return this.optional(element)||/^[a-zA-Z0-9.-]+$/i.test(value);
},
$.tc_validator.messages.alphanumeric
);
$.tc_validator.addMethod('lettersonly',
function(value, element){
return this.optional(element)||/^[a-z]+$/i.test(value);
},
$.tc_validator.messages.lettersonly
);
$.tc_validator.addMethod('lettersspaceonly',
function(value, element){
return this.optional(element)||/^[a-z,\u0020]+$/i.test(value);
},
$.tc_validator.messages.lettersspaceonly
);
$.tc_validator.addMethod('alphanumericunicode',
function(value, element){
return (
this.optional(element) ||
/^[\u0030-\u0039\u0041-\u005A\u0061-\u007A\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0100-\u0148\u014A-\u017F\u0180-\u01BF\u01C4-\u024F\u1E02-\u1EF3\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u3040-\u309f\u30a0-\u30ff\u4e00-\u9faf\u3400-\u4dbf\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF\u10E60-\u10E7F\u1EC70-\u1ECBF\u1ED00-\u1ED4F\u1EE00-\u1EEFF\u0530-\u1058F]+$/i.test(value
)
);
},
$.tc_validator.messages.alphanumericunicode
);
$.tc_validator.addMethod('alphanumericunicodespace',
function(value, element){
return (
this.optional(element) ||
/^[\u0030-\u0039\u0041-\u005A\u0061-\u007A\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0100-\u0148\u014A-\u017F\u0180-\u01BF\u01C4-\u024F\u1E02-\u1EF3\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u3040-\u309f\u30a0-\u30ff\u4e00-\u9faf\u3400-\u4dbf\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF\u10E60-\u10E7F\u1EC70-\u1ECBF\u1ED00-\u1ED4F\u1EE00-\u1EEFF\u0530-\u1058F,\u0020]+$/i.test(value
)
);
},
$.tc_validator.messages.alphanumericunicodespace
);
$.tc_validator.addMethod('repeaterminrows',
function(value, element, param){
return $.epoAPI.math.toInt($(element).closest('.tc-element-inner-wrap').find('.tc-repeater-element').length) >=$.epoAPI.math.toInt(param);
},
$.tc_validator.messages.repeaterminrows
);
$.tc_validator.addMethod('repeatermaxrows',
function(value, element, param){
return $.epoAPI.math.toInt($(element).closest('.tc-element-inner-wrap').find('.tc-repeater-element').length) <=$.epoAPI.math.toInt(param);
},
$.tc_validator.messages.repeatermaxrows
);
$.tc_validator.addMethod('product_element_radio_qty',
function(value, element){
var qty=$(element).closest('.tm-element-ul-product').find('input.tc-epo-field-product.tmcp-radio:checked').closest('.tc-epo-element-product-holder').find('.tm-qty').first().val();
return qty > 0;
},
$.tc_validator.messages.required
);
$.tc_validator.addMethod('product_element_select_qty',
function(value, element){
var qty=$(element).closest('.tm-element-ul-product').find('select.tc-epo-field-product.tmcp-select').closest('.tc-epo-element-product-holder').find('.tm-qty').first().val();
return qty > 0;
},
$.tc_validator.messages.required
);
}
$.epoAPI.util.escapeSelector=(function(){
var selectorEscape=/([!"$%&'()*+,/:;<=>?@[\]^`{|}~])/g;
return function(selector){
return selector.replace(selectorEscape, '\\$1');
};}());
$.epoAPI.util.unformat=function(o){
var a=$.epoAPI.math.unformat(o, tcAPI.localInputDecimalSeparator);
var n=parseFloat(a);
if(! Number.isFinite(n)){
return a;
}
return n;
};
$.epoAPI.util.parseParams=function(string, decode){
if(typeof string!=='string'||string.split===undefined){
return [];
}
return string
.split('&')
.map(function(value){
var obj={};
if(decode===true){
value=decodeURIComponent(value.replace(/\+/g, '%20'));
}
value=value.split('=').map(function(v){
var a=v.split('?');
if(a.length > 1){
return a[ 1 ];
}
return v;
});
if(value.length > 1){
obj[ value[ 0 ] ]=value[ 1 ];
}
return obj;
})
.filter(function(n){
return n!==null;
})
.reduce(function(current, next){
return Object.assign({}, current, next);
}, {});
};
if(! $.tmempty){
$.tmempty=function(obj){
var emptyValues=[ undefined, null, false, 0, '', '0' ];
var isEmptyValue =
emptyValues.filter(function(item){
return obj===item;
}).length===1;
var isEmptyObject=false;
if(typeof obj==='object'){
isEmptyObject =
Object.keys(obj).filter(function(key){
return Object.prototype.hasOwnProperty.call(obj, key);
}).length===0;
return isEmptyObject;
}
return isEmptyValue||isEmptyObject;
};}
if(! $.tmType){
$.tmType=function(obj){
return Object.prototype.toString
.call(obj)
.match(/\s([a-zA-Z]+)/)[ 1 ]
.toLowerCase();
};}
if(! $.is_on_screen){
$.fn.is_on_screen=function(){
var win=$(window);
var scroll=$.epoAPI.dom.scroll();
var bounds=this.offset();
var viewport={
top: scroll.top,
left: scroll.left
};
viewport.right=viewport.left + win.width();
viewport.bottom=viewport.top + win.height();
bounds.right=bounds.left + this.outerWidth();
bounds.bottom=bounds.top + this.outerHeight();
return !(viewport.right < bounds.left||viewport.left > bounds.right||viewport.bottom < bounds.top||viewport.top > bounds.bottom);
};}
if(! $().tmtoggle){
$.fn.tmtoggle=function(){
var elements=this;
var is_one_open_for_accordion=false;
var init_done=0;
if(elements.length===0){
return;
}
if(window.tc_accordion_offset===undefined){
window.tc_accordion_offset=-100;
}
elements.each(function(){
var t=$(this);
var headers;
var wrap;
var wraps;
if(! t.data('tm-toggle-init')){
t.data('tm-toggle-init', 1);
headers=t.find('.tm-toggle');
wrap=t.find('.tm-collapse-wrap');
wraps=$('.tm-collapse.tmaccordion').find('.tm-toggle');
if(headers.length===0||wrap.length===0){
return;
}
if(wrap.is('.closed')){
$(wrap).removeClass('closed open').addClass('closed').hide();
$(headers).find('.tm-arrow').removeClass('tcfa-angle-down tcfa-angle-up').addClass('tcfa-angle-down');
$(headers).removeClass('toggle-header-open toggle-header-closed').addClass('toggle-header-closed');
}else{
$(wrap).removeClass('closed open').addClass('open').show();
$(headers).find('.tm-arrow').removeClass('tcfa-angle-down tcfa-angle-up').addClass('tcfa-angle-up');
$(headers).removeClass('toggle-header-open toggle-header-closed').addClass('toggle-header-open');
is_one_open_for_accordion=true;
}
headers.each(function(i, header){
$(header).on('closewrap.tmtoggle', function(){
if(t.is('.tmaccordion')&&$(wrap).is('.closed')){
return;
}
$(wrap).removeClass('closed open').addClass('closed');
$(this).find('.tm-arrow').removeClass('tcfa-angle-down tcfa-angle-up').addClass('tcfa-angle-down');
$(this).removeClass('toggle-header-open toggle-header-closed').addClass('toggle-header-closed');
$(wrap).removeClass('tm-animated fadein');
if(t.is('.tmaccordion')){
$(wrap).animate({ height: 'toggle' }, 100, function(){
$(wrap).hide();
});
}else{
$(wrap).animate({ height: 'toggle' }, 100, function(){
$(wrap).hide();
});
}
jWindow.trigger('tmlazy');
});
$(header).on('openwrap.tmtoggle', function(e, data){
if(t.is('.tmaccordion')){
$(wraps).not($(this)).trigger('closewrap.tmtoggle');
}
$(wrap).removeClass('closed open').addClass('open');
$(this).find('.tm-arrow').removeClass('tcfa-angle-down tcfa-angle-up').addClass('tcfa-angle-up');
$(this).removeClass('toggle-header-open toggle-header-closed').addClass('toggle-header-open');
$(wrap).show().removeClass('tm-animated fadein').addClass('tm-animated fadein');
setTimeout(function(){
jWindow.trigger('tmlazy');
}, 200);
setTimeout(function(){
if(data===undefined&&init_done&&t.is('.tmaccordion')&&! t.is_on_screen()){
jWindow.tcScrollTo($(header), 10, window.tc_accordion_offset);
}}, 110);
});
$(header).on('click.tmtoggle', function(e){
e.preventDefault();
if($(wrap).is('.closed')){
$(this).trigger('openwrap.tmtoggle');
}else{
$(this).trigger('closewrap.tmtoggle');
}});
$(header)
.find('.tm-qty')
.closest('.cpf-element')
.find('.tm-epo-field')
.on('change.cpf', function(){
$(header).trigger('openwrap.tmtoggle');
});
});
}});
if(undefined===window.tc_accordion_closed_on_page_load&&! is_one_open_for_accordion&&elements.filter('.tmaccordion').length > 0){
elements.filter('.tmaccordion').first().find('.tm-toggle').trigger('openwrap.tmtoggle', { nomove: 1 });
}
init_done=1;
return elements;
};}
if(! $().tmpoplink){
$.fn.tmpoplink=function(options){
var elements=this;
var floatbox_template;
var settings={
classname: 'flasho tc-wrapper cart-popup'
};
if(elements.length===0){
return;
}
if(options){
settings=$.extend({}, settings, options);
}
floatbox_template=function(data){
return $.epoAPI.template.html(wp.template('tc-cart-options-popup'), {
title: data.title,
id: data.id,
html: data.html,
close: TMEPOJS.i18n_close
});
};
return elements.each(function(){
var t=$(this);
var id;
var title;
var html;
var $_html;
if(t.is('.tc-poplink')){
return;
}
t.addClass('tc-poplink');
id=$(this).attr('href');
title=$(this).attr('data-title');
html=$(id).html();
if(! title){
title=TMEPOJS.i18n_addition_options;
}
$_html=floatbox_template({
id: 'tc-floatbox-content',
html: html,
title: title
});
t.on('click.tmpoplink', function(e){
$.tcFloatBox({
fps: 1,
ismodal: false,
refresh: 100,
width: '80%',
height: '80%',
classname: settings.classname,
data: $_html
});
e.preventDefault();
});
});
};}
function readableFileSize(a, b, c, d, e){
b=Math;
c=b.log;
d=1024;
e=c(a) / c(d) | 0;
return(( a / b.pow(d, e)).toFixed(e ? 2:0)) + ' ' +(e ? 'KMGTPEZY'[ --e ] + 'B':'bytes');
}
function toggleState(thisProductContainerWrap, disabled){
thisProductContainerWrap.toArray().forEach(function(setter){
setter=$(setter);
setter.find(':input').prop('disabled', function(i, v){
var state=$(this).data('tc-state');
if(state===undefined){
$(this).data('tc-state', v);
return disabled;
}
if(state===false){
return disabled;
}
return state;
});
});
}
function calculateTaxAmount(priceWithTax, _cart){
var taxable;
var tax_rate;
var pricesIncludeTax;
var tax_display_mode;
var current_variation;
var priceWithoutTax;
var taxAmount=0;
if(_cart){
taxable=_cart.attr('data-taxable');
tax_rate=_cart.attr('data-tax-rate');
pricesIncludeTax=_cart.attr('data-prices-include-tax')||TMEPOJS.prices_include_tax;
tax_display_mode=_cart.attr('data-tax-display-mode');
if(_cart.data('current_variation')!==undefined){
current_variation=_cart.data('current_variation');
}
if(current_variation!==undefined){
current_variation=_cart.data('current_variation');
taxable=current_variation.tc_is_taxable;
tax_rate=current_variation.tc_tax_rate;
}}
if(taxable){
tax_rate=parseFloat(tax_rate / 100);
if(pricesIncludeTax==='1'){
if(tax_display_mode==='incl'){
priceWithTax=parseFloat(priceWithTax);
priceWithoutTax=priceWithTax /(1 + tax_rate);
taxAmount=priceWithTax - priceWithoutTax;
}else{
priceWithoutTax=priceWithTax;
taxAmount=priceWithTax * tax_rate;
}}else if(tax_display_mode==='incl'){
priceWithoutTax=priceWithTax /(1 + tax_rate);
taxAmount=priceWithTax - priceWithoutTax;
}
taxAmount=$.epoAPI.math.toFloat(taxAmount);
}
return taxAmount;
}
function get_price_including_tax(price, _cart, element, force, variation, pricetype, doubleforce){
var taxable;
var tax_rate;
var prices_include_tax;
var is_vat_exempt;
var non_base_location_prices;
var taxes_of_one;
var base_taxes_of_one;
var modded_taxes_of_one;
var current_variation;
if(! Number.isFinite(parseFloat(price))){
price=0;
}
price=price * 10000;
if(_cart){
taxable=_cart.attr('data-taxable');
tax_rate=_cart.attr('data-tax-rate');
prices_include_tax=_cart.attr('data-prices-include-tax')||TMEPOJS.prices_include_tax;
is_vat_exempt=_cart.attr('data-is-vat-exempt');
non_base_location_prices=_cart.attr('data-non-base-location-prices');
taxes_of_one=_cart.attr('data-taxes-of-one');
base_taxes_of_one=_cart.attr('data-base-taxes-of-one');
modded_taxes_of_one=_cart.attr('data-modded-taxes-of-one');
if(_cart.data('current_variation')!==undefined){
current_variation=_cart.data('current_variation');
}else if(variation!==undefined){
current_variation=variation;
}
if(current_variation!==undefined){
current_variation=_cart.data('current_variation');
taxable=current_variation.tc_is_taxable;
tax_rate=current_variation.tc_tax_rate;
non_base_location_prices=current_variation.tc_non_base_location_prices;
taxes_of_one=current_variation.tc_taxes_of_one;
base_taxes_of_one=current_variation.tc_base_taxes_of_one;
modded_taxes_of_one=current_variation.tc_modded_taxes_of_one;
}
if(element){
if(element.data('tax-obj')){
tax_rate=element.data('tax-obj');
if(tax_rate.has_fee==='no'){
taxable=false;
}else if(tax_rate.has_fee==='yes'){
taxable=true;
}
tax_rate=tax_rate.tax_rate;
taxes_of_one=tax_rate / 100;
base_taxes_of_one=tax_rate / 100;
}}
if(taxable){
if(prices_include_tax==='1'&&! force){
if(is_vat_exempt==='1'){
if(non_base_location_prices==='1'){
price=parseFloat(price) -(taxes_of_one * price);
}else{
price=parseFloat(price) -(base_taxes_of_one * price);
}}else if(non_base_location_prices==='1'){
price=parseFloat(price) -(base_taxes_of_one * price) +(modded_taxes_of_one * price);
}}else if(element||current_variation===undefined||doubleforce){
price=parseFloat(price) +(parseFloat(price) * taxes_of_one);
}}
}
price=price / 10000;
return price;
}
function get_price_excluding_tax(price, _cart, element, force, variation, pricetype, doubleforce){
var taxable;
var tax_rate;
var taxes_of_one;
var base_taxes_of_one;
var prices_include_tax;
var current_variation;
var tax_display_mode;
if(! Number.isFinite(parseFloat(price))){
price=0;
}
price=price * 10000;
if(_cart){
tax_display_mode=_cart.attr('data-tax-display-mode');
taxable=_cart.attr('data-taxable');
tax_rate=_cart.attr('data-tax-rate');
taxes_of_one=_cart.attr('data-taxes-of-one');
base_taxes_of_one=_cart.attr('data-base-taxes-of-one');
prices_include_tax=_cart.attr('data-prices-include-tax');
if(_cart.data('current_variation')!==undefined){
current_variation=_cart.data('current_variation');
}else if(variation!==undefined){
current_variation=variation;
}
if(current_variation!==undefined){
taxable=current_variation.tc_is_taxable;
tax_rate=current_variation.tc_tax_rate;
taxes_of_one=current_variation.tc_taxes_of_one;
base_taxes_of_one=current_variation.tc_base_taxes_of_one;
}
if(element){
if(element.data('tax-obj')){
tax_rate=element.data('tax-obj');
if(tax_rate.has_fee==='no'){
taxable=false;
}else if(tax_rate.has_fee==='yes'){
taxable=true;
}
tax_rate=tax_rate.tax_rate;
base_taxes_of_one=tax_rate / 100;
}}
if(taxable){
if(prices_include_tax==='1'||force){
if(tax_display_mode==='incl'){
}else if(element||current_variation===undefined||force||doubleforce){
if(base_taxes_of_one===taxes_of_one){
price=parseFloat(price) - parseFloat(taxes_of_one * price);
}else{
price=price *(1 - parseFloat(base_taxes_of_one));
}}
}}
}
price=price / 10000;
return price;
}
function tm_set_tax_price(value, _cart, element, pricetype, force, variation, doubleforce){
var tax_display_mode;
if(! Number.isFinite(parseFloat(value))){
value=0;
}
if(_cart){
tax_display_mode=_cart.attr('data-tax-display-mode')||TMEPOJS.tax_display_mode;
if(tax_display_mode==='incl'){
value=get_price_including_tax(value, _cart, element, force, variation, pricetype, doubleforce);
}else{
value=get_price_excluding_tax(value, _cart, element, force, variation, pricetype, doubleforce);
}}
return value;
}
function formatPrice(value, args){
var data;
if(! args){
args={};}
data=$.extend({
symbol: '',
format: '',
decimal: tcAPI.localDecimalSeparator,
thousand: tcAPI.localThousandSeparator,
precision: TMEPOJS.currency_format_num_decimals
}, args);
if(TMEPOJS.tm_epo_trim_zeros==='yes'){
if(((value % 1).toString()!=='0')===false){
data.precision=0;
}}
return $.epoAPI.applyFilter('tc_formatPrice', $.epoAPI.math.format(value, data), data, value);
}
function tm_set_price_(value, sign, inc_tax_string){
return (
sign +
formatPrice(value, { symbol: TMEPOJS.currency_format_symbol, format: TMEPOJS.currency_format }) +
inc_tax_string
);
}
function tm_set_price(value, _cart, notax, taxstring, element, pricetype){
var inc_tax_string='';
var val;
var sign=TMEPOJS.option_plus_sign + ' ';
if(! notax){
value=tm_set_tax_price(value, _cart, element, pricetype);
}
val=Math.abs(value);
if(TMEPOJS.tm_epo_global_options_price_sign==='minus'){
sign='';
}
if(value < 0){
sign=TMEPOJS.option_minus_sign + ' ';
}
if(_cart&&taxstring){
inc_tax_string=_cart.attr('data-tax-string');
}
if(inc_tax_string===undefined){
inc_tax_string='';
}
return tm_set_price_(val, sign, inc_tax_string);
}
FloatingTotalsBox=function(this_epo_totals_container, is_quickview, main_cart){
this.this_epo_totals_container=this_epo_totals_container;
this.is_quickview=is_quickview;
this.main_cart=main_cart;
if(! is_quickview&&TMEPOJS.floating_totals_box&&TMEPOJS.floating_totals_box!=='disable'&&main_cart&&this_epo_totals_container.length){
this.init();
return this;
}
return false;
};
FloatingTotalsBox.prototype={
constructor: FloatingTotalsBox,
onUpdate: function(){
var tm_epo_totals_html=this.this_epo_totals_container.data('tm-html');
var tm_floating_box_data=this.this_epo_totals_container.data('tm-floating-box-data');
var values_obj=[];
var floatingBoxHtml;
var floatingBoxaddToCartButton;
if(tm_floating_box_data&&tm_floating_box_data.length){
$.each(tm_floating_box_data, function(i, row){
if(row.title===''){
row.title='&nbsp;';
}
if(row.value===''){
row.value='&nbsp;';
}
if(! row.title){
row.title='&nbsp;';
}else{
row.title=$('<div>' + row.title + '</div>');
row.title.find('span').remove();
row.title=row.title.html();
}
if(this.is_nks){
if(row.label_show!==''){
row.title='';
}
if(row.value_show!==''){
row.value='';
}}
if(TMEPOJS.tm_epo_auto_hide_price_if_zero==='yes'&&$.tmempty(row.price)===true){
row.price='';
}else{
row.price=tm_set_price(row.price, this.this_epo_totals_container, true, false);
}
values_obj.push({
label_show: row.label_show,
value_show: row.value_show,
title: row.title,
value: row.value,
quantity: row.quantity,
price: row.price
});
});
}
if(((tm_epo_totals_html&&tm_epo_totals_html==='')&&(! tm_floating_box_data||! tm_floating_box_data.length))||!(( tm_epo_totals_html&&tm_epo_totals_html!=='')||this.is_nks)){
tm_epo_totals_html='';
this.floatingBox.hide();
}
floatingBoxHtml=$.epoAPI.template.html(this.engineTemplate, {
html_before: TMEPOJS.floating_totals_box_html_before,
html_after: TMEPOJS.floating_totals_box_html_after,
option_label: TMEPOJS.i18n_option_label,
option_value: TMEPOJS.i18n_option_value,
option_qty: TMEPOJS.i18n_option_qty,
option_price: TMEPOJS.i18n_option_price,
values: values_obj,
totals: tm_epo_totals_html
});
this.floatingBox.html(floatingBoxHtml);
this.onUpdateScroll();
if(TMEPOJS.floating_totals_box_add_button==='yes'){
floatingBoxaddToCartButton=this.main_cart.find(tcAPI.addToCartButtonSelector).first();
floatingBoxaddToCartButton
.tcClone()
.addClass('tc-add-to-cart-button')
.on('click', function(){
floatingBoxaddToCartButton.trigger('click');
})
.appendTo(this.floatingBox);
}},
onUpdateScroll: function(){
if(TMEPOJS.floating_totals_box_visibility==='always'){
if(this.floatingBox.is(':empty')&&! this.is_nks_alt){
this.floatingBox.hide();
}else{
this.floatingBox.show();
}
return;
}
if(TMEPOJS.floating_totals_box_visibility==='hideafterscroll'){
if(jWindow.scrollTop() > $.epoAPI.math.toFloat(TMEPOJS.floating_totals_box_pixels)&&! this.is_nks_alt){
if(! this.floatingBox.is(':hidden')){
if(this.is_nks===false){
this.floatingBox.fadeOut();
}else{
this.floatingBox.hide();
}}
}else if(this.floatingBox.is(':hidden')||this.is_nks_alt){
if(! this.floatingBox.is(':empty')||this.is_nks_alt){
if(this.is_nks===false){
this.floatingBox.fadeIn();
}else{
this.floatingBox.show();
}}
}}
if(TMEPOJS.floating_totals_box_visibility==='afterscroll'){
if(jWindow.scrollTop() > $.epoAPI.math.toFloat(TMEPOJS.floating_totals_box_pixels)||this.is_nks_alt){
if(( this.floatingBox.is(':hidden')&&! this.floatingBox.is(':empty'))||this.is_nks_alt){
if(this.is_nks===false){
this.floatingBox.fadeIn();
}else{
this.floatingBox.show();
}}else if(! this.floatingBox.is(':hidden')&&this.floatingBox.is(':empty')){
if(this.is_nks===false){
this.floatingBox.fadeOut();
}else{
this.floatingBox.hide();
}}
}else if(! this.floatingBox.is(':hidden')){
if(this.is_nks===false){
this.floatingBox.fadeOut();
}else{
this.floatingBox.hide();
}}
}},
addEvents: function(){
this.onUpdate();
this.main_cart.on('tm-epo-after-update', this.onUpdate.bind(this));
this.main_cart.on('tm-epo-short-update', this.onUpdate.bind(this));
if(this.is_nks===false){
jWindow.on('scroll', this.onUpdateScroll.bind(this));
}},
init: function(){
this.floatingBox=$('<div class="tm-floating-box ' + TMEPOJS.floating_totals_box + '"></div>');
this.nks_selector=$('.tm-floating-box-nks').first();
this.alt_selector=$('.tm-floating-box-alt').first();
this.engineTemplate=tcAPI.templateEngine.tc_floating_box;
this.is_nks=false;
this.is_nks_alt=false;
if(this.nks_selector.length > 0){
this.is_nks=true;
this.floatingBox.removeClass('top left right bottom').appendTo(this.nks_selector).show();
}else if(this.alt_selector.length > 0){
this.floatingBox.removeClass('top left right bottom').appendTo(this.alt_selector).hide();
}else{
this.floatingBox.appendTo('body').hide();
}
if(this.nks_selector.length > 0||this.alt_selector.length > 0){
this.is_nks_alt=true;
this.engineTemplate=tcAPI.templateEngine.tc_floating_box_nks;
}
this.addEvents();
}};
$.tcFloatingTotalsBox=function(this_epo_totals_container, is_quickview, main_cart){
var data=false;
if(this_epo_totals_container&&this_epo_totals_container.length&&this_epo_totals_container.data('tcfloatingtotalsbox')===undefined){
data=new FloatingTotalsBox(this_epo_totals_container, is_quickview, main_cart);
this_epo_totals_container.data('tcfloatingtotalsbox', data);
}
return data;
};
$.tc_product_image={};
$.tc_product_image_store={};
$.tc_replace_object_values=function(obj1, obj2){
Object.keys(obj1).forEach(function(x){
Object.keys(obj1[ x ]).forEach(function(attr){
if(undefined!==obj2[ x ]&&undefined!==obj2[ x ][ attr ]&&Object.prototype.hasOwnProperty.call(obj2[ x ], attr)){
obj1[ x ][ attr ]=obj2[ x ][ attr ];
}});
});
return obj1;
};
$.tc_maybe_copy_object_values=function(obj1, obj2){
Object.keys(obj2).forEach(function(x){
Object.keys(obj2[ x ]).forEach(function(attr){
if(undefined!==obj2[ x ]&&Object.prototype.hasOwnProperty.call(obj2[ x ], attr)&&undefined!==obj2[ x ][ attr ]&&(undefined===obj1[ x ]||undefined===obj1[ x ][ attr ])){
if(undefined===obj1[ x ]){
obj1[ x ]={};}
obj1[ x ][ attr ]=obj2[ x ][ attr ];
}});
});
return obj1;
};
$.tc_pre_populate_store=function(){
var obj={};
obj[ 0 ]={};
obj[ 1 ]={};
obj[ 2 ]={};
obj[ 3 ]={};
obj[ 0 ].src='';
obj[ 0 ].srcset='';
obj[ 0 ].sizes='';
obj[ 0 ].title='';
obj[ 0 ].alt='';
obj[ 0 ][ 'data-src' ]='';
obj[ 0 ][ 'data-large_image' ]='';
obj[ 0 ][ 'data-large_image_width' ]='';
obj[ 0 ][ 'data-large_image_height' ]='';
obj[ 1 ][ 'data-thumb' ]='';
obj[ 2 ].src='';
obj[ 3 ].href='';
obj[ 3 ].title='';
return obj;
};
$.tc_populate_store=function(img, product_element){
var $gallery_img=product_element.find('.flex-control-nav li:eq(0) img');
var $gallery_wrapper=product_element.find('.woocommerce-product-gallery__wrapper ');
var $product_img_wrap=$gallery_wrapper.find('.woocommerce-product-gallery__image, .woocommerce-product-gallery__image--placeholder').eq(0);
var $product_img=img;
var $product_link=img.closest('a');
var obj={};
obj[ 0 ]={};
obj[ 1 ]={};
obj[ 2 ]={};
obj[ 3 ]={};
obj[ 0 ].src=$product_img.attr('src');
obj[ 0 ].srcset=$product_img.attr('srcset');
obj[ 0 ].sizes=$product_img.attr('sizes');
obj[ 0 ].title=$product_img.attr('title');
obj[ 0 ].alt=$product_img.attr('alt');
obj[ 0 ][ 'data-src' ]=$product_img.attr('data-src');
obj[ 0 ][ 'data-large_image' ]=$product_img.attr('data-large_image');
obj[ 0 ][ 'data-large_image_width' ]=$product_img.attr('data-large_image_width');
obj[ 0 ][ 'data-large_image_height' ]=$product_img.attr('data-large_image_height');
obj[ 1 ][ 'data-thumb' ]=$product_img_wrap.attr('data-thumb');
obj[ 2 ].src=$gallery_img.attr('src');
obj[ 3 ].href=$product_link.attr('href');
obj[ 3 ].title=$product_link.attr('title');
return obj;
};
$.tc_maybe_copy_object_values_from_img=function(obj1, img, product_element){
var $gallery_img=product_element.find('.flex-control-nav li:eq(0) img');
var $gallery_wrapper=product_element.find('.woocommerce-product-gallery__wrapper ');
var $product_img_wrap=$gallery_wrapper.find('.woocommerce-product-gallery__image, .woocommerce-product-gallery__image--placeholder').eq(0);
var $product_img=img;
var $product_link=img.closest('a');
var attrs;
var attr;
var attrs_product_img=[ 'src', 'srcset', 'sizes', 'title', 'alt', 'data-src', 'data-large_image', 'data-large_image_width', 'data-large_image_height', 'large-image' ];
var attrs_product_img_wrap=[ 'data-thumb' ];
var attrs_gallery_img=[ 'src' ];
var attrs_product_link=[ 'href', 'title' ];
var all=[ $product_img, $product_img_wrap, $gallery_img, $product_link ];
var attrs_all=[ attrs_product_img, attrs_product_img_wrap, attrs_gallery_img, attrs_product_link ];
all.forEach(function(item, index){
if(undefined!==item&&undefined!==item[ 0 ]){
attrs=item[ 0 ].attributes;
$.each(attrs, function(){
if(this.specified){
attr=this.name;
if($.inArray(attr, attrs_all[ index ])!==-1&&(undefined===obj1[ index ]||(undefined!==obj1[ index ]&&undefined===obj1[ index ][ attr ]))){
if(undefined===obj1[ index ]){
obj1[ index ]={};}
obj1[ index ][ attr ]=this.value;
}}
});
}});
return obj1;
};
$.fn.tc_set_attr=function(attr, value, id){
if(undefined===id){
id=0;
}
if(undefined===$.tc_product_image[ id ]||(undefined!==$.tc_product_image[ id ]&&undefined===$.tc_product_image[ id ][ attr ])){
if(undefined===$.tc_product_image[ id ]){
$.tc_product_image[ id ]={};}
$.tc_product_image[ id ][ attr ]='';
if(this.attr(attr)){
$.tc_product_image[ id ][ attr ]=this.attr(attr);
}}
if(false===value){
this.removeAttr(attr);
}else{
this.attr(attr, value);
}};
$.fn.tc_reset_attr=function(attr, id){
if(undefined===id){
id=0;
}
if(undefined===$.tc_product_image[ id ]){
return;
}
if(undefined!==$.tc_product_image[ id ][ attr ]){
this.attr(attr, $.tc_product_image[ id ][ attr ]);
}
delete $.tc_product_image[ id ][ attr ];
};
$.fn.tc_update_attr=function(attr, id){
if(undefined===id){
id=0;
}
if(undefined!==$.tc_product_image[ id ]){
$.tc_product_image[ id ][ attr ]=this.attr(attr);
}};
$.fn.tc_image_update=function(dom, image){
var element=$(dom);
var $form=this;
var $image=$(image);
var epo_object=$form.data('epo_object');
var image_info;
var $product_img;
var product_element=epo_object.main_product.closest('#product-' + epo_object.product_id);
var $product_element=product_element;
var $product_link;
var use_image_info;
if(product_element.length <=0){
$product_element=epo_object.main_product.closest('.post-' + epo_object.product_id);
}
if(element.is('select')){
element=element.children('option:selected');
}
image_info=element.data('image-variations');
if(TMEPOJS.tm_epo_global_product_image_selector!==''){
$product_img=$(TMEPOJS.tm_epo_global_product_image_selector);
}else{
$product_img=$product_element.find('a.woocommerce-main-image img, img.woocommerce-main-image,a img').not('.thumbnails img,.product_list_widget img,img.emoji,a.woocommerce-product-gallery__trigger img').first();
}
$product_link=$product_img.closest('a');
if($product_img.length > 1){
$product_img=$product_img.first();
}
if(element&&image_info&&$image.length > 0){
$image.removeAttr('data-o_src').removeAttr('data-o_title').removeAttr('data-o_alt').removeAttr('data-o_srcset').removeAttr('data-o_sizes').removeAttr('srcset').removeAttr('sizes');
use_image_info=image_info.imagep;
if(! image_info.imagep.image_link){
use_image_info=image_info.image;
}
$image.attr('title', use_image_info.image_title);
$image.attr('alt', use_image_info.image_alt);
if(use_image_info.image_srcset){
$image.attr('srcset', use_image_info.image_srcset);
}
if(use_image_info.image_sizes){
$image.attr('sizes', use_image_info.image_sizes);
}
$product_img.tc_set_attr('title', use_image_info.image_title);
$product_img.tc_set_attr('alt', use_image_info.image_alt);
$product_img.tc_set_attr('data-large-image', use_image_info.image_link);
if($product_img.data.wc27_zoom_target){
$product_img.data.wc27_zoom_target.tc_set_attr('data-thumb', use_image_info.image_link);
$product_element.find('.flex-control-nav li:eq(0) img').tc_set_attr('src', use_image_info.image_link);
}
$product_link.tc_set_attr('href', use_image_info.image_link);
$product_link.tc_set_attr('title', use_image_info.image_caption);
}else{
$product_img.tc_reset_attr('title');
$product_img.tc_reset_attr('alt');
$product_img.tc_reset_attr('data-large-image');
if($product_img.data.wc27_zoom_target){
$product_img.data.wc27_zoom_target.tc_reset_attr('data-thumb');
$product_element.find('.flex-control-nav li:eq(0) img').tc_reset_attr('src');
}
$product_link.tc_reset_attr('href');
$product_link.tc_reset_attr('title');
}};
$.fn.tm_find_matching_variations=function(product_variations, settings){
var matching=[];
var i;
var variation;
if(product_variations){
for(i=0; i < product_variations.length; i +=1){
variation=product_variations[ i ];
if($.fn.tm_variations_match(variation.attributes, settings)){
matching.push(variation);
}}
}
return matching;
};
$.fn.tm_variations_match=function(attrs1, attrs2){
var match=true;
var val1;
var val2;
Object.keys(attrs1).forEach(function(x){
if(Object.prototype.hasOwnProperty.call(attrs1, x)){
val1=attrs1[ x ];
val2=attrs2[ x ];
if(val1!==undefined&&val2!==undefined&&val1.length!==0&&val2.length!==0&&val1!==val2){
match=false;
}}
});
return match;
};
function get_element_from_field(element){
var $element=$(element);
var data_uniqid;
var the_epo_id;
var _class;
var epoContainer;
if($element.length===0){
return;
}
if($element.is('.cpf-section')){
return element.find('.tm-epo-field');
}
data_uniqid=$element.attr('data-uniqid');
epoContainer=$element.closest('.tc-extra-product-options');
the_epo_id=epoContainer.attr('data-epo-id');
if(! epoContainer.is('.reactivate')&&tcAPI.getElementFromFieldCache&&tcAPI.getElementFromFieldCache[ the_epo_id ]&&tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ]){
return tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ];
}
_class=$element
.attr('class')
.split(' ')
.map(function(cls){
if(cls.indexOf('cpf-type-', 0)!==-1){
return cls;
}
return null;
})
.filter(function(v){
if(v!==null&&v!==undefined){
return v;
}
return null;
});
if(_class.length > 0){
_class=_class[ 0 ];
if(_class==='cpf-type-product'){
if($element.is('.cpf-type-product-mode-product')||$element.is('.cpf-type-product-checkbox')||$element.is('.cpf-type-product-thumbnailmultiple')){
_class='cpf-type-checkbox';
}else if($element.is('.cpf-type-product-dropdown')){
_class='cpf-type-select';
}else{
_class='cpf-type-radio';
}}
switch(_class){
case 'cpf-type-radio':
tcAPI.getElementFromFieldCache[ the_epo_id ]=[];
tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ]=$element.find('.tm-epo-field.tmcp-radio');
return tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ];
case 'cpf-type-checkbox':
tcAPI.getElementFromFieldCache[ the_epo_id ]=[];
tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ]=$element.find('.tm-epo-field.tmcp-checkbox');
return tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ];
case 'cpf-type-select':
tcAPI.getElementFromFieldCache[ the_epo_id ]=[];
tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ]=$element.find('.tm-epo-field.tmcp-select');
return tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ];
case 'cpf-type-selectmultiple':
tcAPI.getElementFromFieldCache[ the_epo_id ]=[];
tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ]=$element.find('.tm-epo-field.tmcp-selectmultiple');
return tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ];
case 'cpf-type-textarea':
tcAPI.getElementFromFieldCache[ the_epo_id ]=[];
tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ]=$element.find('.tm-epo-field.tmcp-textarea');
return tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ];
case 'cpf-type-textfield':
tcAPI.getElementFromFieldCache[ the_epo_id ]=[];
tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ]=$element.find('.tm-epo-field.tmcp-textfield');
return tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ];
case 'cpf-type-color':
tcAPI.getElementFromFieldCache[ the_epo_id ]=[];
tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ]=$element.find('.tm-epo-field.tm-color-picker');
return tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ];
case 'cpf-type-range':
tcAPI.getElementFromFieldCache[ the_epo_id ]=[];
tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ]=$element.find('.tm-epo-field.tmcp-range');
return tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ];
case 'cpf-type-date':
tcAPI.getElementFromFieldCache[ the_epo_id ]=[];
tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ]=$element.find('.tm-epo-field.tmcp-date');
return tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ];
case 'cpf-type-time':
tcAPI.getElementFromFieldCache[ the_epo_id ]=[];
tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ]=$element.find('.tm-epo-field.tmcp-time');
return tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ];
case 'cpf-type-variations':
tcAPI.getElementFromFieldCache[ the_epo_id ]=[];
tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ]=$element.closest('.cpf-section').find('.tm-epo-field.tm-epo-variation-element');
return tcAPI.getElementFromFieldCache[ the_epo_id ][ data_uniqid ];
}}
}
if(! $().tclightbox){
$.fn.tclightbox=function(){
var elements=this;
if(elements.length===0){
return;
}
return elements.each(function(){
var $this=$(this);
var _imgsrc;
var _label;
var _input;
var tclightboxwrap;
var _img_button;
var preload_img;
var addButtonEvent;
if($this.is('.tcinit')){
return;
}
_imgsrc=$this.attr('src')||$this.attr('data-original');
_label=$this.closest('label');
_input=_label.closest('.tmcp-field-wrap').find(".tm-epo-field[id='" + _label.attr('for') + "']");
_imgsrc=_input.attr('data-imagel')||_input.attr('data-imagep')||_input.attr('data-image')||_imgsrc;
if(! _imgsrc){
return;
}
$this.addClass('tcinit').before($.epoAPI.template.html(tcAPI.templateEngine.tc_lightbox, {}));
tclightboxwrap=$this.prev();
$this.wrap("<div class='tc-lightbox-image-wrap'/>");
$this.after(tclightboxwrap);
_img_button=tclightboxwrap.find('.tc-lightbox-button');
addButtonEvent=function(){
_img_button.addClass('tcinit').on('click.tclightbox', function(buttonevent){
var size;
var _img;
if($('.tc-closing.tc-lightbox').length > 0){
return;
}
size=$.epoAPI.dom.size();
_img=$('<img>')
.addClass('tc-lightbox-img')
.attr('src', _imgsrc)
.css('maxHeight', size.visibleHeight + 'px')
.css('maxWidth', size.visibleWidth + 'px');
$.tcFloatBox({
fps: 1,
ismodal: false,
refresh: 'fixed',
width: 'auto',
height: 'auto',
top: '0%',
left: '0%',
classname: 'flasho tc-lightbox',
animateIn: 'tc-lightbox-zoomin',
animateOut: 'tc-lightbox-zoomout',
data: $.epoAPI.template.html(tcAPI.templateEngine.tc_lightbox_zoom, { img: _img[ 0 ].outerHTML }),
zIndex: 102001,
cancelClass: '.tc-lightbox-img, .tc-lightbox-button-close',
unique: true
});
buttonevent.preventDefault();
});
};
if(TMEPOJS.tm_epo_preload_lightbox_image==='yes'){
preload_img=new Image();
preload_img.src=_imgsrc;
preload_img.onload=function(){
addButtonEvent();
};}else{
addButtonEvent();
}});
};}
if(! $().tmsectionpoplink){
$.fn.tmsectionpoplink=function(){
var elements=this;
if(elements.length===0){
return;
}
return elements.each(function(){
var $this=$(this);
var id;
var title;
var section;
var clicked;
var _ovl;
var cancelfunc;
if($this.data('tmsectionpoplink')){
return;
}
$this.data('tmsectionpoplink', true);
id=$this.attr('data-sectionid');
title=TMEPOJS.i18n_addition_options;
section=$this.closest(".cpf-section[data-uniqid='" + id + "']");
clicked=false;
_ovl=$('<div class="fl-overlay"></div>').css({
zIndex: parseInt($this.zIndex, 10) - 1,
opacity: 0.8
});
cancelfunc=function(){
var pop=$('#tm-section-pop-up');
pop.parents().removeClass('noanimated');
_ovl.unbind().remove();
pop.after(section);
pop.remove();
section.find('.tm-section-link').show();
section.find('.tm-section-pop').hide();
};
if($this.attr('data-title')){
title=$this.attr('data-title');
}
$this.on('click.tmsectionpoplink', function(e){
var pop;
e.preventDefault();
clicked=false;
_ovl.appendTo('body').on('click', cancelfunc);
section.before($.epoAPI.template.html(tcAPI.templateEngine.tc_section_pop_link, {
title: title,
close: TMEPOJS.i18n_close
})
);
pop=$('#tm-section-pop-up');
pop.find('.float-editbox').prepend(section);
section.find('.tm-section-link').hide();
section.find('.tm-section-pop').show();
pop.parents().addClass('noanimated');
pop.find('.floatbox-cancel').on('click', function(){
if(clicked){
return;
}
clicked=true;
cancelfunc();
});
jWindow.trigger('tmlazy');
jWindow.trigger('tmsectionpoplink');
});
});
};}
function getVariationIdSelector(currentCart){
var variationIdSelector="input[name^='variation_id']";
if(currentCart.find('input.variation_id').length > 0){
variationIdSelector='input.variation_id';
}else{
variationIdSelector='input.product-variation-id';
}
return variationIdSelector;
}
function getVariationIdElement(currentCart, not){
var variationIdSelector=getVariationIdSelector(currentCart);
var variationIdElement=currentCart.find(variationIdSelector);
if(currentCart.is('.tc-epo-element-product-container-cart')){
variationIdElement=currentCart.closest('.tc-epo-element-product-li-container').find(variationIdSelector);
}else{
variationIdElement=currentCart.find(variationIdSelector).not('.tc-epo-element-product-container-variation-id ' + variationIdSelector);
}
if(not){
variationIdElement=variationIdElement.not(not);
}
return variationIdElement;
}
function getCurrentVariation(currentCart){
var field_div;
var newCart;
if(currentCart.is('.tc-epo-element-product-container-cart')){
field_div=currentCart.closest('.cpf-element');
if(field_div.is('.cpf-type-product-thumbnailmultiple')||field_div.is('.cpf-type-product-checkbox')){
newCart=currentCart.closest('.tc-epo-element-product-holder').find('.tc-epo-element-product-container-variation-id');
}else if(field_div.is('.cpf-type-product-thumbnail')||field_div.is('.cpf-type-product-radio')||field_div.is('.cpf-type-product-dropdown')||field_div.is('.cpf-type-product-single')){
newCart=field_div.find('.tc-epo-element-product-container-variation-id');
}
if(newCart&&newCart.length){
currentCart=newCart;
}}
return currentCart.find(getVariationIdSelector(currentCart)).val()||0;
}
function getQtyElement(currentCart){
var qty=currentCart.find(tcAPI.qtySelector).last();
if(qty.length===0){
qty=currentCart.find(tcAPI.associateQtySelector).last();
}
qty=$.epoAPI.applyFilter('tc_getQtyElement', qty, currentCart);
return qty;
}
function getCurrentQty(currentCart){
return $.epoAPI.applyFilter('tc_getCurrentQty', $.epoAPI.math.toFloat(getQtyElement(currentCart).val()), currentCart);
}
function add_variation_event(name, selector, func){
lateVariationEvent[ lateVariationEvent.length ]={
name: name,
selector: selector,
func: func
};}
function field_is_active(field, nochecks, single){
var ret=true;
var insideProductCheck=false;
var productElement;
field=$(field);
productElement=field.filter('.tc-epo-field-product');
if(productElement.length&&productElement.data('islogicinit')===undefined){
insideProductCheck=true;
}
field.each(function(j, element){
if(! ret&&field.has('.tc-epo-field-product').length){
if(insideProductCheck||productElement.is('.tcdisabled')){
field_check_active(element, nochecks, single);
}}else{
ret=field_check_active(element, nochecks, single)&&ret;
}});
return ret;
}
function field_check_active(field, nochecks, single){
var hideElement;
var singleField;
var ul;
var isInsideProductElement;
var productElementActive;
var productElementSectionActive;
var productElementQty;
var section;
var elements;
var disableElements;
var sectionLi;
var allSectionsDisabled;
field=$(field);
if(field.is('.cpf-element')){
hideElement=field;
field=field.find('.tmcp-field, .tmcp-fee-field');
}else{
hideElement=field.closest('.cpf-element');
}
section=hideElement.closest('.cpf-section');
sectionLi=section.closest('.tm-extra-product-options-field');
if(single){
ul=field.closest('.tmcp-ul-wrap');
}else{
ul=hideElement;
}
if(field.is('.tc-epo-field-product')&&field.data('islogicinit')===undefined){
field.data('islogicinit', 1);
}
isInsideProductElement = ! field.is('.tc-epo-field-product')&&hideElement.closest('.cpf-type-product');
if(isInsideProductElement.length){
productElementQty=isInsideProductElement.find(tcAPI.associateQtySelector);
if(productElementQty.length){
if($.epoAPI.math.toFloat(productElementQty.val()) > 0){
field.removeClass('ignore');
productElementQty.removeClass('ignore');
}else{
field.addClass('ignore');
productElementQty.addClass('ignore');
}}
productElementActive=isInsideProductElement.data('isactive');
isInsideProductElement=isInsideProductElement.closest('.cpf-section');
productElementSectionActive=isInsideProductElement.data('isactive');
}
if(productElementActive!==false&&productElementSectionActive!==false&&hideElement.data('isactive')!==false&&section.data('isactive')!==false){
singleField=field.first();
field.prop('disabled', false);
if(field.data('tc-state')!==undefined){
field.data('tc-state', false);
}
if(TMEPOJS.tm_epo_show_only_active_quantities!=='yes'){
if(singleField.is(':radio, .cpf-type-radio')||singleField.is(':checkbox, .cpf-type-checkbox')){
field.filter(':checked').closest('.tmcp-field-wrap').find('.tm-qty').prop('disabled', false);
field.not(':checked').closest('.tmcp-field-wrap').find('.tm-qty').prop('disabled', true);
}else if(singleField.is('select, .cpf-type-select, .cpf-type-selectmultiple')){
if(singleField.val()){
ul.find('.tm-qty').prop('disabled', false);
}else{
ul.find('.tm-qty').prop('disabled', true);
}}else if(singleField.val()){
ul.find('.tm-qty').prop('disabled', false);
}else{
ul.find('.tm-qty').prop('disabled', true);
}}else if(! nochecks){
hideElement.find('.tm-quantity').trigger('showhide.cpfcustom');
}
if(! singleField.is('.cpf-element')){
field.removeClass('tcdisabled').addClass('tcenabled');
if(field.is('.tmcp-upload')){
if(field.next('.tmcp-upload-hidden').length){
field.next('.tmcp-upload-hidden').removeClass('tcdisabled').addClass('tcenabled').prop('disabled', false);
}}
}
hideElement.removeClass('tc-container-disabled').addClass('tc-container-enabled');
field.trigger({
type: 'tm-field-is-active',
field: field,
value: true
});
section.removeClass('section-disabled');
sectionLi.removeClass('tc-hidden');
return true;
}
if(! field.is('.cpf-element')){
field.prop('disabled', true).removeClass('tcenabled').addClass('tcdisabled');
if(field.data('tc-state')!==undefined){
field.data('tc-state', true);
}
hideElement.find('.tm-qty').prop('disabled', true);
if(field.is('.tmcp-upload')){
if(field.next('.tmcp-upload-hidden').length){
field.next('.tmcp-upload-hidden').removeClass('tcenabled').addClass('tcdisabled').prop('disabled', true);
}}
}
hideElement.removeClass('tc-container-enabled').addClass('tc-container-disabled');
field.trigger({
type: 'tm-field-is-active',
field: field,
value: false
});
elements=section.find('.cpf-element').length;
disableElements=section.find('.cpf-element.tc-container-disabled').length;
if(elements===disableElements){
section.addClass('section-disabled');
allSectionsDisabled=sectionLi.children('.cpf-section').filter(function(){
return ! $(this).hasClass('section-disabled');
}).length===0;
if(allSectionsDisabled){
sectionLi.addClass('tc-hidden');
}}
return false;
}
function tm_variation_check_match(element, val2, operator){
var $element=$(element);
var epoId=$element.attr('data-epo_id');
var productId=$element.attr('data-product_id');
var variationsForm=$(".variations_form[data-epo_id='" + epoId + "'][data-product_id='" + productId + "']");
var val1;
var variationIdSelector="input[name^='variation_id']";
var $variationId;
variationsForm=$.epoAPI.applyFilter('tm_variation_check_match_variationsForm', variationsForm, epoId, productId, $element);
if(variationsForm.length===0){
return false;
}
$variationId=variationsForm.find(variationIdSelector);
if($variationId.length===0){
variationIdSelector='input.variation_id';
$variationId=variationsForm.find(variationIdSelector);
if($variationId.length===0){
$variationId=variationsForm.closest('.tc-epo-element-product-li-container').find('.product-variation-id');
}}
if(element!==null&&val2!==null&&element!==undefined&&val2!==undefined&&element!==false&&val2!==false){
if(val2){
val2=parseInt(val2, 10);
}else{
val2=-1;
}}
val1=parseInt($variationId.val(), 10);
if(! Number.isFinite(val1)){
val1=0;
}
if(! Number.isFinite(val2)){
val2=0;
}
switch(operator){
case 'is':
return val1!==''&&val1===val2;
case 'isnot':
return val1!==''&&val1!==val2;
case 'isempty':
return val1===''||val1===0;
case 'isnotempty':
return val1!==''&&val1!==0;
case 'startswith':
return val1.toString().startsWith(val2);
case 'endswith':
return val1.toString().endsWith(val2);
case 'greaterthan':
return parseFloat(val1) > parseFloat(val2);
case 'lessthan':
return parseFloat(val1) < parseFloat(val2);
case 'greaterthanequal':
return parseFloat(val1) >=parseFloat(val2);
case 'lessthanequal':
return parseFloat(val1) <=parseFloat(val2);
}
return false;
}
function tm_check_match(val1, val2, operator){
if(val1!==null&&val2!==null){
val1=encodeURIComponent(val1);
if($.qtranxj_split){
val2=encodeURIComponent($.qtranxj_split(decodeURIComponent(val2))[ TMEPOQTRANSLATEXJS.language ]);
}else{
val2=encodeURIComponent(decodeURIComponent(val2));
}
if(val1){
val1=val1.toLowerCase();
}else{
val1='';
}
if(val2){
val2=val2.toLowerCase();
}else{
val2='';
}}else{
return false;
}
val1=val1.toString();
val2=val2.toString();
switch(operator){
case 'is':
return val1!==null&&val1===val2;
case 'isnot':
return val1!==null&&val1!==val2;
case 'isempty':
return !(val1!=='undefined'&&val1!==undefined&&val1!=='');
case 'isnotempty':
return val1!=='undefined'&&val1!==undefined&&val1!=='';
case 'startswith':
return val1.startsWith(val2);
case 'endswith':
return val1.endsWith(val2);
case 'greaterthan':
return parseFloat(val1) > parseFloat(val2);
case 'lessthan':
return parseFloat(val1) < parseFloat(val2);
case 'greaterthanequal':
return parseFloat(val1) >=parseFloat(val2);
case 'lessthanequal':
return parseFloat(val1) <=parseFloat(val2);
}
return false;
}
function tm_check_section_match(elements, operator){
var all_checked=true;
var val;
var all_elements=elements.find('.cpf-element');
var radio_checked;
var checkbox_checked;
var noSplit=false;
if(elements.is('.tc-hidden')){
if(operator==='isnotempty'){
return false;
}else if(operator==='isempty'){
return true;
}}
$(all_elements).each(function(j, element){
var _class;
var elementToCheck='';
element=$(element);
if(element.is('.cpf-type-product')){
elementToCheck=':not(.tc-extra-product-options-inline .tm-epo-field)';
}
if(field_is_active(element)){
_class=element
.attr('class')
.split(' ')
.map(function(cls){
if(cls.indexOf('cpf-type-', 0)!==-1){
return cls;
}
return null;
})
.filter(function(v){
if(v!==null&&v!==undefined){
return v;
}
return null;
});
if(_class.length > 0){
_class=_class[ 0 ];
if(_class==='cpf-type-product'){
noSplit=true;
if(element.is('.cpf-type-product-mode-product')||element.is('.cpf-type-product-checkbox')||element.is('.cpf-type-product-thumbnailmultiple')){
_class='cpf-type-checkbox';
}else if(element.is('.cpf-type-product-dropdown')){
_class='cpf-type-select';
}else{
_class='cpf-type-radio';
}}
switch(_class){
case 'cpf-type-radio':
radio_checked=element.find('input.tm-epo-field.tmcp-radio:checked' + elementToCheck);
if(operator==='isnotempty'){
all_checked=all_checked&&radio_checked.length > 0;
if(radio_checked.length > 0){
val=radio_checked.length;
}}else if(operator==='isempty'){
all_checked=all_checked&&radio_checked.length===0;
}
break;
case 'cpf-type-checkbox':
checkbox_checked=element.find('input.tm-epo-field.tmcp-checkbox:checked' + elementToCheck);
if(operator==='isnotempty'){
all_checked=all_checked&&checkbox_checked.length > 0;
if(checkbox_checked.length > 0){
val=checkbox_checked.length;
}}else if(operator==='isempty'){
all_checked=all_checked&&checkbox_checked.length===0;
}
break;
case 'cpf-type-select':
val=element.find('select.tm-epo-field.tmcp-select' + elementToCheck).val();
if(val&&! noSplit){
val=val.slice(0, val.lastIndexOf('_'));
}
break;
case 'cpf-type-selectmultiple':
val=element.find('select.tm-epo-field.tmcp-selectmultiple' + elementToCheck).val();
if(val&&! noSplit){
val.forEach(function(option, i){
val[ i ]=option.slice(0, option.lastIndexOf('_'));
});
}
break;
default:
val=element.find('.tm-epo-field' + elementToCheck).val();
break;
}
if(Array.isArray(val)){
all_checked=all_checked&&val.some(function(item){
return tm_check_match(item, '', operator);
});
}else{
all_checked=all_checked&&tm_check_match(val, '', operator);
}}else{
all_checked=all_checked&&false;
}}
});
return all_checked;
}
function tm_check_field_match(f){
var element=$(f.element);
var operator=f.operator;
var value=f.value;
var val;
var radio_checked;
var checkbox_checked;
var ret;
var _class;
var noSplit=false;
var elementToCheck='';
if(! element.length){
return false;
}
if(element.is('.cpf-section')){
return tm_check_section_match(element, operator);
}
if(element.is('.cpf-type-product')){
elementToCheck=':not(.tc-extra-product-options-inline .tm-epo-field)';
}
_class=element
.attr('class')
.split(' ')
.map(function(cls){
if(cls.indexOf('cpf-type-', 0)!==-1){
return cls;
}
return null;
})
.filter(function(v){
if(v!==null&&v!==undefined){
return v;
}
return null;
});
if(_class.length > 0){
_class=_class[ 0 ];
if(_class==='cpf-type-product'){
noSplit=true;
if(element.is('.cpf-type-product-mode-product')||element.is('.cpf-type-product-checkbox')||element.is('.cpf-type-product-thumbnailmultiple')){
_class='cpf-type-checkbox';
}else if(element.is('.cpf-type-product-dropdown')){
_class='cpf-type-select';
}else{
_class='cpf-type-radio';
}}
switch(_class){
case 'cpf-type-radio':
radio_checked=element.find('input.tm-epo-field.tmcp-radio:checked' + elementToCheck);
if(operator==='is'||operator==='isnot'){
if(radio_checked.length===0&&operator==='is'){
return false;
}
if(radio_checked.length===0&&operator==='isnot'){
return true;
}
val=element.find('input.tm-epo-field.tmcp-radio:checked' + elementToCheck).val();
if(val&&! noSplit){
val=val.slice(0, val.lastIndexOf('_'));
}}
if(operator==='isnotempty'){
return radio_checked.length > 0;
}
if(operator==='isempty'){
return radio_checked.length===0;
}
break;
case 'cpf-type-checkbox':
checkbox_checked=element.find('input.tm-epo-field.tmcp-checkbox:checked' + elementToCheck);
if(operator==='is'||operator==='isnot'){
if(checkbox_checked.length===0&&operator==='is'){
return false;
}
if(checkbox_checked.length===0&&operator==='isnot'){
return true;
}
ret=false;
checkbox_checked.each(function(i, el){
val=$(el).val();
if(val&&! noSplit){
val=val.slice(0, val.lastIndexOf('_'));
}
if(tm_check_match(val, value, operator)){
ret=true;
}else if(operator==='isnot'){
ret=false;
return false;
}});
return ret;
}
if(operator==='isnotempty'){
return checkbox_checked.length > 0;
}
if(operator==='isempty'){
return checkbox_checked.length===0;
}
break;
case 'cpf-type-select':
val=element.find('select.tm-epo-field.tmcp-select' + elementToCheck).val();
if(val&&! noSplit){
val=val.slice(0, val.lastIndexOf('_'));
}
break;
case 'cpf-type-selectmultiple':
val=element.find('select.tm-epo-field.tmcp-selectmultiple' + elementToCheck).val();
if(val&&! noSplit){
val.forEach(function(option, i){
val[ i ]=option.slice(0, option.lastIndexOf('_'));
});
}
break;
case 'cpf-type-variations':
return tm_variation_check_match(element, value, operator);
default:
val=element.find('.tm-epo-field' + elementToCheck).val();
break;
}
if(Array.isArray(val)){
return val.some(function(item){
return tm_check_match(item, value, operator);
});
}
return tm_check_match(val, value, operator);
}
return false;
}
function tm_check_rules(o, theevent){
o.each(function(){
var $this=$(this);
var matches=$this.data('matches');
var toggle=$this.data('toggle');
var fields=$this.data('fields');
var checked=[];
var show=false;
switch(toggle){
case 'show':
show=false;
break;
case 'hide':
show=true;
break;
}
$.each(fields, function(i, ifield){
if(Array.isArray(ifield)){
checked[ i ]=0;
$.each(ifield, function(ii, field){
var fia=true;
if(theevent==='cpflogic'){
fia=field_is_active($(field.element));
}
if(fia&&tm_check_field_match(field)){
checked[ i ]=parseInt(checked[ i ], 10) + 1;
}});
}});
$.each(matches, function(im, match){
var checkim=parseInt(checked[ im ], 10);
match=parseInt(match, 10);
if(checkim > 0&&match===checkim){
show = ! show;
return false;
}});
if(show){
if(theevent==='cpflogic'&&! $this.data('did_initial_activation')){
latecpflogicactions.push(function(){
var enabledEpos=$this.find('.tm-epo-field.tcenabled');
enabledEpos.each(function(i, el){
el=$(el);
if(! el.data('initial_activation')&&! $this.closest('.cpf-section').is('.tc-hidden')&&field_is_active(el)){
el.trigger('tc_element_epo_rules');
el.data('initial_activation', 1);
}});
if(( $this.is('.cpf-element')&&enabledEpos.length)||$this.is('.cpf-section')){
$this.data('did_initial_activation', 1);
}});
}
$this.removeClass('tc-hidden');
}else{
$this.addClass('tc-hidden');
}
$this.data('isactive', show);
$this.trigger('tc-logic');
});
}
function run_cpfdependson(obj){
var iscpfdependson;
var last_activate_field=[];
if(! $(obj).length){
obj='body';
}
obj=$(obj);
iscpfdependson=obj.find('.iscpfdependson');
iscpfdependson.each(function(i, elements){
$(elements).each(function(j, el){
tm_check_rules($(el));
});
});
iscpfdependson.each(function(i, elements){
$(elements).each(function(j, el){
tm_check_rules($(el), 'cpflogic');
});
});
iscpfdependson.each(function(i, elements){
$(elements).each(function(j, o){
o=$(o);
if(o.is('.cpf-section')){
o=o.find('.cpf-element');
}
o.each(function(theindex, theelement){
field_is_active($(theelement).find('.tm-epo-field'));
});
});
});
latecpflogicactions.forEach(function(func){
func();
});
latecpflogicactions=[];
if($().selectric){
$('.tm-extra-product-options select').selectric('refresh');
}
setTimeout(function(){
$('.tm-owl-slider').each(function(){
$(this).trigger('refresh.owl.carousel');
});
}, 200);
obj.find('.tm-product-image:checked,select.tm-product-image').each(function(){
var t=$(this);
if(field_is_active(t)&&t.val()!==''){
last_activate_field.push(t);
}});
if(last_activate_field.length){
last_activate_field[ last_activate_field.length - 1 ].trigger('tm_trigger_product_image');
}
jWindow.trigger('cpflogicrun');
jWindow.trigger('tmlazy');
jWindow.trigger('cpflogicdone');
}
if(! $().cpfdependson){
$.fn.cpfdependson=function(fields, toggle, refresh){
var elements=this;
var matches=[];
if(elements.length===0||typeof fields!=='object'){
return;
}
if(! toggle){
toggle='show';
}
$.each(fields, function(i, ifield){
var get_element;
var $this_epo_container;
matches[ i ]=0;
if(Array.isArray(ifield)){
$.each(ifield, function(ii, field){
if(typeof field!=='object'){
return true;
}
get_element=get_element_from_field(field.element);
if(get_element&&get_element.length > 0){
get_element.each(function(iii, element){
var $element=$(element);
var $pid1;
var $epo_id1;
var _events='change.cpflogic';
if(! $this_epo_container||$this_epo_container.closest('.tc-extra-product-options-inline').length){
$pid1='.tm-product-id-' + $element.closest('.tc-extra-product-options').attr('data-product-id');
$epo_id1="[data-epo-id='" + $element.closest('.tc-extra-product-options').attr('data-epo-id') + "']";
$this_epo_container=$('.tc-extra-product-options' + $pid1 + $epo_id1);
}
if(element&&$element.length > 0&&(! $element.data('tmhaslogicevents')||refresh)){
if($element.is('.tm-epo-variation-element')){
add_variation_event('found_variation.tmlogic', false, function(){
run_cpfdependson($this_epo_container);
jWindow.trigger('tm-do-epo-update');
});
add_variation_event('hide_variation.tmlogic', false, function(){
run_cpfdependson($this_epo_container);
jWindow.trigger('tm-do-epo-update');
});
}else{
if($element.is(':text')||$element.is('textarea')){
_events='change.cpflogic input.cpflogic';
}
$element.off(_events).on(_events, function(){
run_cpfdependson($this_epo_container);
});
}
$element.data('tmhaslogicevents', 1);
}});
matches[ i ]=parseInt(matches[ i ], 10) + 1;
}});
}});
elements.each(function(){
var $this=$(this);
var show=false;
$this.data('matches', matches).data('toggle', toggle).data('fields', fields);
switch(toggle){
case 'show':
show=false;
break;
case 'hide':
show=true;
break;
}
if(show){
$this.removeClass('tc-hidden');
}else{
$this.addClass('tc-hidden');
}
$this.data('isactive', show);
});
elements.addClass('iscpfdependson is-epo-depend').data('iscpfdependson', 1);
return elements;
};
$.fn.run_cpfdependson=function(){
run_cpfdependson();
};}
$.tcepo={
formSubmitEvents: {},
oneOptionIsSelected: {},
initialActivation: {},
lateFieldsPrices: {},
errorObject: {},
showHideTotal: {}};
function validate_logic(l){
return typeof l==='object'&&'toggle' in l&&'rules' in l&&l.rules.length > 0;
}
function convert_rules(rules){
if(rules.what){
if(rules.what==='all'){
rules.rules=[ rules.rules ];
}else if(rules.what==='any'){
rules.rules=rules.rules.reduce(function(accumulator, elrule){
accumulator.push([ elrule ]);
return accumulator;
}, []);
}
delete rules.what;
}
return rules;
}
function cpf_section_logic(obj){
var root_element=$(obj);
var all_sections=root_element.find('.cpf-section');
var search_obj;
var cpf_section;
var sect;
var logic;
var haslogic;
var fields;
var section;
var element;
var operator;
var value;
var obj_section;
var obj_element;
var closestProductElement;
if(root_element.is('.cpf-section')){
search_obj=false;
}else{
search_obj=all_sections;
}
root_element.each(function(j, obj_el){
if($(obj_el).is('.cpf-section')){
cpf_section=$(obj_el);
}else{
cpf_section=$(obj_el).find('.cpf-section');
}
cpf_section.filter('[data-haslogic="1"]').each(function(index, el){
sect=$(el);
logic=sect.data('logic');
logic=convert_rules(logic);
haslogic=parseInt(sect.data('haslogic'), 10);
fields=[];
closestProductElement=sect.parent().closest('.cpf-type-product');
if(haslogic===1&&validate_logic(logic)){
$.each(logic.rules, function(i, irule){
if(irule){
if(Array.isArray(irule)){
fields[ i ]=[];
$.each(irule, function(ii, rule){
section=rule.section;
element=rule.element;
operator=rule.operator;
value=rule.value;
if(search_obj){
if(closestProductElement.length){
obj_section=closestProductElement.find('.cpf-section').filter("[data-uniqid='" + section + "']");
if(element!==section){
obj_element=obj_section.find('.cpf-element').eq(element);
}else{
obj_element=obj_section;
}}else{
obj_section=search_obj.filter("[data-uniqid='" + section + "']");
if(element!==section){
obj_element=obj_section.find('.cpf-element:not(.cpf-element .cpf-element)').eq(element);
}else{
obj_element=obj_section;
}}
}else if(element!==section){
obj_element=root_element.find('.cpf-element').eq(element);
}else{
obj_element=obj_section;
}
fields[ i ].push({
element: obj_element,
operator: operator,
value: value
});
});
}}
});
if(! sect.data('iscpfdependson')){
sect.data('cpfdependson-fields', fields);
sect.cpfdependson(fields, logic.toggle);
}else{
sect.cpfdependson(sect.data('cpfdependson-fields'), logic.toggle, true);
}}
});
});
}
function cpf_element_logic(obj){
var root_element=$(obj);
var all_sections=root_element.find('.cpf-section').not('.cpf-type-product .cpf-section');
var search_obj;
var current_element;
var logic;
var haslogic;
var section;
var element;
var operator;
var value;
var obj_section;
var obj_element;
var closestProductElement;
if(root_element.is('.cpf-section')){
search_obj=false;
}else{
search_obj=all_sections;
}
root_element.find('.cpf-element[data-haslogic="1"]').each(function(index, el){
var fields=[];
current_element=$(el);
logic=current_element.data('logic');
logic=convert_rules(logic);
haslogic=parseInt(current_element.data('haslogic'), 10);
closestProductElement=current_element.parent().closest('.cpf-type-product');
if(haslogic===1&&validate_logic(logic)){
$.each(logic.rules, function(i, irule){
if(irule){
if(Array.isArray(irule)){
fields[ i ]=[];
$.each(irule, function(ii, rule){
section=rule.section;
element=rule.element;
operator=rule.operator;
value=rule.value;
if(search_obj){
if(closestProductElement.length){
obj_section=closestProductElement.find('.cpf-section').filter("[data-uniqid='" + section + "']");
if(element!==section){
obj_element=obj_section.find('.cpf-element').eq(element);
}else{
obj_element=obj_section;
}}else{
obj_section=search_obj.filter("[data-uniqid='" + section + "']");
if(element!==section){
obj_element=obj_section.find('.cpf-element:not(.cpf-element .cpf-element)').eq(element);
}else{
obj_element=obj_section;
}}
}else if(element!==section){
obj_element=root_element.find('.cpf-element').eq(element);
}else{
obj_element=obj_section;
}
fields[ i ].push({
element: obj_element,
operator: operator,
value: value
});
});
}}
});
if(! current_element.data('iscpfdependson')){
current_element.data('cpfdependson-fields', fields);
current_element.cpfdependson(fields, logic.toggle);
}else{
current_element.cpfdependson(current_element.data('cpfdependson-fields'), logic.toggle, true);
}}
});
}
function tm_set_price_without_tax(value, _cart, force){
var taxable;
var tax_rate;
var tax_display_mode;
var prices_include_tax;
if(_cart){
taxable=_cart.attr('data-taxable');
tax_rate=_cart.attr('data-tax-rate');
tax_display_mode=_cart.attr('data-tax-display-mode');
prices_include_tax=_cart.attr('data-prices-include-tax');
if(force||(taxable&&tax_display_mode==='incl'&&prices_include_tax!=='1')){
value=parseFloat(value) /(1 +(tax_rate / 100));
}}
return value;
}
function tm_set_price_with_tax(value, _cart, force){
var taxable;
var tax_rate;
var tax_display_mode;
var prices_include_tax;
if(_cart){
taxable=_cart.attr('data-taxable');
tax_rate=_cart.attr('data-tax-rate');
tax_display_mode=_cart.attr('data-tax-display-mode');
prices_include_tax=_cart.attr('data-prices-include-tax');
if(force||(taxable&&tax_display_mode!=='incl'&&prices_include_tax==='1')){
value=parseFloat(value) *(1 +(tax_rate / 100));
}}
return value;
}
function tm_set_backend_price(value, _cart, variation){
var taxable;
var tax_display_mode;
var prices_include_tax;
if(_cart){
taxable=_cart.attr('data-taxable');
tax_display_mode=_cart.attr('data-tax-display-mode');
prices_include_tax=_cart.attr('data-prices-include-tax');
if(taxable){
if(variation&&variation.tc_tax_rate&&String(variation.tc_tax_rate)==='0'){
return value;
}
if(prices_include_tax==='1'){
if(tax_display_mode==='incl'){
if(variation.tc_base_taxes_of_one!==variation.tc_modded_taxes_of_one){
value=parseFloat(((1 - variation.tc_taxes_of_one) * value) *(1 /(1 - variation.tc_base_taxes_of_one)));
}}else{
value=tm_set_price_with_tax(value, _cart);
}}else if(prices_include_tax!=='1'&&tax_display_mode==='incl'){
value=tm_set_price_without_tax(value, _cart);
}}
}
return value;
}
function tm_set_price_totals(value, _cart, notax, taxstring, element){
var inc_tax_string='';
var sign='';
var val;
if(! notax){
value=tm_set_tax_price(value, _cart, element, undefined, true);
}
val=Math.abs(value);
if(_cart&&taxstring){
inc_tax_string=_cart.attr('data-tax-string');
}
if(inc_tax_string===undefined){
inc_tax_string='';
}
if(value < 0){
sign=TMEPOJS.minus_sign + ' ';
}
return tm_set_price_(val, sign, inc_tax_string);
}
function replace_suffixes(value, rawValue, tc_totals_ob, totalsHolder){
if(totalsHolder.attr('data-tax-display-mode')==='excl'){
tc_totals_ob[ value ]=tc_totals_ob[ value ].replace(/{price_excluding_tax}/g, tm_set_price_totals(tc_totals_ob[ rawValue ], totalsHolder, true, false));
tc_totals_ob[ value ]=tc_totals_ob[ value ].replace(/{price_including_tax}/g, tm_set_price_totals(tm_set_price_with_tax(tc_totals_ob[ rawValue ], totalsHolder, true), totalsHolder, true, false));
}else{
tc_totals_ob[ value ]=tc_totals_ob[ value ].replace(/{price_including_tax}/g, tm_set_price_totals(tc_totals_ob[ rawValue ], totalsHolder, true, false));
tc_totals_ob[ value ]=tc_totals_ob[ value ].replace(/{price_excluding_tax}/g, tm_set_price_totals(tm_set_price_without_tax(tc_totals_ob[ rawValue ], totalsHolder, true), totalsHolder, true, false));
}
return tc_totals_ob;
}
function tm_force_update_price(obj, price, formated_price, original_price, original_formated_price){
tm_update_price(obj, price, formated_price, original_price, original_formated_price, true);
}
function tm_update_price(obj, price, formated_price, original_price, original_formated_price, force){
var $obj=$(obj);
var w;
var $ba_amount;
var priceobj;
var f;
var pw;
if($obj.length===0){
return;
}
w=$obj.closest('.tmcp-field-wrap');
pw=$obj.closest('.tc-price-wrap');
f=w.find('.tm-epo-field');
if(! force&&f.attr('data-no-price-change')==='1'&&f.data('price-changed')){
return;
}
price=$.epoAPI.applyFilter('tc_adjust_update_price_price', price);
formated_price=$.epoAPI.applyFilter('tc_adjust_update_price_formated_price', formated_price, price);
original_price=$.epoAPI.applyFilter('tc_adjust_update_price_original_price', original_price);
original_formated_price=$.epoAPI.applyFilter('tc_adjust_update_price_original_formated_price', original_formated_price, original_price);
if(! Number.isFinite(parseFloat(original_price))){
original_price=0;
}
if(! Number.isFinite(parseFloat(price))){
price=0;
}
$ba_amount=w.find('.before-amount,.after-amount');
priceobj={
price: formated_price,
original_price: original_formated_price
};
if(( TMEPOJS.tm_epo_auto_hide_price_if_zero==='yes'&&$.tmempty(price)===false)||TMEPOJS.tm_epo_auto_hide_price_if_zero!=='yes'){
if(( $.tmempty(price)===true&&f.attr('data-no-price')==='1')||(! force&&f.length > 0&&(f.attr('data-no-price')==='1'||(f.attr('data-type')==='variable'&&! f.data('price'))))){
pw.addClass('tm-hidden');
$obj.addClass('tm-hidden');
$obj.empty();
$ba_amount.addClass('tm-hidden');
}else{
if(original_price&&original_price!==undefined&&parseFloat(original_price)!==parseFloat(price)){
$obj.html($.epoAPI.template.html(tcAPI.templateEngine.sale_price, { price: priceobj }));
}else{
$obj.html($.epoAPI.template.html(tcAPI.templateEngine.price, { price: priceobj }));
}
pw.removeClass('tm-hidden');
$obj.removeClass('tm-hidden');
$ba_amount.removeClass('tm-hidden');
}}else{
pw.addClass('tm-hidden');
$obj.addClass('tm-hidden');
$obj.empty();
$ba_amount.addClass('tm-hidden');
}}
function get_variation_current_settings(form, epoObject){
var current_settings={};
if(epoObject.thisForm){
form=epoObject.thisForm;
}
form.find('.variations select, .tc-epo-variable-product-selector').each(function(){
var attribute_name;
var value;
if(typeof $(this).data('attribute_name')!=='undefined'){
attribute_name=$(this).data('attribute_name');
}else{
attribute_name=$(this).attr('name');
}
value=$(this).val();
current_settings[ attribute_name ]=value;
});
return current_settings;
}
function do_tm_custom_variations_update(form, all_variations, epoObject){
var check_if_all_are_not_set=[];
var formSettings=get_variation_current_settings(form, epoObject);
var redo_check=true;
var variationId=form.find(getVariationIdSelector(form)).val();
variationId=(variationId!=='0'&&variationId!=='')||form.find('.cpf-type-variations').find('.tm-epo-variation-element:checked').length > 0||form.find('.cpf-type-variations').find('.tm-epo-variation-element option[value!=""]:selected');
if(! variationId){
return;
}
form.find('.cpf-type-variations').each(function(i, el){
var t=$(el).find('.tm-epo-variation-element');
var id;
var v;
var exists=false;
check_if_all_are_not_set[ i ]=true;
if(t.is('select')){
id=$.epoAPI.dom.id(t.attr('data-tm-for-variation'));
v=t.val();
if(v){
check_if_all_are_not_set[ i ]=false;
}
t.children('option').each(function(x, o){
exists=false;
form.find("[data-attribute_name='attribute_" + id + "']")
.children('option')
.each(function(){
if($(this).attr('value')===$(o).attr('value')){
exists=true;
return false;
}});
if(! exists){
$(o).prop('disabled', true).hide();
}else{
$(o).prop('disabled', false).show();
}});
}else{
t.each(function(x, oe){
var o=$(oe);
var li=o.closest('li');
var input=li.find('.tm-epo-variation-element');
var this_settings=$.extend(true, {}, formSettings);
var matching_variations;
var variation;
var is_in_stock;
id=o.attr('data-tm-for-variation');
v=o.val();
if(o.is(':checked')){
check_if_all_are_not_set[ i ]=false;
}
this_settings[ 'attribute_' + id ]=v;
matching_variations=$.fn.tm_find_matching_variations(all_variations, this_settings);
variation=matching_variations.shift();
is_in_stock=variation&&'is_in_stock' in variation&&variation.is_in_stock;
if(! is_in_stock){
if(! input.is(':checked')&&! is_in_stock){
li.addClass('pointereventsoff');
}else{
li.removeClass('pointereventsoff');
}
o.attr('disabled', 'disabled').addClass('tm-disabled');
input.attr('disabled', 'disabled');
input.attr('data-tm-disabled', 'disabled');
li.addClass('tm-attribute-disabled').fadeTo('fast', 0.5);
}else{
o.prop('disabled', false).removeClass('tm-disabled');
li.removeClass('pointereventsoff tm-attribute-disabled').fadeTo('fast', 1, function(){
$(this).css('opacity', '');
});
input.prop('disabled', false);
input.removeAttr('data-tm-disabled');
}});
}});
if(check_if_all_are_not_set){
check_if_all_are_not_set.shift();
$.each(check_if_all_are_not_set, function(i, el){
if(el===false){
redo_check=false;
return false;
}});
if(redo_check){
form.find('.cpf-type-variations')
.first()
.each(function(i, el){
var t;
var li;
var input;
t=$(el).find('.tm-epo-variation-element');
if(! t.is('select')){
t.each(function(x, o){
o=$(o);
li=o.closest('li');
input=li.find('.tm-epo-variation-element');
o.prop('disabled', false).removeClass('tm-disabled');
li.removeClass('tm-attribute-disabled').stop().css('opacity', '');
input.prop('disabled', false);
input.removeAttr('data-tm-disabled');
});
}});
}}
}
function tm_custom_variations_update(form, epoObject){
var data;
var all_variations=form.data('product_variations');
var product_id=parseInt(form.data('product_id'), 10);
var globalVariationObject=form.data('globalVariationObject')||false;
if(! product_id){
product_id=form.data('tc_product_id');
}
if(! product_id&&form.is(tcAPI.compositeSelector)){
data=form.find('.component_options').data('options_data');
product_id=data[ 0 ].option_id;
if(! all_variations){
all_variations=form.find('.details.component_data').data('product_variations');
}}
if(! epoObject.is_associated){
if(! all_variations&&window.product_variations&&window.product_variations.product_id){
all_variations=window.product_variations.product_id;
}
if(! all_variations&&window.product_variations){
all_variations=window.product_variations;
}
if(! all_variations&&window[ 'product_variations_' + product_id ]){
all_variations=window[ 'product_variations_' + product_id ];
}}
if(! all_variations){
if(! globalVariationObject){
data={
action: 'woocommerce_tm_get_variations_array',
post_id: product_id
};
$.post(TMEPOJS.ajax_url,
data,
function(response){
globalVariationObject=response;
form.data('globalVariationObject', response);
do_tm_custom_variations_update(form, globalVariationObject.variations, epoObject);
},
'json'
);
}else{
do_tm_custom_variations_update(form, globalVariationObject.variations, epoObject);
}
return;
}
do_tm_custom_variations_update(form, all_variations, epoObject);
}
function tm_fix_stock(cart, html){
var custom_variations;
var section;
if(html===undefined){
return false;
}
cart=$(cart);
custom_variations=cart.find('.tm-epo-variation-element').first();
section=custom_variations.closest('.tm-epo-variation-section');
if(custom_variations.length){
section.find('.tm-stock').remove();
section.append('<div class="tm-stock">' + html + '</div>');
return true;
}
cart.find('.tm-stock').remove();
cart.find('.variations').after('<div class="tm-stock">' + html + '</div>');
return true;
}
function fix_stock($this, form){
var stock;
if(TMEPOJS.tm_epo_global_move_out_of_stock==='no'){
return;
}
stock=$this.find('.woocommerce-variation-availability').last();
if(! stock.length){
stock=$this.find('.stock').last();
}
if(stock.length){
form.find('.tm-stock').remove();
if(tm_fix_stock(form, stock.prop('outerHTML'))){
stock.remove();
}}else{
form.find('.tm-stock').remove();
}}
function get_main_input_id(main_product, product, id){
var selector='';
var inputid;
if(id){
selector=selector + "[value='" + id + "']";
}
if(! product){
product=main_product;
}
inputid=product.find(tcAPI.addToCartSelector + selector);
if(inputid.length===0){
inputid=product.find(tcAPI.tcAddToCartSelector + selector);
}
return inputid.last();
}
function get_main_form(main_product, product, selector, id){
if(! selector){
selector='form';
}
return get_main_input_id(main_product, product, id).closest(selector);
}
function get_main_cart(main_product, product, selector, id){
return get_main_form(main_product, product, selector, id);
}
function tm_get_native_prices_block(obj){
var selector=$.epoAPI.applyFilter('tcGetNativePricesBlockSelector', '.single_variation .price', obj);
return $(obj).find(selector).not('.tc-price');
}
function tm_set_url_fields(){
jDocument.on('click.cpfurl change.cpfurl tmredirect', '.tc-url-container .tmcp-radio, .tc-url-container .tmcp-radio+label', function(e){
var data_url=$(this).attr('data-url');
if(data_url){
if(window.location!==data_url){
e.preventDefault();
window.location=data_url;
}}
});
jDocument.on('change.cpfurl tmredirect', '.tc-url-container .tmcp-select', function(e){
var data_url=$(this).children('option:selected').attr('data-url');
if(data_url){
if(window.location!==data_url){
e.preventDefault();
window.location=data_url;
}}
});
}
function tm_floating_totals(this_epo_totals_container, is_quickview, main_cart){
$.tcFloatingTotalsBox(this_epo_totals_container, is_quickview, main_cart);
}
function tm_show_hide_add_to_cart_button(main_product, currentEpoObject){
var button;
var qty;
var showHideCart=currentEpoObject.showHideCart;
if(showHideCart!==undefined){
if(TMEPOJS.tm_epo_hide_add_cart_button==='yes'||TMEPOJS.tm_epo_hide_all_add_cart_button==='yes'||TMEPOJS.tm_epo_hide_required_add_cart_button==='yes'){
button=main_product.find(tcAPI.addToCartButtonSelector).first();
qty=main_product.find(tcAPI.qtySelector).first();
if(showHideCart){
button.removeClass('tc-hide-add-to-cart-button');
qty.removeClass('tc-hide-add-to-cart-button');
}else{
button.addClass('tc-hide-add-to-cart-button');
qty.addClass('tc-hide-add-to-cart-button');
}
jWindow.trigger('epoShowHideCart', {
main_product: main_product,
currentEpoObject: currentEpoObject,
showHideCart: showHideCart,
button: button,
qty: qty
});
}}
}
function addShowHidetoEpoObject(currentEpoObject, epoEventId, epoObject){
var has_epo;
var this_epo_container;
var epos;
var allElementsAreSelected;
var showHideCart=true;
var showHideTotal=true;
var one_option_is_selected=$.tcepo.oneOptionIsSelected[ epoEventId ];
if(typeof epoObject==='object'){
has_epo=epoObject.has_epo;
this_epo_container=epoObject.this_epo_container;
has_epo=has_epo&&(this_epo_container.find('.tmcp-fee-field').length||this_epo_container.find('.tmcp-field').not('.cpf-type-variations .tmcp-field').length);
}else{
has_epo=epoObject;
}
currentEpoObject.showHideCart=undefined;
currentEpoObject.showHideTotal=undefined;
if(has_epo&&(TMEPOJS.tm_epo_hide_add_cart_button==='yes'||TMEPOJS.tm_epo_hide_all_add_cart_button==='yes'||TMEPOJS.tm_epo_hide_required_add_cart_button==='yes'||TMEPOJS.tm_epo_hide_totals_until_any==='yes'||TMEPOJS.tm_epo_hide_totals_until_all_required==='yes'||TMEPOJS.tm_epo_hide_totals_until_all==='yes')){
if(TMEPOJS.tm_epo_hide_add_cart_button==='yes'){
showHideCart=one_option_is_selected;
}
if(TMEPOJS.tm_epo_hide_totals_until_any==='yes'){
showHideTotal=one_option_is_selected;
}
if(TMEPOJS.tm_epo_hide_required_add_cart_button==='yes'||TMEPOJS.tm_epo_hide_totals_until_all_required==='yes'){
epos=currentEpoObject.this_epo_container.find('.cpf-element').not('.cpf-type-variations').filter('.tc-container-enabled.tc-is-required');
allElementsAreSelected=epos.toArray().every(function(element){
var elementToCheck='';
var _class;
var noSplit=false;
var radio_checked;
var checkbox_checked;
var val;
element=$(element);
if(element.is('.cpf-type-product')){
elementToCheck=':not(.tc-extra-product-options-inline .tm-epo-field)';
}
_class=element
.attr('class')
.split(' ')
.map(function(cls){
if(cls.indexOf('cpf-type-', 0)!==-1){
return cls;
}
return null;
})
.filter(function(v){
if(v!==null&&v!==undefined){
return v;
}
return null;
});
if(_class.length > 0){
_class=_class[ 0 ];
if(_class==='cpf-type-product'){
noSplit=true;
if(element.is('.cpf-type-product-mode-product')||element.is('.cpf-type-product-checkbox')||element.is('.cpf-type-product-thumbnailmultiple')){
_class='cpf-type-checkbox';
}else if(element.is('.cpf-type-product-dropdown')){
_class='cpf-type-select';
}else{
_class='cpf-type-radio';
}}
switch(_class){
case 'cpf-type-radio':
radio_checked=element.find('input.tm-epo-field.tmcp-radio:checked' + elementToCheck);
return radio_checked.length > 0;
case 'cpf-type-checkbox':
checkbox_checked=element.find('input.tm-epo-field.tmcp-checkbox:checked' + elementToCheck);
return checkbox_checked.length > 0;
case 'cpf-type-select':
val=element.find('select.tm-epo-field.tmcp-select' + elementToCheck).val();
if(val&&! noSplit){
val=val.slice(0, val.lastIndexOf('_'));
}
break;
case 'cpf-type-selectmultiple':
val=element.find('select.tm-epo-field.tmcp-selectmultiple' + elementToCheck).val();
if(val&&! noSplit){
val.forEach(function(option, i){
val[ i ]=option.slice(0, option.lastIndexOf('_'));
});
}
break;
default:
val=element.find('.tm-epo-field' + elementToCheck).val();
break;
}
if(Array.isArray(val)){
return val.some(function(item){
return item!=='';
});
}
return val!=='';
}
return false;
});
if(TMEPOJS.tm_epo_hide_required_add_cart_button==='yes'){
showHideCart=allElementsAreSelected;
}
if(TMEPOJS.tm_epo_hide_totals_until_all_required==='yes'){
showHideTotal=allElementsAreSelected;
}}
if(TMEPOJS.tm_epo_hide_all_add_cart_button==='yes'||TMEPOJS.tm_epo_hide_totals_until_all==='yes'){
epos=currentEpoObject.this_epo_container.find('.cpf-element').not('.cpf-type-variations').filter('.tc-container-enabled');
allElementsAreSelected=epos.toArray().every(function(element){
var elementToCheck='';
var _class;
var noSplit=false;
var radio_checked;
var checkbox_checked;
var val;
element=$(element);
if(element.is('.cpf-type-product')){
elementToCheck=':not(.tc-extra-product-options-inline .tm-epo-field)';
}
_class=element
.attr('class')
.split(' ')
.map(function(cls){
if(cls.indexOf('cpf-type-', 0)!==-1){
return cls;
}
return null;
})
.filter(function(v){
if(v!==null&&v!==undefined){
return v;
}
return null;
});
if(_class.length > 0){
_class=_class[ 0 ];
if(_class==='cpf-type-product'){
noSplit=true;
if(element.is('.cpf-type-product-mode-product')||element.is('.cpf-type-product-checkbox')||element.is('.cpf-type-product-thumbnailmultiple')){
_class='cpf-type-checkbox';
}else if(element.is('.cpf-type-product-dropdown')){
_class='cpf-type-select';
}else{
_class='cpf-type-radio';
}}
switch(_class){
case 'cpf-type-radio':
radio_checked=element.find('input.tm-epo-field.tmcp-radio:checked' + elementToCheck);
return radio_checked.length > 0;
case 'cpf-type-checkbox':
checkbox_checked=element.find('input.tm-epo-field.tmcp-checkbox:checked' + elementToCheck);
return checkbox_checked.length > 0;
case 'cpf-type-select':
val=element.find('select.tm-epo-field.tmcp-select' + elementToCheck).val();
if(val&&! noSplit){
val=val.slice(0, val.lastIndexOf('_'));
}
break;
case 'cpf-type-selectmultiple':
val=element.find('select.tm-epo-field.tmcp-selectmultiple' + elementToCheck).val();
if(val&&! noSplit){
val.forEach(function(option, i){
val[ i ]=option.slice(0, option.lastIndexOf('_'));
});
}
break;
default:
val=element.find('.tm-epo-field' + elementToCheck).val();
break;
}
if(Array.isArray(val)){
return val.some(function(item){
return item!=='';
});
}
return val!=='';
}
return false;
});
if(TMEPOJS.tm_epo_hide_all_add_cart_button==='yes'){
showHideCart=allElementsAreSelected;
}
if(TMEPOJS.tm_epo_hide_totals_until_all==='yes'){
showHideTotal=allElementsAreSelected;
}}
currentEpoObject.showHideCart=showHideCart;
currentEpoObject.showHideTotal=showHideTotal;
$.tcepo.showHideTotal[ epoEventId ]=showHideTotal;
}
return currentEpoObject;
}
function goto_error_item(item, epoEventId){
var el=$.tcepo.errorObject[ epoEventId ]||item;
var elsection;
var elsectionlink;
var cpfElement;
var pos;
if(el){
if(TMEPOJS.tm_epo_disable_error_scroll!=='yes'){
elsection=el.closest('.cpf-section');
elsectionlink=elsection.find('.tm-section-link');
cpfElement=el.closest('.cpf-element');
if(elsection.find('.tm-toggle').length){
elsection.find('.tm-toggle').trigger('openwrap.tmtoggle');
}
if(window.tc_validation_offset===undefined){
window.tc_validation_offset=-100;
}
if(elsection.is('.section_popup')){
errorContainer.tcScrollTo(elsectionlink, 300, window.tc_validation_offset);
elsectionlink.trigger('click.tmsectionpoplink');
}else if(elsection.is('.tm-owl-slider-section')){
pos=el.closest('.owl-item').index();
elsection.find('.tcowl-carousel').trigger('to.owl.carousel', [ pos, 100 ]);
setTimeout(function(){
elsection.find('.tcowl-carousel').trigger('refresh.owl.carousel');
if(cpfElement.length > 0){
errorContainer.tcScrollTo(cpfElement, 300, window.tc_validation_offset);
}}, 200);
}else if(cpfElement.length > 0){
errorContainer.tcScrollTo(cpfElement, 300, window.tc_validation_offset);
}}
if(! item){
$.tcepo.errorObject[ epoEventId ]=false;
}}
}
function tm_limit_c_selection(field, prevent){
var allowed=parseInt(field.attr('data-limit'), 10);
var checked=false;
var val;
var t;
var q;
if(allowed > 0){
checked=0;
field
.closest('.tm-extra-product-options-checkbox')
.find("input.tm-epo-field[type='checkbox']:checked")
.each(function(){
t=$(this);
q=t.closest('li.tmcp-field-wrap').find('input.tm-qty');
if(q.length > 0){
val=parseInt(q.val(), 10);
if(val <=0){
val=1;
}
checked=parseInt(checked, 10) + val;
}else{
checked=parseInt(checked, 10) + 1;
}});
if(checked > allowed){
if(prevent){
field.prop('checked', '').trigger('change');
}
return false;
}}
return true;
}
function tm_exact_c_selection(field, prevent){
var allowed=parseInt(field.attr('data-exactlimit'), 10);
var checked=false;
var val;
var t;
var q;
if(allowed > 0){
checked=0;
field
.closest('.tm-extra-product-options-checkbox')
.find("input.tm-epo-field[type='checkbox']:checked")
.each(function(){
t=$(this);
q=t.closest('li.tmcp-field-wrap').find('input.tm-qty');
if(q.length > 0){
val=parseInt(q.val(), 10);
if(val <=0){
val=1;
}
checked=parseInt(checked, 10) + val;
}else{
checked=parseInt(checked, 10) + 1;
}});
if(checked > allowed){
if(prevent){
field.prop('checked', '').trigger('change');
}
return false;
}}
return true;
}
function tm_limit_cont(fields, main_product, epoEventId){
var checkall=true;
var first_error_obj=false;
var limit;
var eln;
var checked;
var t;
var val;
var q;
var ew;
var em;
var message;
var field;
fields.each(function(){
field=$(this);
limit=field.find("[type='checkbox'][data-limit]");
if(limit.length&&field_is_active(limit)){
eln=parseInt(limit.attr('data-limit'), 10);
checked=0;
field.find("input.tm-epo-field[type='checkbox']:checked").each(function(){
t=$(this);
q=t.closest('li.tmcp-field-wrap').find('input.tm-qty');
if(q.length > 0){
val=parseInt(q.val(), 10);
if(val <=0){
val=1;
}
checked=parseInt(checked, 10) + val;
}else{
checked=parseInt(checked, 10) + 1;
}});
ew=field.closest('.cpf-element');
em=ew.find('div.tm-error-min');
if(eln < checked){
checkall=false;
first_error_obj=field;
if(eln===1){
message=TMEPOJS.tm_epo_global_validator_messages.epolimitsingle.replace('{0}', eln);
}else{
message=TMEPOJS.tm_epo_global_validator_messages.epolimit.replace('{0}', eln);
}
if(em.length){
em.remove();
}
if(TMEPOJS.tm_epo_global_error_label_placement==='before'){
field.closest('.tc-element-container').before('<div class="tm-error-min tm-error tc-cell tcwidth tcwidth-100">' + message + '</div>');
}else{
field.closest('.tc-element-container').after('<div class="tm-error-min tm-error tc-cell tcwidth tcwidth-100">' + message + '</div>');
}
main_product.find(tcAPI.addToCartButtonSelector).first().removeClass('disabled loading fpd-disabled').prop('disabled', false);
}else{
em.remove();
}}
});
if(first_error_obj){
$.tcepo.errorObject[ epoEventId ]=first_error_obj;
}
return checkall;
}
function tm_check_limit_cont(limit_cont, main_product, epoEventId){
$.tcepo.formSubmitEvents[ epoEventId ][ $.tcepo.formSubmitEvents[ epoEventId ].length ]={
trigger: function(){
return tm_limit_cont(limit_cont, main_product, epoEventId);
},
on_true: function(){
return true;
},
on_false: function(){
goto_error_item($(limit_cont).find('.tm-epo-field').first(), epoEventId);
return true;
}};}
function tm_exactlimit_cont(fields, main_product, epoEventId){
var checkall=true;
var first_error_obj=false;
var exactlimit;
var eln;
var checked;
var t;
var val;
var q;
var ew;
var em;
var message;
var field;
fields.each(function(){
field=$(this);
exactlimit=field.find("[type='checkbox'][data-exactlimit]");
if(exactlimit.length&&field_is_active(exactlimit)){
eln=parseInt(exactlimit.attr('data-exactlimit'), 10);
checked=0;
field.find("input.tm-epo-field[type='checkbox']:checked").each(function(){
t=$(this);
q=t.closest('li.tmcp-field-wrap').find('input.tm-qty');
if(q.length > 0){
val=parseInt(q.val(), 10);
if(val <=0){
val=1;
}
checked=parseInt(checked, 10) + val;
}else{
checked=parseInt(checked, 10) + 1;
}});
ew=field.closest('.cpf-element');
em=ew.find('div.tm-error-min');
if(eln!==checked){
checkall=false;
first_error_obj=field;
if(eln===1){
message=TMEPOJS.tm_epo_global_validator_messages.epoexactsingle.replace('{0}', eln);
}else{
message=TMEPOJS.tm_epo_global_validator_messages.epoexact.replace('{0}', eln);
}
if(em.length){
em.remove();
}
if(TMEPOJS.tm_epo_global_error_label_placement==='before'){
field.closest('.tc-element-container').before('<div class="tm-error-min tm-error tc-cell tcwidth tcwidth-100">' + message + '</div>');
}else{
field.closest('.tc-element-container').after('<div class="tm-error-min tm-error tc-cell tcwidth tcwidth-100">' + message + '</div>');
}
main_product.find(tcAPI.addToCartButtonSelector).first().removeClass('disabled loading fpd-disabled').prop('disabled', false);
}else{
em.remove();
}}
});
if(first_error_obj){
$.tcepo.errorObject[ epoEventId ]=first_error_obj;
}
return checkall;
}
function tm_check_exactlimit_cont(exactlimit_cont, main_product, epoEventId){
$.tcepo.formSubmitEvents[ epoEventId ][ $.tcepo.formSubmitEvents[ epoEventId ].length ]={
trigger: function(){
return tm_exactlimit_cont(exactlimit_cont, main_product, epoEventId);
},
on_true: function(){
return true;
},
on_false: function(){
goto_error_item($(exactlimit_cont).find('.tm-epo-field').first(), epoEventId);
return true;
}};}
function tm_minimumlimit_cont(fields, epoEventId){
var checkall=true;
var first_error_obj=false;
var eln;
var checked;
var t;
var val;
var q;
var ew;
var em;
var message;
var field;
fields.each(function(){
var minimumlimit;
field=$(this);
minimumlimit=field.find("[type='checkbox'][data-minimumlimit]");
if(minimumlimit.length&&field_is_active(minimumlimit)){
eln=parseInt(minimumlimit.attr('data-minimumlimit'), 10);
checked=0;
field.find("input.tm-epo-field[type='checkbox']:checked").each(function(){
t=$(this);
q=t.closest('li.tmcp-field-wrap').find('input.tm-qty');
if(q.length > 0){
val=parseInt(q.val(), 10);
if(val <=0){
val=1;
}
checked=parseInt(checked, 10) + val;
}else{
checked=parseInt(checked, 10) + 1;
}});
ew=field.closest('.cpf-element');
em=ew.find('div.tm-error-min');
if(eln > checked){
checkall=false;
first_error_obj=field;
if(eln===1){
message=TMEPOJS.tm_epo_global_validator_messages.epominsingle.replace('{0}', eln);
}else{
message=TMEPOJS.tm_epo_global_validator_messages.epomin.replace('{0}', eln);
}
if(em.length){
em.remove();
}
if(TMEPOJS.tm_epo_global_error_label_placement==='before'){
field.closest('.tc-element-container').before('<div class="tm-error-min tm-error tc-cell tcwidth tcwidth-100">' + message + '</div>');
}else{
field.closest('.tc-element-container').after('<div class="tm-error-min tm-error tc-cell tcwidth tcwidth-100">' + message + '</div>');
}}else{
em.remove();
}}
});
if(first_error_obj){
$.tcepo.errorObject[ epoEventId ]=first_error_obj;
}
return checkall;
}
function tm_check_minimumlimit_cont(minimumlimit_cont, epoEventId){
$.tcepo.formSubmitEvents[ epoEventId ][ $.tcepo.formSubmitEvents[ epoEventId ].length ]={
trigger: function(){
return tm_minimumlimit_cont(minimumlimit_cont, epoEventId);
},
on_true: function(){
return true;
},
on_false: function(){
goto_error_item(false, epoEventId);
return true;
}};}
function cleanPrice(price){
if(price===null){
return 0;
}
if(typeof price==='object'){
price=price[ 0 ];
}
if(! Number.isFinite(parseFloat(price))){
price=0;
}
return price;
}
function tm_apply_dpd(price, totals, apply, force){
price=cleanPrice(price);
if(apply){
price=$.epoAPI.applyFilter('tc_apply_dpd', price, totals, apply, force);
}
return price;
}
function tm_calculate_product_regular_price(totals, allowfalse){
var price=0;
if(totals.length > 0){
price=totals.data('regular-price');
}
price=$.epoAPI.applyFilter('tc_calculate_product_regular_price', price, totals);
if(allowfalse&&price===false){
return false;
}
price=parseFloat(price);
if(! Number.isFinite(price)){
price=0;
}
return price;
}
function tm_calculate_product_price(totals, allowfalse){
var price=0;
if(totals.length > 0){
price=totals.data('price');
}
price=$.epoAPI.applyFilter('tc_calculate_product_price', price, totals);
if(allowfalse&&price===false){
return false;
}
price=parseFloat(price);
if(! Number.isFinite(price)){
price=0;
}
return price;
}
function calculateMathPrice(price, thisElement, epoObject, noevents, useOriginalPrice, funcTotal, cumulativeTotal){
var formula=price.toString();
var val=0;
var matches;
var match;
var elementWrap;
var element;
var reg;
var elementPrice=0;
var pos;
var type;
var id;
var thisVal;
var thisValForced;
var thisElementId=thisElement.closest('.cpf-element').attr('data-uniqid');
var thisElementWrap=thisElement.closest('.tmcp-ul-wrap');
var totalsHolder_tc_totals_ob=epoObject.this_epo_totals_container.data('totalsHolder_tc_totals_ob');
var thisElementIndex=thisElementWrap.find('.tmcp-field, .tmcp-fee-field, .tmcp-sub-fee-field').filter(':checked').index(thisElement);
var thisElementIndexForced=thisElementWrap.find('.tmcp-field, .tmcp-fee-field, .tmcp-sub-fee-field').index(thisElement);
var this_epo_container=epoObject.is_associated ? epoObject.this_epo_container:epoObject.this_epo_container.not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector);
var constants=$.epoAPI.util.parseJSON(TMEPOJS.tm_epo_math)||{};
var productPrice;
if(thisElementIndex===-1&&! thisElement.is('.tmcp-checkbox, .tmcp-radio')){
thisElementIndex=0;
}
if(thisElementIndexForced===-1&&! thisElement.is('.tmcp-checkbox, .tmcp-radio')){
thisElementIndexForced=0;
}
if(! thisElement.is('.tcdisabled')&&! noevents&&! thisElement.data('addedtcEpoBeforeOptionPriceCalculation')){
jWindow.on('tcEpoBeforeOptionPriceCalculation.math' + thisElementId, function(){
tm_element_epo_rules(epoObject, thisElement, undefined, undefined, undefined, true);
});
jWindow.on('tcEpoAfterOptionPriceCalculation.math' + thisElementId, function(){
thisElement.data('fetchOptionPrices', false);
thisElement.data('fetchOptionPrices-forced', false);
thisElement.data('fetchOptionPrices-fee', false);
thisElement.data('fetchOptionPrices-fee-forced', false);
thisElement.data('fetchOptionPrices-sub-fee', false);
thisElement.data('fetchOptionPrices-sub-fee-forced', false);
});
thisElement.data('addedtcEpoBeforeOptionPriceCalculation', 1);
}
if(thisElement.is('.tmcp-field')){
if(thisElement.data('fetchOptionPrices')){
thisVal=thisElement.data('fetchOptionPrices');
thisValForced=thisElement.data('fetchOptionPrices-forced');
}else{
thisVal=fetchOptionPrices(epoObject, thisElementWrap, '.tmcp-field', 0, 0, [], true);
thisValForced=fetchOptionPrices(epoObject, thisElementWrap, '.tmcp-field', 0, 0, [], true, true);
thisElement.data('fetchOptionPrices', thisVal);
thisElement.data('fetchOptionPrices-forced', thisValForced);
}}else if(thisElement.is('.tmcp-fee-field')){
if(thisElement.data('fetchOptionPrices-fee')){
thisVal=thisElement.data('fetchOptionPrices-fee');
thisValForced=thisElement.data('fetchOptionPrices-fee-forced');
}else{
thisVal=fetchOptionPrices(epoObject, thisElementWrap, '.tmcp-fee-field', 0, 0, [], true);
thisValForced=fetchOptionPrices(epoObject, thisElementWrap, '.tmcp-fee-field', 0, 0, [], true, true);
thisElement.data('fetchOptionPrices-fee', thisVal);
thisElement.data('fetchOptionPrices-fee-forced', thisValForced);
}}else if(thisElement.is('.tmcp-sub-fee-field')){
if(thisElement.data('fetchOptionPrices-sub-fee')){
thisVal=thisElement.data('fetchOptionPrices-sub-fee');
thisValForced=thisElement.data('fetchOptionPrices-sub-fee-forced');
}else{
thisVal=fetchOptionPrices(epoObject, thisElementWrap, '.tmcp-sub-fee-field', 0, 0, [], true);
thisValForced=fetchOptionPrices(epoObject, thisElementWrap, '.tmcp-sub-fee-field', 0, 0, [], true, true);
thisElement.data('fetchOptionPrices-sub-fee', thisVal);
thisElement.data('fetchOptionPrices-sub-fee-forced', thisValForced);
}}
Object.keys(constants).forEach(function(key){
var name;
var value;
if(constants[ key ].name!==''&&constants[ key ].value!==''){
name=constants[ key ].name;
value=constants[ key ].value;
if(constants[ key ].name.isNumeric()){
formula=formula.replace('{' + name + '}', value);
}else{
name=new RegExp('{' + name + '}', 'g');
if(value.startsWith('{')){
formula=formula.replace(name, value);
}else{
formula=formula.replace(name, $.epoAPI.math.unformat(value.replace(',', '.')));
}}
}});
if(totalsHolder_tc_totals_ob!==undefined){
formula=formula.replace(/{quantity}/g, $.epoAPI.math.unformat(totalsHolder_tc_totals_ob.qty));
if(useOriginalPrice&&totalsHolder_tc_totals_ob.original_product_price!==undefined){
productPrice=$.epoAPI.math.unformat(totalsHolder_tc_totals_ob.original_product_price);
}else{
productPrice=$.epoAPI.math.unformat(totalsHolder_tc_totals_ob.product_price);
}}else{
formula=formula.replace(/{quantity}/g, 0);
productPrice=0;
}
productPrice=$.epoAPI.math.toFloat(productPrice);
formula=formula.replace(/{product_price}/g, productPrice);
if(! funcTotal){
funcTotal=0;
}
funcTotal=$.epoAPI.math.toFloat(funcTotal);
formula=formula.replace(/{options_total}/g, funcTotal);
formula=formula.replace(/{product_price_plus_options_total}/g, productPrice + funcTotal);
formula=formula.replace(/{cumulative_total}/g, cumulativeTotal);
formula=formula.replace(/{product_price_plus_cumulative_total}/g, productPrice + cumulativeTotal);
if(thisValForced.floatingBoxData!==undefined&&thisValForced.floatingBoxData[ thisElementIndexForced ]!==undefined){
if(thisValForced.floatingBoxData[ thisElementIndexForced ].input_type==='number'||thisValForced.floatingBoxData[ thisElementIndexForced ].input_type==='hidden'){
formula=formula
.replace(/{this.value}/g, $.epoAPI.math.toFloat($.epoAPI.math.unformat(thisValForced.floatingBoxData[ thisElementIndexForced ].valueText)));
}else{
formula=formula
.replace(/{this.value}/g, $.epoAPI.math.toFloat($.epoAPI.math.unformat(thisValForced.floatingBoxData[ thisElementIndexForced ].valueText, tcAPI.localDecimalSeparator)));
}
if(thisValForced.floatingBoxData[ thisElementIndexForced ].input_type==='number'||thisValForced.floatingBoxData[ thisElementIndexForced ].input_type==='hidden'){
formula=formula
.replace(/{this.rawvalue}/g, $.epoAPI.math.unformat(thisValForced.floatingBoxData[ thisElementIndexForced ].valueText));
}else{
formula=formula
.replace(/{this.rawvalue}/g, $.epoAPI.math.unformat(thisValForced.floatingBoxData[ thisElementIndexForced ].valueText, tcAPI.localDecimalSeparator));
}
if(thisValForced.floatingBoxData[ thisElementIndexForced ].input_type==='number'||thisValForced.floatingBoxData[ thisElementIndexForced ].input_type==='hidden'){
formula=formula
.replace(/{this.text}/g, $.epoAPI.math.unformat(thisValForced.floatingBoxData[ thisElementIndexForced ].valueText));
}else{
formula=formula
.replace(/{this.text}/g, $.epoAPI.math.unformat(thisValForced.floatingBoxData[ thisElementIndexForced ].valueText, tcAPI.localDecimalSeparator));
}
formula=formula
.replace(/{this.value.length}/g, thisValForced.floatingBoxData[ thisElementIndexForced ].valueText.length);
}else{
formula=formula
.replace(/{this.value}/g, 0)
.replace(/{this.rawvalue}/g, '')
.replace(/{this.text}/g, '')
.replace(/{this.value.length}/g, 0);
}
formula=formula
.replace(/{this.count}/g, thisVal.floatingBoxData.length)
.replace(/{this.count.quantity}/g,
thisVal.floatingBoxData
.map(function(x){
return x.quantity;
})
.reduce(function(acc, thisval){
return $.epoAPI.math.toFloat(acc) + $.epoAPI.math.toFloat(thisval);
}, 0)
)
.replace(/{this.quantity}/g, thisElement.data('tm-quantity'));
if(formula.match(/\{(\s)*?field\.([^}]*)}/)){
matches=formula.match(/\{(\s)*?field\.([^}]*)}/g);
matches.forEach(function(field){
match=field.match(/\{(\s)*?field\.([^}]*)}/);
if(undefined!==match[ 2 ]&&'string'===typeof match[ 2 ]){
pos=match[ 2 ].indexOf('.', match[ 2 ].indexOf('.') + 1);
if(pos!==-1){
id=match[ 2 ].substring(0, pos);
type=match[ 2 ].substring(pos + 1);
if($.inArray(type, [ 'price', 'value', 'value.length', 'rawvalue', 'text', 'text.length', 'quantity', 'count', 'count.quantity' ])!==-1){
elementWrap=this_epo_container.find("[data-uniqid='" + $.epoAPI.util.escapeSelector(id) + "']");
if(elementWrap.length){
element=elementWrap.find('.tmcp-field, .tmcp-fee-field, .tmcp-sub-fee-field');
element=element.first();
if(thisElement.attr('id')!==element.attr('id')){
tm_element_epo_rules(epoObject, element, undefined, undefined, undefined, true);
}
if(! thisElement.is('.tcdisabled')&&! noevents&&! thisElement.data('addedfieldtcEpoBeforeOptionPriceCalculation')){
jWindow.on('tcEpoBeforeOptionPriceCalculation.math' + thisElementId, function(){
tm_element_epo_rules(epoObject, thisElement, undefined, undefined, undefined, true);
thisElement.trigger('tm-math-select-change-html-all');
});
thisElement.data('addedfieldtcEpoBeforeOptionPriceCalculation', 1);
}
val=0;
if(elementWrap.is('.tc-container-enabled')){
if(element.is('.tmcp-field')){
val=fetchOptionPrices(epoObject, elementWrap, '.tmcp-field', 0, 0, [], true, undefined, undefined, true);
}else if(element.is('.tmcp-fee-field')){
val=fetchOptionPrices(epoObject, elementWrap, '.tmcp-fee-field', 0, 0, [], true, undefined, undefined, true);
}else if(element.is('.tmcp-sub-fee-field')){
val=fetchOptionPrices(epoObject, elementWrap, '.tmcp-sub-fee-field', 0, 0, [], true, undefined, undefined, true);
}
switch(type){
case 'price':
val=val.total;
break;
case 'value':
case 'text':
case 'rawvalue':
if(val.floatingBoxData){
val=val.floatingBoxData
.map(function(x){
if(x.input_type==='number'||x.input_type==='hidden'){
if(type==='text'||type==='rawvalue'){
return x.valueText;
}
return $.epoAPI.math.unformat(x.valueText);
}
if(type==='text'||type==='rawvalue'){
return x.valueText;
}
return $.epoAPI.math.unformat(x.valueText, tcAPI.localInputDecimalSeparator);
})
.reduce(function(acc, thisval){
if(type==='text'||type==='rawvalue'){
return acc + thisval;
}
return $.epoAPI.math.toFloat(acc) + $.epoAPI.math.toFloat(thisval);
},(type==='text'||type==='rawvalue') ? '':0);
if(type==='text'||type==='rawvalue'){
if(val===''){
val="''";
}else if(! val.toString().isNumeric()){
val="'" + val.replace("'", "\\'") + "'";
}}
}
break;
case 'value.length':
case 'text.length':
if(val.floatingBoxData){
val=val.floatingBoxData
.map(function(x){
return x.valueText;
})
.reduce(function(acc, thisval){
return $.epoAPI.math.toFloat(acc) + thisval.length;
}, 0);
}
break;
case 'quantity':
case 'count.quantity':
if(val.floatingBoxData){
val=val.floatingBoxData
.map(function(x){
return x.quantity;
})
.reduce(function(acc, thisval){
return $.epoAPI.math.toFloat(acc) + $.epoAPI.math.toFloat(thisval);
}, 0);
}
break;
case 'count':
if(val.floatingBoxData){
val=val.floatingBoxData.length;
}
break;
}
if(type!=='text'&&type!=='rawvalue'){
val=$.epoAPI.math.toFloat(val);
if(! Number.isFinite(val)){
val=0;
}}
}}else{
val=0;
}
reg=new RegExp(match[ 0 ]);
if(type==='text'||type==='rawvalue'){
formula=formula.replace(reg, val);
}else{
formula = ! Number.isFinite(val) ? formula.replace(reg, "'" + val.replace("'", "\\'") + "'"):formula.replace(reg, val);
}}
}}
});
}
try {
elementPrice=tcmexp.evaluate(formula);
} catch(e){
elementPrice=0;
}
return elementPrice;
}
function get_price_type(epoObject, obj){
var element=$(obj);
var setter=element;
var cart;
var current_variation;
var rules;
var rulestype;
var _rulestype;
var pricetype;
var variation_id_selector;
var _tmcpulwrap;
cart=epoObject.main_cart;
variation_id_selector="input[name^='variation_id']";
if(cart.find('input.variation_id').length > 0){
variation_id_selector='input.variation_id';
}
current_variation=cart.find(variation_id_selector).val();
if(! current_variation){
current_variation=0;
}
if(element.is('select')){
setter=element.find('option:selected');
}
rules=$.epoAPI.util.parseJSON(setter.attr('data-rules'));
rulestype=$.epoAPI.util.parseJSON(setter.attr('data-rulestype'));
pricetype='';
if(typeof rules==='object'){
if(typeof rulestype==='object'){
if(current_variation in rulestype){
pricetype=rulestype[ current_variation ];
}else{
_rulestype=$.epoAPI.util.parseJSON(element.closest('.tmcp-ul-wrap').attr('data-rulestype'));
if(typeof _rulestype==='object'){
if(current_variation in _rulestype){
pricetype=_rulestype[ current_variation ];
}else{
pricetype=rulestype[ 0 ];
}}else{
pricetype=rulestype[ 0 ];
}}
}else{
rulestype=$.epoAPI.util.parseJSON(element.closest('.tmcp-ul-wrap').attr('data-ulestype'));
if(typeof rulestype==='object'){
if(current_variation in rulestype){
pricetype=rulestype[ current_variation ];
}else{
pricetype=rulestype[ 0 ];
}}
}}else{
_tmcpulwrap=element.closest('.tmcp-ul-wrap');
rules=$.epoAPI.util.parseJSON(_tmcpulwrap.attr('data-rules'));
if(typeof rules==='object'){
if(typeof rulestype==='object'){
if(current_variation in rulestype){
pricetype=rulestype[ current_variation ];
}else{
_rulestype=$.epoAPI.util.parseJSON(_tmcpulwrap.attr('data-rulestype'));
if(typeof _rulestype==='object'){
if(current_variation in _rulestype){
pricetype=_rulestype[ current_variation ];
}else{
pricetype=rulestype[ 0 ];
}}else{
pricetype=rulestype[ 0 ];
}}
}else{
rulestype=$.epoAPI.util.parseJSON(_tmcpulwrap.attr('data-rulestype'));
if(typeof rulestype==='object'){
if(current_variation in rulestype){
pricetype=rulestype[ current_variation ];
}else{
pricetype=rulestype[ 0 ];
}}
}}
}
if(typeof pricetype==='object'){
pricetype=pricetype[ 0 ];
}
if(element.is('.tmcp-fee-field')){
if($.inArray(pricetype, [ 'fee', 'stepfee', 'currentstepfee' ])!==-1){
pricetype='';
}}
return pricetype;
}
function wordLength(str){
var regex=new RegExp(/[\p{L}\d!@#$%^&*()_+=\{[\}\]|\\"':;?/>.<,-]+/, 'gu');
var m;
var len=0;
while(( m=regex.exec(str))!==null){
if(m.index===regex.lastIndex){
regex.lastIndex++;
}
len=len + m.length;
}
return len;
}
function tm_element_epo_rules(epoObject, obj, args, setter_override, noremove, manthnoevent, funcTotal, cumulativeTotal){
var element=$(obj);
var setterall=element;
var cart;
var current_variation;
var bundleid;
var epoTotalsContainer;
var apply_dpd;
var product_price;
var product_original_price;
var is_range_field=element.is('.tmcp-range');
var rules;
var rulestype;
var original_rules;
var _rules;
var _rulestype;
var _original_rules;
var pricetype;
var price;
var original_price;
var raw_price;
var raw_original_price;
var formatted_price;
var original_formatted_price;
var textlength;
var freechars;
var min_value;
var main_product=epoObject.main_product;
var epoEventId=epoObject.epoEventId;
var variation_id_selector;
var _tmcpulwrap;
var cart_total;
var per_product_pricing=true;
var addedPrice=0;
var originalAddedPrice=0;
var undiscounted_raw_price;
var undiscounted_raw_original_price;
var undiscounted_price;
var undiscounted_original_price;
var isFilled;
if(element.data('associated_price_set')){
return;
}
if(! args){
cart=epoObject.main_cart;
if(cart.data('per_product_pricing')!==undefined){
per_product_pricing=cart.data('per_product_pricing');
}
variation_id_selector="input[name^='variation_id']";
if(cart.find('input.variation_id').length > 0){
variation_id_selector='input.variation_id';
}
current_variation=cart.find(variation_id_selector).val();
bundleid=$.epoAPI.applyFilter('tc_get_bundleid', cart.attr('data-product_id'), cart, epoObject);
if(! current_variation){
current_variation=0;
}
epoTotalsContainer=$.epoAPI.applyFilter('tc_get_totals_container', epoObject.this_epo_totals_container, element, main_product, bundleid);
product_price=tm_calculate_product_price(epoTotalsContainer);
product_original_price=tm_calculate_product_regular_price(epoTotalsContainer);
apply_dpd=epoTotalsContainer.data('fields-price-rules');
}else{
cart=args.cart;
current_variation=args.current_variation;
bundleid=args.bundleid;
epoTotalsContainer=args.epoTotalsContainer;
product_price=args.product_price;
product_original_price=args.product_original_price;
apply_dpd=args.apply_dpd;
per_product_pricing=args.per_product_pricing;
}
product_price=$.epoAPI.applyFilter('tc_alter_product_price', product_price, element, cart, epoTotalsContainer, bundleid);
product_original_price=$.epoAPI.applyFilter('tc_alter_product_original_price', product_original_price, element, cart, epoTotalsContainer);
if(product_price===false||! per_product_pricing){
return;
}
if(element.is('select')){
setterall=element.find('option:selected');
}
if(setter_override){
setterall=setter_override;
}
setterall.toArray().forEach(function(setter){
setter=$(setter);
rules=$.epoAPI.util.parseJSON(setter.attr('data-rules'));
rulestype=$.epoAPI.util.parseJSON(setter.attr('data-rulestype'));
original_rules=$.epoAPI.util.parseJSON(setter.attr('data-original-rules'));
if(original_rules===undefined){
original_rules=rules;
}
pricetype='';
if(typeof rules==='object'){
if(current_variation in rules){
price=rules[ current_variation ];
original_price=original_rules[ current_variation ];
}else{
_rules=$.epoAPI.util.parseJSON(element.closest('.tmcp-ul-wrap').attr('data-rules'));
_original_rules=element.closest('.tmcp-ul-wrap').data('original-rules');
if(typeof _rules==='object'){
if(current_variation in _rules){
price=_rules[ current_variation ];
}else{
price=rules[ 0 ];
}}else{
price=rules[ 0 ];
}
if(typeof _original_rules==='object'){
if(current_variation in _original_rules){
original_price=_original_rules[ current_variation ];
}else{
original_price=original_rules[ 0 ];
}}else{
original_price=original_rules[ 0 ];
}}
if(typeof rulestype==='object'){
if(current_variation in rulestype){
pricetype=rulestype[ current_variation ];
}else{
_rulestype=$.epoAPI.util.parseJSON(element.closest('.tmcp-ul-wrap').attr('data-rulestype'));
if(typeof _rulestype==='object'){
if(current_variation in _rulestype){
pricetype=_rulestype[ current_variation ];
}else{
pricetype=rulestype[ 0 ];
}}else{
pricetype=rulestype[ 0 ];
}}
}else{
rulestype=$.epoAPI.util.parseJSON(element.closest('.tmcp-ul-wrap').attr('data-ulestype'));
if(typeof rulestype==='object'){
if(current_variation in rulestype){
pricetype=rulestype[ current_variation ];
}else{
pricetype=rulestype[ 0 ];
}}
}}else{
_tmcpulwrap=element.closest('.tmcp-ul-wrap');
rules=$.epoAPI.util.parseJSON(_tmcpulwrap.attr('data-rules'));
original_rules=$.epoAPI.util.parseJSON(_tmcpulwrap.attr('data-original-rules'));
if(typeof rules==='object'){
if(current_variation in rules){
price=rules[ current_variation ];
}else{
price=rules[ 0 ];
}
if(typeof original_rules==='object'){
if(current_variation in original_rules){
original_price=original_rules[ current_variation ];
}else{
original_price=original_rules[ 0 ];
}}else{
original_price=price;
}
if(typeof rulestype==='object'){
if(current_variation in rulestype){
pricetype=rulestype[ current_variation ];
}else{
_rulestype=$.epoAPI.util.parseJSON(_tmcpulwrap.attr('data-rulestype'));
if(typeof _rulestype==='object'){
if(current_variation in _rulestype){
pricetype=_rulestype[ current_variation ];
}else{
pricetype=rulestype[ 0 ];
}}else{
pricetype=rulestype[ 0 ];
}}
}else{
rulestype=$.epoAPI.util.parseJSON(_tmcpulwrap.attr('data-rulestype'));
if(typeof rulestype==='object'){
if(current_variation in rulestype){
pricetype=rulestype[ current_variation ];
}else{
pricetype=rulestype[ 0 ];
}}
}}
}
if(typeof pricetype==='object'){
pricetype=pricetype[ 0 ];
}
if(element.is('.tmcp-fee-field')){
if($.inArray(pricetype, [ 'fee', 'stepfee', 'currentstepfee' ])!==-1){
pricetype='';
}
apply_dpd=0;
}
if(noremove===undefined){
if(element.is('select')){
element.find('option').removeClass('tm-epo-late-field').removeData('tm-price-for-late islate');
}else{
setter.removeClass('tm-epo-late-field').removeData('tm-price-for-late islate');
}}
if(pricetype!=='math'){
price=cleanPrice(price);
original_price=cleanPrice(original_price);
}
undiscounted_raw_price=price;
undiscounted_raw_original_price=original_price;
switch(pricetype){
case '':
undiscounted_price=price;
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd);
break;
case 'math':
price=calculateMathPrice(price, element, epoObject, manthnoevent, $.epoAPI.applyFilter('tc_use_undiscounted_price', undefined, element, cart, epoTotalsContainer), funcTotal, cumulativeTotal);
undiscounted_price=price;
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd);
original_price=calculateMathPrice(original_price, element, epoObject, true, true, funcTotal, cumulativeTotal);
break;
case 'percent_cart_total':
cart_total=parseFloat(TMEPOJS.cart_total);
if(! Number.isFinite(cart_total)){
cart_total=0;
}
undiscounted_price=(price / 100) * cart_total;
price=(tm_apply_dpd(price, epoTotalsContainer, apply_dpd) / 100) * cart_total;
original_price=(tm_apply_dpd(original_price, epoTotalsContainer, apply_dpd) / 100) * cart_total;
break;
case 'percent':
undiscounted_price=(price / 100) * product_price;
price=(tm_apply_dpd(price, epoTotalsContainer, apply_dpd) / 100) * product_price;
original_price=(original_price / 100) * product_original_price;
break;
case 'percentcurrenttotal':
$.tcepo.lateFieldsPrices[ epoEventId ].push({
setter: setter,
price: price,
original_price: original_price,
bundleid: bundleid,
pricetype: pricetype
});
setter.data('tm-price-for-late', price).data('tm-original-price-for-late', original_price).data('islate', 1).addClass('tm-epo-late-field');
undiscounted_price=0;
price=0;
original_price=0;
break;
case 'fixedcurrenttotal':
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd);
$.tcepo.lateFieldsPrices[ epoEventId ].push({
setter: setter,
price: price,
original_price: original_price,
bundleid: bundleid,
pricetype: pricetype
});
setter.data('tm-price-for-late', price).data('tm-original-price-for-late', original_price).data('islate', 1).addClass('tm-epo-late-field');
undiscounted_price=0;
price=0;
original_price=0;
break;
case 'word':
undiscounted_price=price * wordLength(setter.val());
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd) * wordLength(setter.val());
original_price=original_price * wordLength(setter.val());
break;
case 'wordpercent':
undiscounted_price=(price / 100) * product_price * wordLength(setter.val());
price=(tm_apply_dpd(price, epoTotalsContainer, apply_dpd) / 100) * product_price * wordLength(setter.val());
original_price=(original_price / 100) * product_original_price * wordLength(setter.val());
break;
case 'wordnon':
freechars=parseInt(setter.attr('data-freechars'), 10);
if(! Number.isFinite(freechars)){
freechars=0;
}
textlength=wordLength(setter.val()) - freechars;
if(textlength < 0){
textlength=0;
}
undiscounted_price=price * textlength;
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd) * textlength;
original_price=original_price * textlength;
break;
case 'wordpercentnon':
freechars=parseInt(setter.attr('data-freechars'), 10);
if(! Number.isFinite(freechars)){
freechars=0;
}
textlength=wordLength(setter.val()) - freechars;
if(textlength < 0){
textlength=0;
}
undiscounted_price=(price / 100) * product_price * textlength;
price=(tm_apply_dpd(price, epoTotalsContainer, apply_dpd) / 100) * product_price * textlength;
original_price=(original_price / 100) * product_original_price * textlength;
break;
case 'char':
undiscounted_price=price * setter.val().length;
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd) * setter.val().length;
original_price=original_price * setter.val().length;
break;
case 'charpercent':
undiscounted_price=(price / 100) * product_price * setter.val().length;
price=(tm_apply_dpd(price, epoTotalsContainer, apply_dpd) / 100) * product_price * setter.val().length;
original_price=(original_price / 100) * product_original_price * setter.val().length;
break;
case 'charnospaces':
undiscounted_price=price * setter.val().replace(/\s/g, '').length;
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd) * setter.val().replace(/\s/g, '').length;
original_price=original_price * setter.val().replace(/\s/g, '').length;
break;
case 'charnofirst':
textlength=setter.val().length - 1;
if(textlength < 0){
textlength=0;
}
undiscounted_price=price * textlength;
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd) * textlength;
original_price=original_price * textlength;
break;
case 'charnon':
freechars=parseInt(setter.attr('data-freechars'), 10);
if(! Number.isFinite(freechars)){
freechars=0;
}
textlength=setter.val().length - freechars;
if(textlength < 0){
textlength=0;
}
undiscounted_price=price * textlength;
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd) * textlength;
original_price=original_price * textlength;
break;
case 'charpercentnon':
freechars=parseInt(setter.attr('data-freechars'), 10);
if(! Number.isFinite(freechars)){
freechars=0;
}
textlength=setter.val().length - freechars;
if(textlength < 0){
textlength=0;
}
undiscounted_price=(price / 100) * product_price * textlength;
price=(tm_apply_dpd(price, epoTotalsContainer, apply_dpd) / 100) * product_price * textlength;
original_price=(original_price / 100) * product_original_price * textlength;
break;
case 'charnonnospaces':
freechars=parseInt(setter.attr('data-freechars'), 10);
if(! Number.isFinite(freechars)){
freechars=0;
}
textlength=setter.val().replace(/\s/g, '').length - freechars;
if(textlength < 0){
textlength=0;
}
undiscounted_price=price * textlength;
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd) * textlength;
original_price=original_price * textlength;
break;
case 'charpercentnonnospaces':
freechars=parseInt(setter.attr('data-freechars'), 10);
if(! Number.isFinite(freechars)){
freechars=0;
}
textlength=setter.val().replace(/\s/g, '').length - freechars;
if(textlength < 0){
textlength=0;
}
undiscounted_price=(price / 100) * product_price * textlength;
price=(tm_apply_dpd(price, epoTotalsContainer, apply_dpd) / 100) * product_price * textlength;
original_price=(original_price / 100) * product_original_price * textlength;
break;
case 'charpercentnofirst':
textlength=setter.val().length - 1;
if(textlength < 0){
textlength=0;
}
undiscounted_price=(price / 100) * product_price * textlength;
price=(tm_apply_dpd(price, epoTotalsContainer, apply_dpd) / 100) * product_price * textlength;
original_price=(original_price / 100) * product_original_price * textlength;
break;
case 'step':
if(is_range_field){
undiscounted_price=price * setter.val();
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd) * setter.val();
original_price=original_price * $.epoAPI.math.toFloat(setter.val());
}else{
undiscounted_price=price * $.epoAPI.math.toFloat(setter.val());
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd) * $.epoAPI.math.toFloat(setter.val());
original_price=original_price * $.epoAPI.math.toFloat(setter.val());
}
break;
case 'currentstep':
if(is_range_field){
undiscounted_price=setter.val();
price=tm_apply_dpd(setter.val(), epoTotalsContainer, apply_dpd);
original_price=tm_apply_dpd(setter.val(), epoTotalsContainer, apply_dpd);
}else{
undiscounted_price=$.epoAPI.math.toFloat(setter.val());
price=tm_apply_dpd($.epoAPI.math.toFloat(setter.val()), epoTotalsContainer, apply_dpd);
original_price=tm_apply_dpd($.epoAPI.math.toFloat(setter.val()), epoTotalsContainer, apply_dpd);
}
break;
case 'intervalstep':
if(is_range_field){
min_value=parseFloat($('.tm-range-picker[data-field-id="' + setter.attr('id') + '"]').attr('data-min'));
undiscounted_price=price *(setter.val() - min_value);
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd) *(setter.val() - min_value);
original_price=original_price *(setter.val() - min_value);
}
break;
case 'row':
undiscounted_price=price *(( setter.val().match(/(\r\n|\n|\r)/gm)||[]).length + 1);
price=tm_apply_dpd(price, epoTotalsContainer, apply_dpd) *(( setter.val().match(/(\r\n|\n|\r)/gm)||[]).length + 1);
original_price=original_price *(( setter.val().match(/(\r\n|\n|\r)/gm)||[]).length + 1);
break;
}
raw_price=price;
raw_original_price=original_price;
undiscounted_original_price=original_price;
undiscounted_raw_price=undiscounted_price;
undiscounted_raw_original_price=undiscounted_original_price;
if(element.data('tm-quantity')){
undiscounted_price=undiscounted_price * parseFloat(element.data('tm-quantity'));
undiscounted_original_price=undiscounted_original_price * parseFloat(element.data('tm-quantity'));
undiscounted_raw_price=undiscounted_raw_price * parseFloat(element.data('tm-quantity'));
undiscounted_raw_original_price=undiscounted_raw_original_price * parseFloat(element.data('tm-quantity'));
price=price * parseFloat(element.data('tm-quantity'));
original_price=original_price * parseFloat(element.data('tm-quantity'));
raw_price=raw_price * parseFloat(element.data('tm-quantity'));
raw_original_price=raw_original_price * parseFloat(element.data('tm-quantity'));
}
addedPrice=addedPrice + parseFloat(price);
originalAddedPrice=originalAddedPrice + parseFloat(original_price);
formatted_price=tm_set_price(addedPrice, epoTotalsContainer, false, false, setter, pricetype);
original_formatted_price=tm_set_price(originalAddedPrice, epoTotalsContainer, false, false, setter, pricetype);
element.data('price_set', 1);
setter.data('price_set', 1);
setter.data('undiscounted_raw_price', undiscounted_raw_price);
setter.data('undiscounted_raw_original_price', undiscounted_raw_original_price);
setter.data('undiscounted_price', tm_set_tax_price(undiscounted_price, epoTotalsContainer, setter, pricetype));
setter.data('undiscounted_original_price', tm_set_tax_price(undiscounted_original_price, epoTotalsContainer, setter, pricetype));
setter.data('raw_price', raw_price);
setter.data('raw_original_price', raw_original_price);
setter.data('price', tm_set_tax_price(price, epoTotalsContainer, setter, pricetype));
setter.data('original_price', tm_set_tax_price(original_price, epoTotalsContainer, setter, pricetype));
if(! setter_override){
if(element.is('.tc-epo-field-product')){
isFilled=false;
if(element.is('select')){
if(element.val()!==''){
isFilled=true;
}}else if(( element.is(':checkbox')||element.is(':radio'))){
if(element.is(':checked')){
isFilled=true;
}}else if(element.val()!==''){
isFilled=true;
}
if(! isFilled){
formatted_price=setter.data('price-html');
original_formatted_price='';
}}
tm_update_price(setter.closest('.tmcp-field-wrap').find('.tc-price'), addedPrice, formatted_price, originalAddedPrice, original_formatted_price);
element.data('price-changed', 1);
}});
}
function tm_epo_rules(epoObject, theCart){
var all_carts;
var variation_id_selector;
var per_product_pricing=true;
var current_variation;
var bundleid;
var epoContainer;
var epoTotalsContainer;
var apply_dpd;
var rules;
var original_rules;
var price;
var formatted_price;
var original_price;
var original_formatted_price;
var product_price;
var product_original_price;
var all_fields;
var active_fields;
var args;
var main_product=epoObject.main_product;
var epoEventId=epoObject.epoEventId;
var this_epo_container=epoObject.this_epo_container;
var this_epo_totals_container=epoObject.this_epo_totals_container;
if(! theCart){
all_carts=main_product.find('.cart');
}else{
all_carts=theCart;
}
if(all_carts.length <=0){
return;
}
$.tcepo.lateFieldsPrices[ epoEventId ]=[];
all_carts.toArray().forEach(function(cart){
cart=$(cart);
variation_id_selector="input[name^='variation_id']";
if(cart.find('input.variation_id').length > 0){
variation_id_selector='input.variation_id';
}
if(cart.data('per_product_pricing')!==undefined){
per_product_pricing=cart.data('per_product_pricing');
}
current_variation=cart.find(variation_id_selector).val();
bundleid=$.epoAPI.applyFilter('tc_get_bundleid', cart.attr('data-product_id'), cart, epoObject);
if(! current_variation){
current_variation=0;
}
epoContainer=$.epoAPI.applyFilter('tc_get_epo_container', this_epo_container, cart, main_product, bundleid);
epoTotalsContainer=$.epoAPI.applyFilter('tc_get_totals_container', this_epo_totals_container, cart, main_product, bundleid);
apply_dpd=epoTotalsContainer.data('fields-price-rules');
if(! epoContainer.data('tm_rules_init_done')){
if(epoTotalsContainer.data('force-quantity')){
cart.find(tcAPI.qtySelector).val(epoTotalsContainer.data('force-quantity'));
}
epoContainer.toArray().forEach(function(el){
$(el).closest('.tmcp-field-wrap').find('.tm-epo-field').data('tm-quantity', $(el).val());
});
epoContainer
.find('.tmcp-attributes, .tmcp-elements')
.toArray()
.forEach(function(element){
element=$(element);
rules=$.epoAPI.util.parseJSON(element.attr('data-rules'));
original_rules=$.epoAPI.util.parseJSON(element.attr('data-original-rules'));
if(typeof rules!=='object'){
rules={
0: '0'
};}
if(typeof original_rules!=='object'){
original_rules={
0: '0'
};}
if(typeof rules==='object'){
price=tm_apply_dpd(rules[ $.epoAPI.math.toFloat(current_variation) ], epoTotalsContainer, apply_dpd);
formatted_price=tm_set_price(price, epoTotalsContainer);
original_price=tm_apply_dpd(original_rules[ $.epoAPI.math.toFloat(current_variation) ], epoTotalsContainer, apply_dpd);
original_formatted_price=tm_set_price(original_price, epoTotalsContainer);
element
.find('.tmcp-field, .tmcp-fee-field ')
.toArray()
.forEach(function(el){
el=$(el);
if(per_product_pricing){
if(el.attr('data-no-price')==='1'){
price=0;
original_price=0;
}
el.data('raw_price', price);
el.data('raw_original_price', original_price);
el.data('price', tm_set_tax_price(price, epoTotalsContainer, el));
el.data('original_price', tm_set_tax_price(original_price, epoTotalsContainer, el));
tm_update_price(el.closest('.tmcp-field-wrap').find('.tc-price'), price, formatted_price, original_price, original_formatted_price);
}else{
el.data('price', 0);
el.data('original_price', 0);
el.closest('.tmcp-field-wrap').find('.amount').empty();
}});
}});
epoContainer.data('tm_rules_init_done', 1);
}
if(! per_product_pricing){
return true;
}
product_price=tm_calculate_product_price(epoTotalsContainer);
product_original_price=tm_calculate_product_regular_price(epoTotalsContainer);
args={
cart: cart,
current_variation: current_variation,
bundleid: bundleid,
epoTotalsContainer: epoTotalsContainer,
product_price: product_price,
product_original_price: product_original_price,
apply_dpd: apply_dpd,
per_product_pricing: per_product_pricing
};
all_fields=epoContainer.find('.tmcp-field,.tmcp-sub-fee-field,.tmcp-fee-field');
if(! epoObject.is_associated){
all_fields=all_fields.not(tcAPI.associatedEpoSelector + ' ' + '.tmcp-field,' + tcAPI.associatedEpoSelector + ' ' + '.tmcp-sub-fee-field,' + tcAPI.associatedEpoSelector + ' ' + '.tmcp-fee-field');
}
active_fields=all_fields.filter('.tcenabled');
if(! $.tcepo.initialActivation[ epoEventId ]||(active_fields.length===0&&all_fields.length > 0)){
all_fields.each(function(){
field_is_active($(this));
});
$.tcepo.initialActivation[ epoEventId ]=true;
}
all_fields.filter('.tcenabled').each(function(index, element){
tm_element_epo_rules(epoObject, element, args);
});
all_fields.each(function(index, element){
$(element).on('tc_element_epo_rules', function(){
tm_element_epo_rules(epoObject, element, args);
});
});
});
}
function add_late_fields_prices(epoObject, currentProductPrice, originalProductPrice, options_total, original_options_total, bid, _cart, applydpd){
var total=0;
var originalTotal=0;
var totalFees=0;
var originalTotalFees=0;
var price;
var originalPrice;
var priceType;
var setter;
var id;
var hidden;
var bundleid;
var realSetter;
var productId;
var epoId;
var formattedPrice;
var originalFormattedPrice;
var epoEventId=epoObject.epoEventId;
var taxPrice;
var taxOriginalPrice;
var hiddenName;
var productPrice;
var oProductPrice;
var apply_dpd;
if(applydpd!==undefined){
apply_dpd=applydpd;
}else{
apply_dpd=epoObject.this_epo_totals_container.data('fields-price-rules');
}
productPrice=currentProductPrice;
oProductPrice=originalProductPrice;
$.tcepo.lateFieldsPrices[ epoEventId ].forEach(function(field){
price=field.price;
originalPrice=field.original_price;
priceType=field.pricetype;
setter=field.setter;
bundleid=field.bundleid;
realSetter=setter;
if(priceType==='percentcurrenttotal'){
hiddenName='_hidden';
}else{
hiddenName='_hiddenfixed';
}
if(setter.is('option')){
realSetter=setter.closest('select');
}
productPrice=parseFloat($.epoAPI.applyFilter('tc_alter_product_price', productPrice, realSetter, _cart, epoObject.this_epo_totals_container, bid));
oProductPrice=parseFloat($.epoAPI.applyFilter('tc_alter_original_product_price', oProductPrice, realSetter, _cart, epoObject.this_epo_totals_container, bid));
id=$.epoAPI.dom.id(realSetter.attr('name'));
productId=$('.tc-totals-form.tm-totals-form-' + _cart.attr('data-cart-id')).attr('data-product-id');
epoId=$('.tc-totals-form.tm-totals-form-' + _cart.attr('data-cart-id')).attr('data-epo-id');
hidden=$('.tc-extra-product-options.tm-product-id-' + productId + "[data-epo-id='" + epoId + "']").find('#' + id + hiddenName);
if(bundleid===bid){
if(priceType==='percentcurrenttotal'){
price=(parseFloat(price) / 100) *(tm_apply_dpd(parseFloat(productPrice), epoObject.this_epo_totals_container, apply_dpd) + parseFloat(options_total));
originalPrice=(parseFloat(originalPrice) / 100) *(parseFloat(oProductPrice) + parseFloat(original_options_total));
}else if(priceType==='fixedcurrenttotal'){
price=parseFloat(price) + parseFloat(options_total);
originalPrice=parseFloat(originalPrice) + parseFloat(original_options_total);
}
if(realSetter.data('tm-quantity')){
price=price * parseFloat(realSetter.data('tm-quantity'));
originalPrice=originalPrice * parseFloat(realSetter.data('tm-quantity'));
}
if(setter.data('isset')===1&&field_is_active(setter)){
if(realSetter.is('.tmcp-field')){
total=total + price;
originalTotal=originalTotal + originalPrice;
}else if(realSetter.is('.tmcp-fee-field')){
totalFees=totalFees + price;
originalTotalFees=originalTotalFees + originalPrice;
}}
taxPrice=tm_set_tax_price(price, _cart, setter);
taxOriginalPrice=tm_set_tax_price(originalPrice, _cart, setter);
formattedPrice=tm_set_price(price, _cart, false, false, setter);
originalFormattedPrice=tm_set_price(originalPrice, _cart, false, false, setter);
setter.data('price', taxPrice);
setter.data('pricew', taxPrice);
setter.data('original_price', taxOriginalPrice);
setter.data('original_pricew', taxOriginalPrice);
tm_update_price(setter.closest('.tmcp-field-wrap').find('.tc-price'), taxPrice, formattedPrice, taxOriginalPrice, originalFormattedPrice);
if(hidden.length===0){
realSetter.before('<input type="hidden" id="' + id + hiddenName + '" name="' + id + hiddenName + '" value="' + tm_set_price_without_tax(price, _cart) + '">');
}
if(setter.is('.tm-epo-field.tmcp-radio')){
if(setter.is(':checked')){
hidden.val(tm_set_price_without_tax(price, _cart));
}}else{
hidden.val(tm_set_price_without_tax(price, _cart));
}}else if(setter.data('pricew')!==undefined){
formattedPrice=tm_set_price(setter.data('pricew'), _cart, true, false, setter);
originalFormattedPrice='';
if(setter.data('original_pricew')!==undefined){
originalFormattedPrice=tm_set_price(setter.data('original_pricew'), _cart, true, false, setter);
}
tm_update_price(setter.closest('.tmcp-field-wrap').find('.tc-price'), setter.data('pricew'), formattedPrice, setter.data('original_pricew'), originalFormattedPrice);
}});
return {
normal: [ total, originalTotal ],
fees: [ totalFees, originalTotalFees ]
};}
function tm_lazyload(){
var container;
if(TMEPOJS.tm_epo_no_lazy_load==='yes'){
return;
}
if(tmLazyloadContainer){
container=$(tmLazyloadContainer).find('img.tmlazy');
}else{
container=$('.tc-extra-product-options img.tmlazy');
}
container.lazyLoadXT();
container.on('lazyshow', function(){
jWindow.trigger('lazyLoadXToncomplete');
});
}
function tm_css_styles(obj){
var slider;
var $cart;
if(! obj){
return;
}
$cart=$('.cart');
obj.find('.tm-owl-slider-section').each(function(){
slider=$(this);
slider.find('.tc-slider-content').addClass('tm-owl-slider');
slider=slider.find('.tm-owl-slider');
slider
.addClass('tcowl-carousel-show')
.addClass('tcowl-carousel')
.on('changed.owl.carousel', function(){
$cart.css('display', 'block').addClass('slider-setup');
})
.tmowlCarousel(Object.assign({
rtl: TMEPOJS.isRTL==='1',
dots: false,
nav: true,
items: 1,
autoHeight: true,
mouseDrag: false,
touchDrag: true,
navText: [ TMEPOJS.i18n_prev_text, TMEPOJS.i18n_next_text ],
navClass: [ 'owl-prev button', 'owl-next button' ],
navElement: 'a',
loop: false,
navRewind: false
}, window.tmowlCarouselSettings||{}));
slider.removeClass('tcowl-carousel-show');
});
if($.fn.tcTabs){
obj.find('.tc-tabs').tcTabs({
headers: 'tc-tab-headers',
header: 'tab-header',
dataopenattribute: 'data-tab',
sortabletabs: false
});
}}
function repeaterAdd(el, elementInnerWrap){
var cpf=elementInnerWrap.closest('.cpf-element');
var maxRows=cpf.data('repeater-max-rows');
var repeater=elementInnerWrap.find('.tc-repeater-element');
var rows=repeater.length;
var repeaterLast=repeater.last();
var repeaterLastUL=repeater.last().find('.tmcp-ul-wrap');
var clone;
var cloneUl;
var originalId=el.data('tc-repeater-id');
var index=el.data('tc-repeater-init');
if(maxRows){
if(rows >=maxRows){
return false;
}}
if(rows + 1 >=maxRows&&el.is('.tc-repeater-add')){
el.closest('.tc-repeater-wrap').addClass('tc-hidden');
}
if(repeaterLastUL.is('.tm-element-ul-date, .tm-element-ul-time')){
repeaterLastUL.find('.tm-epo-field').tm_datepicker('destroy');
repeaterLastUL.find('.tmcp-date-select').off();
}
if(repeaterLastUL.is('.tm-element-ul-color')){
repeaterLastUL.find('.tm-epo-field').spectrum('destroy');
}
clone=repeaterLast.tcClone(true);
clone.find('.tm-epo-field').attr('id', function(i, value){
return value.replace(/\_\d+$/g, '') + '_' + index;
});
clone.find('[data-for]').attr('data-for', function(i, value){
return value.replace(/\_\d+$/g, '') + '_' + index;
});
clone.find('[for]').attr('for', function(i, value){
return value.replace(/\_\d+$/g, '') + '_' + index;
});
clone.find('[data-field-id]').attr('data-field-id', function(i, value){
return value.replace(/\_\d+$/g, '') + '_' + index;
});
clone.find('[data-tm-date]').attr('data-tm-date', function(){
return originalId + '_' + index;
});
clone.find('.tm-epo-field').attr('name', function(i, value){
return value.replace(/\[\d+\]/g, '[' + index + ']');
});
clone.find('.tm-qty').attr('name', function(i, value){
return value.replace(/\[\d+\]/g, '[' + index + ']');
});
clone.find('.tmcp-date-select').attr('name', function(i, value){
return value.replace(/\[\d+\]/g, '[' + index + ']');
});
clone.find('.tmcp-date-select').attr('id', function(i, value){
return originalId + '_' + index + '_' + value.substring(value.lastIndexOf('_') + 1);
});
cloneUl=clone.find('.tmcp-ul-wrap');
if(elementInnerWrap.find('.tc-repeater-element').length > 0){
elementInnerWrap.find('.tc-repeater-delete').removeClass('tc-hidden');
clone.find('.tc-repeater-delete').removeClass('tc-hidden');
}
if(cloneUl.is('.tm-element-ul-checkbox')){
clone.find('li.tmcp-field-wrap').removeClass('tc-active');
clone
.find('.tm-epo-field.tmcp-checkbox')
.prop('checked', false);
clone
.find('.tm-epo-field.tmcp-checkbox')
.filter(function(i, x){
return $.inArray($(x).val(), el.data('repeater-init-value'))!==-1;
})
.prop('checked', true)
.closest('li.tmcp-field-wrap').addClass('tc-active');
}else if(cloneUl.is('.tm-element-ul-radio')){
clone.find('li.tmcp-field-wrap').removeClass('tc-active');
clone
.find('.tm-epo-field.tmcp-radio')
.filter(function(i, x){
return $(x).val()===el.data('repeater-init-value');
})
.prop('checked', true)
.closest('li.tmcp-field-wrap').addClass('tc-active');
}else{
clone.find('.tm-epo-field').val(el.data('repeater-init-value'));
}
if(! cloneUl.is('.tm-element-ul-checkbox')&&! cloneUl.is('.tm-element-ul-radio')){
clone.find('.tm-epo-field').val(el.data('repeater-init-value'));
}
el.data('tc-repeater-init', el.data('tc-repeater-init') + 1);
return [ clone, repeaterLast, repeaterLastUL ];
}
function repeaterAddAfter(epoObject, clone, repeaterLast, repeaterLastUL, doevents){
var cloneUl=clone.find('.tmcp-ul-wrap');
if(cloneUl.is('.tm-element-ul-range')){
clone.find('.tm-range-picker').removeData('tc-picker-init').attr('class', 'tm-range-picker').html('');
setRangePickers(clone);
}
if(cloneUl.is('.tm-element-ul-date, .tm-element-ul-time')){
tm_set_datepicker(repeaterLastUL);
tm_set_datepicker(cloneUl);
}
if(cloneUl.is('.tm-element-ul-color')){
tm_set_color_pickers(repeaterLastUL);
tm_set_color_pickers(cloneUl);
}
clone.find('.tm-tooltip').removeData('tctooltip').removeData('tm-has-tm-tip');
$.tcToolTip(clone.find('.tm-tooltip'));
clone.find('.tm-epo-field')
.removeData('addedtcEpoBeforeOptionPriceCalculation')
.each(function(y, elc){
var element=$(elc);
field_is_active(element, false, true);
if(element.is('.tcenabled')){
tm_element_epo_rules(epoObject, element);
}
element.on('tc_element_epo_rules', function(){
tm_element_epo_rules(epoObject, element);
});
});
if(! doevents){
return;
}
if(cloneUl.is('.tm-element-ul-checkbox')){
clone
.find('.tm-epo-field.tmcp-checkbox')
.filter(':checked')
.trigger('change.cpf');
}else if(cloneUl.is('.tm-element-ul-radio')){
clone
.find('.tm-epo-field.tmcp-radio')
.filter(':checked')
.trigger('change.cpf');
}else{
clone.find('.tm-epo-field').trigger('change.cpf');
}}
function repeaterDelete(elementInnerWrap, repeaterElement, repeaterObj, $this){
var cpf=elementInnerWrap.closest('.cpf-element');
var minRows=cpf.data('repeater-min-rows');
var rows=elementInnerWrap.find('.tc-repeater-element').length;
var repeaterElementIndex=repeaterElement.index();
var message;
if(minRows){
if(rows <=minRows){
if($this){
message='<div class="tm-error-repeater tm-error tc-cell tcwidth tcwidth-100">' + $.tc_validator.messages.repeaterminrows(minRows) + '</div>';
$this.tcToolTip({ tip: message, onetime: true, trigger: true, tipclass: 'tc-error' });
}
return false;
}}
if(rows===1){
return;
}
if(rows===2){
elementInnerWrap.find('.tc-repeater-delete').addClass('tc-hidden');
}
if(repeaterObj.is('.tc-repeater-add')){
repeaterObj.closest('.tc-repeater-wrap').removeClass('tc-hidden');
}
repeaterElement.remove();
repeaterObj.data('tc-repeater-init', repeaterObj.data('tc-repeater-init') - 1);
if(repeaterElementIndex + 1===rows){
return;
}
elementInnerWrap.find('.tc-repeater-element')
.toArray()
.forEach(function(clone, index){
clone=$(clone);
clone.find('.tm-epo-field').attr('id', function(i, value){
return value.replace(/\_\d+$/g, '') +(( index!==0) ? '_' + index:'');
});
clone.find('[data-for]').attr('data-for', function(i, value){
return value.replace(/\_\d+$/g, '') +(( index!==0) ? '_' + index:'');
});
clone.find('[for]').attr('for', function(i, value){
return value.replace(/\_\d+$/g, '') +(( index!==0) ? '_' + index:'');
});
clone.find('[data-field-id]').attr('data-field-id', function(i, value){
return value.replace(/\_\d+$/g, '') +(( index!==0) ? '_' + index:'');
});
clone.find('[data-tm-date]').attr('data-tm-date', function(i, value){
return value.replace(/\_\d+$/g, '') +(( index!==0) ? '_' + index:'');
});
clone.find('.tm-epo-field').attr('name', function(i, value){
return value.replace(/\[\d+\]/g, '[' + index + ']');
});
clone.find('.tm-qty').attr('name', function(i, value){
return value.replace(/\[\d+\]/g, '[' + index + ']');
});
clone.find('.tmcp-date-select').attr('name', function(i, value){
return value.replace(/\[\d+\]/g, '[' + index + ']');
});
});
}
function tm_set_repeaters(obj, epoObject){
var currentCart;
var qtyElement;
var quantityRepeaters;
if(! obj){
return;
}
obj=$(obj);
if(obj.length){
currentCart=epoObject.main_cart;
qtyElement=getQtyElement(currentCart);
qtyElement=$.epoAPI.applyFilter('qtyElementForRepeaterQuantity', qtyElement, {
epo: epoObject,
currentCart: currentCart,
obj: obj,
qtyElement: qtyElement
});
quantityRepeaters=obj.find('.tc-repeater-quantity');
quantityRepeaters
.toArray()
.forEach(function(repeater, qx){
var el=$(repeater);
var tmEpoField;
var repeaterElement;
var length;
if(el.data('tc-repeater-init')){
return;
}
repeaterElement=el.find('.tc-repeater-element');
length=repeaterElement.length;
tmEpoField=repeaterElement.first().find('.tm-epo-field');
if(tmEpoField.is(':checkbox')){
el.data('repeater-init-value',
tmEpoField.filter(':checked').toArray().map(function(x){
return $(x).val();
}));
}else if(tmEpoField.is(':radio')){
el.data('repeater-init-value', tmEpoField.filter(':checked').val());
}else{
el.data('repeater-init-value', tmEpoField.val());
}
el.data('tc-repeater-init', length);
el.data('tc-repeater-id', tmEpoField.attr('id'));
el.data('tc-repeater-name', tmEpoField.attr('name'));
if(qtyElement.length){
qtyElement
.off('change.r' + qx + 'cpf input.r' + qx + 'cpf')
.on('change.r' + qx + 'cpf input.r' + qx + 'cpf', function(event){
var field=$(this);
var prevValue=field.data('tm-prev-value');
var value=$.epoAPI.applyFilter('qtyElementForRepeaterQuantityValue', field.val(), {
epo: epoObject,
currentCart: currentCart,
obj: obj,
qtyElement: qtyElement,
field: field
});
var difference=value - prevValue;
var elementInnerWrap;
var thisRepeaterElement;
var i;
var ele;
var cloned;
var repeaterLast;
var repeaterLastUL;
var fieldprevval;
if(prevValue===undefined){
prevValue=value - 1;
difference=value - prevValue;
}
if(event.isTrigger!==undefined){
prevValue=el.find('.tc-element-inner-wrap').find('.tc-repeater-element').length;
difference=value - prevValue;
}
if(difference===0){
return;
}
elementInnerWrap=el.find('.tc-element-inner-wrap');
fieldprevval=$.epoAPI.applyFilter('qtyElementForRepeaterQuantity_tm-prev-value', field.val(), {
epo: epoObject,
currentCart: currentCart,
obj: obj,
qtyElement: qtyElement,
field: field
});
if(fieldprevval <=0){
fieldprevval=1;
}
if(qx===quantityRepeaters.length){
field.data('tm-prev-value', fieldprevval);
}
if(difference > 0){
thisRepeaterElement=elementInnerWrap.find('.tc-repeater-element').eq(value - 1);
if(thisRepeaterElement.length){
return;
}
for(i=0; i < difference; i++){
cloned=repeaterAdd(el, elementInnerWrap);
if(cloned){
if(ele){
ele=ele.add(cloned[ 0 ]);
}else{
ele=cloned[ 0 ];
}
if(i===0){
repeaterLast=cloned[ 1 ];
repeaterLastUL=cloned[ 2 ];
}}
}
if(ele){
ele.appendTo(elementInnerWrap.find('.tc-element-container'));
repeaterAddAfter(epoObject, ele, repeaterLast, repeaterLastUL);
}}else{
for(i=value - difference; i > value; i -=1){
thisRepeaterElement=elementInnerWrap.find('.tc-repeater-element').eq(i - 1);
repeaterDelete(elementInnerWrap, thisRepeaterElement, el);
}}
currentCart.trigger({
type: 'tm-epo-update',
norules: 2
});
});
qtyElement.data('tm-prev-value', $.epoAPI.applyFilter('qtyElementForRepeaterQuantityValue', qtyElement.val(), {
epo: epoObject,
currentCart: currentCart,
obj: obj,
qtyElement: qtyElement,
field: qtyElement
})).trigger('change');
}});
obj.find('.tc-repeater-add')
.toArray()
.forEach(function(repeater){
var el=$(repeater);
var tmEpoField;
var elementInnerWrap;
var repeaterElement;
var length;
if(el.data('tc-repeater-init')){
return;
}
elementInnerWrap=el.closest('.tc-element-inner-wrap');
repeaterElement=elementInnerWrap.find('.tc-repeater-element');
length=repeaterElement.length;
tmEpoField=repeaterElement.first().find('.tm-epo-field');
if(elementInnerWrap.find('.tc-repeater-element').length > 1){
elementInnerWrap.find('.tc-repeater-delete').removeClass('tc-hidden');
}
if(tmEpoField.is(':checkbox')){
el.data('repeater-init-value',
tmEpoField.filter(':checked').toArray().map(function(x){
return $(x).val();
}));
}else if(tmEpoField.is(':radio')){
el.data('repeater-init-value', tmEpoField.filter(':checked').val());
}else{
el.data('repeater-init-value', tmEpoField.val());
}
el.data('tc-repeater-init', length);
el.data('tc-repeater-id', tmEpoField.attr('id'));
el.data('tc-repeater-name', tmEpoField.attr('name'));
el.on('click.repeater', function(){
var ele=repeaterAdd(el, elementInnerWrap);
if(ele){
ele[ 0 ].appendTo(elementInnerWrap.find('.tc-element-container'));
repeaterAddAfter(epoObject, ele[ 0 ], ele[ 1 ], ele[ 2 ], true);
}});
});
obj.find('.tc-repeater-delete .delete').on('click', function(){
var $this=$(this);
var elementInnerWrap=$this.closest('.tc-element-inner-wrap');
var repeaterElement=$this.closest('.tc-repeater-element');
repeaterDelete(elementInnerWrap, repeaterElement, elementInnerWrap.find('.tc-repeater-add'), $this);
});
}}
function tm_set_color_pickers(obj){
if(! obj){
return;
}
obj=$(obj).find('.tm-color-picker');
if(obj.length){
obj.spectrum({
type: 'color',
theme: 'epo',
showButtons: true,
allowEmpty: true,
showInitial: true,
showInput: true,
clickoutFiresChange: false,
chooseText: TMEPOJS.closeText,
cancelText: TMEPOJS.i18n_cancel
});
obj.spectrum('enable');
}}
function tm_set_lightbox(obj){
if(! obj){
return;
}
if($(obj).length){
$(function(){
$(obj).tclightbox();
});
}}
function has_active_changes_product_image(field){
var uic=field.closest('.tmcp-field-wrap').find('label img');
var src=$(uic).first().attr('data-original');
if(field.is('select.tm-product-image')){
field=field.children('option:selected');
}
if(! src){
src=$(uic).first().attr('src');
}
if(! src){
src=field.attr('data-image');
}
if(field.attr('data-imagep')){
src=field.attr('data-imagep');
}
if(src){
return true;
}
return false;
}
function tm_set_upload_fields(epoObject){
var field;
var dT;
var name;
var file;
var selector=epoObject.is_associated
? epoObject.this_epo_container.find('.tm-epo-field.tmcp-upload')
: epoObject.this_epo_container.find('.tm-epo-field.tmcp-upload').not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector + ' .tm-epo-field.tmcp-upload');
try {
selector
.not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector + ' .tm-epo-field.tmcp-upload')
.toArray()
.forEach(function(el){
var dataFiles;
var dataFilename;
file=[];
field=$(el);
if(field.attr('data-file')===''){
return false;
}
dataFiles=field.attr('data-file').split('|');
if(dataFiles.length===0){
return false;
}
if(ClipboardEvent||DataTransfer){
dT=new ClipboardEvent('').clipboardData||new DataTransfer();
}
dataFiles.forEach(function(dataFile){
dataFilename=$.epoAPI.util.basename(dataFile);
if(ClipboardEvent||DataTransfer){
dT.items.add(new File([ dataFile ], dataFilename));
}
file.push(dataFile);
});
if(dT){
el.files=dT.files;
}
file=file.join('|');
name=field.attr('name');
field.trigger('tcupload');
field.after('<input type="hidden" class="tmcp-upload-hidden" name="' + name + '" value="' + file + '">');
field.removeAttr('data-file');
});
} catch(err){
window.console.log(err);
$('.tm-epo-field.tmcp-upload').not('.tm-multiple-file-upload').addClass('tc-nodt');
errorObject=err;
}}
function tm_set_upload_rules(epoObject){
var epoEventId=epoObject.epoEventId;
var this_epo_container=epoObject.this_epo_container;
if(TMEPOJS.tm_epo_upload_popup==='yes'){
$.tcepo.formSubmitEvents[ epoEventId ][ $.tcepo.formSubmitEvents[ epoEventId ].length ]={
trigger: function(){
return true;
},
on_true: function(){
var upload_fields=this_epo_container.data('num_uploads');
var thisPopup;
var ajaxSuccessFunc;
if(upload_fields&&Object.keys(upload_fields).length){
thisPopup=$.tcFloatBox({
fps: 1,
ismodal: true,
refresh: 'fixed',
width: '50%',
height: '300px',
classname: 'flasho tc-wrapper',
data: $.epoAPI.template.html(tcAPI.templateEngine.tc_upload_messages, {
files: upload_fields,
title: TMEPOJS.i18n_uploading_files,
message: TMEPOJS.i18n_uploading_message
})
});
ajaxSuccessFunc=function(){
thisPopup.destroy();
jDocument.off('ajaxSuccess', ajaxSuccessFunc);
};
jDocument.on('ajaxSuccess', ajaxSuccessFunc);
}
return true;
},
on_false: function(){
return true;
}};}}
function tm_set_checkboxes_rules(epoObject){
var this_epo_container=epoObject.this_epo_container;
var main_product=epoObject.main_product;
var epoEventId=epoObject.epoEventId;
var limit_cont=this_epo_container.find('.tm-limit');
var exactlimit_cont=this_epo_container.find('.tm-exactlimit');
var minimumlimit_cont=this_epo_container.find('.tm-minimumlimit');
this_epo_container.on('change.cpflimit', 'input.tm-epo-field.tmcp-checkbox', function(){
var $this=$(this);
tm_limit_c_selection($this, true);
tm_exact_c_selection($this, true);
});
if(limit_cont.length){
tm_check_limit_cont(limit_cont, main_product, epoEventId);
}
if(exactlimit_cont.length){
tm_check_exactlimit_cont(exactlimit_cont, main_product, epoEventId);
}
if(minimumlimit_cont.length){
tm_check_minimumlimit_cont(minimumlimit_cont, epoEventId);
}}
function tm_theme_specific_actions(epoObject){
var this_epo_container=epoObject.this_epo_container;
var theme_name=TMEPOJS.theme_name;
var all_epo_selects;
var blaszok_selects;
if(theme_name){
theme_name=theme_name.toLowerCase();
all_epo_selects=this_epo_container.find('select');
switch(theme_name){
case 'flatsome':
case 'flatsome-child':
case 'flatsome child':
all_epo_selects.wrap('<div class="custom select-wrapper"/>');
break;
case 'avada':
case 'avada-child':
case 'avada child':
all_epo_selects.wrap('<div class="avada-select-parent tm-select-parent"></div>');
$('<div class="select-arrow">&#xe61f;</div>').appendTo(this_epo_container.find('.tm-select-parent'));
if(window.calc_select_arrow_dimensions){
window.calc_select_arrow_dimensions();
jWindow.on('tmsectionpoplink cpflogicdone', function(){
window.calc_select_arrow_dimensions();
});
}else if(window.calcSelectArrowDimensions){
window.calcSelectArrowDimensions();
jWindow.on('tmsectionpoplink cpflogicdone', function(){
window.calcSelectArrowDimensions();
});
}
break;
case 'bazar':
case 'bazar-child':
case 'bazar child':
all_epo_selects.wrap('<div class="tm-select-wrapper select-wrapper"/>');
break;
case 'blaszok':
case 'blaszok-child':
case 'blaszok child':
blaszok_selects=function(){
setTimeout(function(){
$('.tm-extra-product-options select')
.not('.hasCustomSelect')
.filter(':visible')
.each(function(){
if(! $(this).is('.mpcthSelect')){
$(this).width($(this).outerWidth());
$(this).customSelect({ customClass: 'mpcthSelect' });
}});
}, 100);
};
jWindow.on('cpflogicrun', function(){
blaszok_selects();
});
jWindow.on('epo_options_visible', function(){
blaszok_selects();
});
break;
case 'handmade':
case 'handmade child theme':
$('.tm-owl-slider.tcowl-carousel').addClass('manual');
break;
}
jWindow.trigger('tm-theme-specific-actions', {
epo: {
theme_name: theme_name,
all_epo_selects: all_epo_selects
}});
}
jDocument.off('click.cpf', '.quantity:not(.buttons_added) .minus, .quantity:not(.buttons_added) .plus').on('click.cpf', '.quantity:not(.buttons_added) .minus, .quantity:not(.buttons_added) .plus', function(){
$(this).closest('.quantity').find(tcAPI.qtySelector).trigger('change.cpf');
});
}
function tm_custom_variations(epoObject, form, item_id, $main_product, $epo_holder){
var epoEventId=epoObject.epoEventId;
var variation_id_selector="input[name^='variation_id']";
var tm_epo_variation_section;
var li_variations;
var composite_load_test;
var form_event;
var type;
var name;
var selector;
var func;
var i;
var eventName=epoObject.is_associated ? 'tc_variation_form.tmlogic':'wc_variation_form.tmlogic';
var eventNamePrefix=epoObject.is_associated ? 'tc_':'';
var variationsForm=epoObject.variations_form;
var variationsTable=epoObject.is_associated ? variationsForm.find('.tc-epo-element-variations'):variationsForm.find('.variations');
var resetSelector=epoObject.is_associated ? '.tc-epo-element-variable-reset-variations':'.reset_variations';
variationsForm.attr('data-epo_id', epoObject.epo_id);
if(form.find('input.variation_id').length > 0){
variation_id_selector='input.variation_id';
}
if($epo_holder.find('.tm-epo-variation-element').length||$epo_holder.data('tm-epo-variation-element')){
tm_epo_variation_section=$epo_holder.find('.tm-epo-variation-section').first();
tm_epo_variation_section.find('.cpf-type-variations').attr('data-epo_id', epoObject.epo_id).attr('data-product_id', variationsForm.attr('data-product_id'));
$epo_holder.data('tm-epo-variation-element', tm_epo_variation_section.find('.tm-epo-variation-element'));
if(item_id&&item_id!=='main'&&! epoObject.is_associated){
variationsForm=epoObject.form;
variationsTable=variationsForm.find('.composite_component[data-item_id="' + item_id + '"]').find('.variations');
variationsForm.attr('data-epo_id', epoObject.epo_id);
if(variationsTable.length===0){
return;
}
li_variations=tm_epo_variation_section.closest('li.tm-extra-product-options-field');
if(! tm_epo_variation_section.is('.tm-hidden')){
variationsTable.hide();
}
variationsTable.after(tm_epo_variation_section.addClass('tm-extra-product-options nopadding'));
if(li_variations.is(':empty')){
li_variations.hide();
}
if(! tm_epo_variation_section.is('.section_popup')){
tm_epo_variation_section.removeClass('tc-cell');
tm_epo_variation_section.wrap("<div class='tc-styled-variations'></div>");
}else{
tm_epo_variation_section.wrap("<div class='tc-styled-variations tc-row'></div>");
}
composite_load_test=false;
form.off(eventName).on(eventName, function(){
composite_load_test=true;
variationsForm.on('click.tmlogic', '.reset_variations', function(){
tm_epo_variation_section.find('select.tm-epo-variation-element').val('').children('option').prop('disabled', false).show();
tm_epo_variation_section.find('.tm-epo-variation-element').prop('disabled', false).removeClass('tm-disabled').prop('checked', false).closest('li').show();
jWindow.trigger('tmlazy');
tm_epo_variation_section.find('.tm-epo-variation-element').trigger('tm_trigger_product_image');
tm_epo_variation_section.find('li').removeClass('tc-active tm-attribute-disabled').css('opacity', '');
});
form.off('woocommerce_update_variation_values_tmlogic').on('woocommerce_update_variation_values_tmlogic', function(){
tm_custom_variations_update(form, epoObject);
});
for(i=0; i < lateVariationEvent.length; i +=1){
form_event=lateVariationEvent[ i ];
type=typeof form_event;
if(type==='object'){
name=typeof form_event.name==='string'||false;
selector=typeof form_event.selector==='string'||false;
func=typeof form_event.func==='function'||false;
if(name&&func){
if(selector==="input[name='variation_id']"){
selector=variation_id_selector;
}
if(form_event.selector){
form.data('tm-styled-variations', 1)
.off(eventNamePrefix + form_event.name + i, selector)
.on(eventNamePrefix + form_event.name + i, selector, form_event.func);
}else{
form.data('tm-styled-variations', 1)
.off(eventNamePrefix + form_event.name + i)
.on(eventNamePrefix + form_event.name + i, form_event.func);
}}
}}
lateVariationEvent=[];
tm_epo_variation_section.find('.tm-epo-variation-element:not(.tm-hidden .tm-epo-variation-element)').last().trigger('tm_epo_variation_element_change');
});
$(function(){
if(composite_load_test===false){
form.trigger(eventName);
}});
}else{
if(tm_epo_variation_section.length){
if(! tm_epo_variation_section.is('.tm-hidden')){
variationsTable.hide();
}
li_variations=tm_epo_variation_section.closest('li.tm-extra-product-options-field');
variationsTable.after(tm_epo_variation_section.addClass('tm-extra-product-options nopadding'));
if(li_variations.is(':empty')){
li_variations.hide();
}
if(! tm_epo_variation_section.is('.section_popup')){
tm_epo_variation_section.removeClass('tc-cell');
tm_epo_variation_section.wrap("<div class='tc-styled-variations'></div>");
}else{
tm_epo_variation_section.wrap("<div class='tc-styled-variations tc-row'></div>");
}
variationsForm.off('click.tmlogic', resetSelector).on('click.tmlogic', resetSelector, function(){
tm_epo_variation_section.find('select.tm-epo-variation-element').val('').children('option').prop('disabled', false).show();
tm_epo_variation_section.find('.tm-epo-variation-element').prop('disabled', false).removeClass('tm-disabled').prop('checked', false).closest('li').show();
jWindow.trigger('tmlazy');
tm_epo_variation_section.find('.tm-epo-variation-element').trigger('tm_trigger_product_image');
tm_epo_variation_section.find('li').removeClass('tc-active tm-attribute-disabled').css('opacity', '');
});
}
variationsForm.off('woocommerce_update_variation_values_tmlogic').on('woocommerce_update_variation_values_tmlogic', function(){
tm_custom_variations_update(variationsForm, epoObject);
});
for(i=0; i < lateVariationEvent.length; i +=1){
form_event=lateVariationEvent[ i ];
type=typeof form_event;
if(type==='object'){
name=typeof form_event.name==='string'||false;
selector=typeof form_event.selector==='string'||false;
func=typeof form_event.func==='function'||false;
if(name&&func){
if(selector==="input[name='variation_id']"){
selector=variation_id_selector;
}
if(form_event.selector){
variationsForm
.data('tm-styled-variations', 1)
.off(eventNamePrefix + form_event.name + i, selector)
.on(eventNamePrefix + form_event.name + i, selector, form_event.func);
}else{
variationsForm
.data('tm-styled-variations', 1)
.off(eventNamePrefix + form_event.name + i)
.on(eventNamePrefix + form_event.name + i, form_event.func);
}}
}}
lateVariationEvent=[];
tm_epo_variation_section.find('.tm-epo-variation-element:not(.tm-hidden .tm-epo-variation-element)').last().trigger('tm_epo_variation_element_change');
}
$.tcepo.formSubmitEvents[ epoEventId ][ $.tcepo.formSubmitEvents[ epoEventId ].length ]={
trigger: function(){
return true;
},
on_true: function(){
tm_epo_variation_section.find('.tm-epo-variation-element').attr('disabled', 'disabled');
return true;
},
on_false: function(){
tm_epo_variation_section.find('.tm-epo-variation-element').prop('disabled', false);
}};
$(document.body).on('added_to_cart', function(){
tm_epo_variation_section.find('.tm-epo-variation-element').prop('disabled', false);
});
}}
function repopulate_backup_image_atts(img, product_element){
var $gallery_img=product_element.find('.flex-control-nav li:eq(0) img');
var $gallery_wrapper=product_element.find('.woocommerce-product-gallery__wrapper ');
var $product_img_wrap=$gallery_wrapper.find('.woocommerce-product-gallery__image, .woocommerce-product-gallery__image--placeholder').eq(0);
var $product_img=img;
var $product_link=img.closest('a');
$product_img.attr('data-o_' + 'src', $.tc_product_image_store[ 0 ].src);
$product_img.attr('data-o_' + 'srcset', $.tc_product_image_store[ 0 ].srcset);
$product_img.attr('data-o_' + 'sizes', $.tc_product_image_store[ 0 ].sizes);
$product_img.attr('data-o_' + 'title', $.tc_product_image_store[ 0 ].title);
$product_img.attr('data-o_' + 'alt', $.tc_product_image_store[ 0 ].alt);
$product_img.attr('data-o_' + 'data-src', $.tc_product_image_store[ 0 ][ 'data-src' ]);
$product_img.attr('data-o_' + 'data-large_image', $.tc_product_image_store[ 0 ][ 'data-large_image' ]);
$product_img.attr('data-o_' + 'data-large_image_width', $.tc_product_image_store[ 0 ][ 'data-large_image_width' ]);
$product_img.attr('data-o_' + 'data-large_image_height', $.tc_product_image_store[ 0 ][ 'data-large_image_height' ]);
$product_img_wrap.attr('data-o_' + 'data-thumb', $.tc_product_image_store[ 1 ][ 'data-thumb' ]);
if($.tc_product_image_store[ 2 ]){
$gallery_img.attr('data-o_' + 'src', $.tc_product_image_store[ 2 ].src);
}
$product_link.attr('data-o_' + 'href', $.tc_product_image_store[ 3 ].href);
$product_link.attr('data-o_' + 'title', $.tc_product_image_store[ 3 ].title);
}
function reset_saved_image(img, product_element){
var $gallery_img=product_element.find('.flex-control-nav li:eq(0) img');
var $gallery_wrapper=product_element.find('.woocommerce-product-gallery__wrapper ');
var $product_img_wrap=$gallery_wrapper.find('.woocommerce-product-gallery__image, .woocommerce-product-gallery__image--placeholder').eq(0);
var $product_img=img;
var $product_link=img.closest('a');
if(! $.isEmptyObject($.tc_product_image)){
$.tc_product_image_store=$.tc_pre_populate_store();
$.tc_product_image_store=$.tc_maybe_copy_object_values($.tc_product_image_store, $.tc_product_image);
}else{
$.tc_product_image_store=$.tc_populate_store(img, product_element);
}
$product_img.tc_update_attr('src', 0);
$product_img.tc_update_attr('srcset', 0);
$product_img.tc_update_attr('sizes', 0);
$product_img.tc_update_attr('title', 0);
$product_img.tc_update_attr('alt', 0);
$product_img.tc_update_attr('data-src', 0);
$product_img.tc_update_attr('data-large_image', 0);
$product_img.tc_update_attr('data-large_image_width', 0);
$product_img.tc_update_attr('data-large_image_height', 0);
$product_img_wrap.tc_update_attr('data-thumb', 1);
$gallery_img.tc_update_attr('src', 2);
$product_link.tc_update_attr('href', 3);
$product_link.tc_update_attr('title', 3);
}
function image_update(data, img, product_element){
var $gallery_img=product_element.find('.flex-control-nav li:eq(0) img');
var $gallery_wrapper=product_element.find('.woocommerce-product-gallery__wrapper ');
var $product_img_wrap=$gallery_wrapper.find('.woocommerce-product-gallery__image, .woocommerce-product-gallery__image--placeholder').eq(0);
var $product_img=img;
var $product_link=img.closest('a');
var $img_zoom=$product_link.next('.zoomImg');
if(data&&data.image_link&&data.image_link&&data.image_link.length > 1){
if(data.full_src===null||data.full_src===''){
data.full_src=data.image_link;
}
if(data.full_src_w===null||data.full_src_w===''){
data.full_src_w=$product_img.attr('data-large_image_width');
}
if(data.full_src_h===null||data.full_src_h===''){
data.full_src_h=$product_img.attr('data-large_image_height');
}
if($product_img.length){
if(! data.image_srcset){
data.image_sizes=false;
}
if(! data.image_sizes){
data.image_srcset=false;
}
$product_img.tc_set_attr('src', data.image_link, 0);
$product_img.tc_set_attr('srcset', data.image_srcset, 0);
$product_img.tc_set_attr('sizes', data.image_sizes, 0);
$product_img.tc_set_attr('title', data.image_title, 0);
$product_img.tc_set_attr('alt', data.image_alt, 0);
$product_img.tc_set_attr('data-src', data.full_src, 0);
$product_img.tc_set_attr('data-large_image', data.full_src, 0);
$product_img.tc_set_attr('data-large_image_width', data.full_src_w, 0);
$product_img.tc_set_attr('data-large_image_height', data.full_src_h, 0);
$product_img_wrap.tc_set_attr('data-thumb', data.image_link, 1);
}
if($gallery_img.length){
$gallery_img.tc_set_attr('src', data.image_link, 2);
}
if($product_link.length){
$product_link.tc_set_attr('href', data.full_src, 3);
$product_link.tc_set_attr('title', data.image_caption, 3);
}
if($img_zoom.length){
$img_zoom.tc_set_attr('src', data.full_src, 4);
}}else{
if($product_img.length){
$product_img.tc_reset_attr('src', 0);
$product_img.tc_reset_attr('srcset', 0);
$product_img.tc_reset_attr('sizes', 0);
$product_img.tc_reset_attr('title', 0);
$product_img.tc_reset_attr('alt', 0);
$product_img.tc_reset_attr('data-src', 0);
$product_img.tc_reset_attr('data-large_image', 0);
$product_img.tc_reset_attr('data-large_image_width', 0);
$product_img.tc_reset_attr('data-large_image_height', 0);
$product_img_wrap.tc_reset_attr('data-thumb', 1);
}
if($gallery_img.length){
$gallery_img.tc_reset_attr('src', 2);
}
if($product_link.length){
$product_link.tc_reset_attr('href', 3);
$product_link.tc_reset_attr('title', 3);
}
if($img_zoom.length){
$img_zoom.tc_reset_attr('src', 4);
}}
}
function get_main_product_image(epoObject, product_element){
var img;
if(epoObject.is_associated){
img=product_element.find('.tc-product-image .wp-post-image').first();
}else if(TMEPOJS.tm_epo_global_product_image_selector!==''){
img=$(TMEPOJS.tm_epo_global_product_image_selector);
}else{
img=product_element.find('.woocommerce-product-gallery__image:not(.clone), .woocommerce-product-gallery__image--placeholder:not(.clone)').eq(0).find('.wp-post-image').first();
if(img.length===0){
img=product_element.find('a.woocommerce-main-image img, img.woocommerce-main-image,a img').not('.thumbnails img,.product_list_widget img').first();
}
if(img.length===0){
img=product_element.find('img.wp-post-image').not('.thumbnails img,.product_list_widget img').first();
}
if(img.length===0){
img=product_element.find('.elementor-widget-wd_single_product_gallery img.wp-post-image').first();
}
if(img.length===0){
img=product_element.find('.elementor-widget-ae-post-image .wp-post-image').first();
}
if(img.length===0){
img=$('.woocommerce div.product div.images').not('.thumbnails img,.product_list_widget img').first();
}}
if($(img).length > 1){
img=$(img).first();
}
return img;
}
function get_product_element(epoObject){
var main_product;
var product_id;
var product_element;
if(epoObject.is_associated){
return epoObject.main_product.closest('.tc-epo-element-product-container');
}
main_product=epoObject.main_product;
product_id=epoObject.product_id;
product_element=main_product.closest('#product-' + product_id);
if(product_element.length <=0){
product_element=main_product.closest('.post-' + product_id);
}
return product_element;
}
function gallery_compatibility_actions(gallery_type, clone_image, preload_img, visible, event_data, $form, product_element){
var gallery;
var _elements;
var ge;
var galleryWidth;
var zoomEnabled;
var image;
var zoom_options;
for(gallery in gallery_type){
if(Object.prototype.hasOwnProperty.call(gallery_type, gallery)){
gallery=gallery_type[ gallery ];
if(gallery.enabled){
switch(gallery.type){
case 'yith':
if(! clone_image){
if(! visible){
gallery.yith_wcmg_zoom.attr('href', gallery._yith_wcmg_default_zoom);
}else{
gallery.yith_wcmg_zoom.attr('href', gallery.yith_wcmg_default_zoom);
}
if(gallery.element.data('yith_magnifier')){
gallery.element.yith_magnifier('destroy');
}
gallery.element.yith_magnifier(window.yith_magnifier_options);
}else{
clone_image.attr('srcset', preload_img).attr('src-orig', preload_img);
if(gallery.element.data('yith_magnifier')){
gallery.element.yith_magnifier('destroy');
}
_elements={
elements: {
zoom: $('.yith_magnifier_zoom'),
zoomImage: clone_image,
gallery: $('.yith_magnifier_gallery li a')
}};
gallery.element.yith_magnifier($.extend(true, {}, window.yith_magnifier_options, _elements));
}
break;
case 'iosslider':
setTimeout(
function(g){
g.element.iosSlider('update');
}.bind(null, gallery),
150
);
break;
case 'flexslider':
jWindow.trigger('resize');
break;
case 'elevatezoom':
gallery.element.each(function(g, j){
var elevateZoom=j(this).data('elevateZoom');
if(typeof elevateZoom!=='undefined'){
elevateZoom.swaptheimage(g, g);
}}.bind(null, preload_img, $)
);
break;
case 'easyzoom':
gallery.element.swap(null, preload_img);
break;
case 'easyzoom-flatsome':
gallery.element.swap(preload_img, preload_img);
break;
case 'woocommerce':
gallery.element.flexslider(0);
ge=gallery.element;
window.setTimeout(function(g, w){
g.trigger('woocommerce_gallery_init_zoom');
w.trigger('resize');
}.bind(null, ge, jWindow),
10
);
break;
case 'zoom':
if(product_element){
galleryWidth=product_element.find('.woocommerce-product-gallery--with-images').width();
zoomEnabled=false;
image=gallery.element.find('img.wp-post-image');
if(image.attr('data-large_image_width') > galleryWidth){
zoomEnabled=true;
}
if(zoomEnabled){
zoom_options={
touch: false
};
if('ontouchstart' in window){
zoom_options.on='click';
}
gallery.element.trigger('zoom.destroy');
gallery.element.zoom(zoom_options);
}else{
gallery.element.trigger('zoom.destroy');
}}
break;
}}
}}
jWindow.trigger('tm_gallery_compatibility_actions', {
event_data: event_data,
product_element: product_element,
form: $form
});
}
function get_gallery_type(epoObject, img, product_element){
var is_yith_wcmg;
var yith_wcmg;
var yith_wcmg_zoom;
var yith_wcmg_default_zoom;
var _yith_wcmg_default_zoom;
var yith_wcmg_default_image;
var is_iosSlider;
var is_iosSlider_element;
var is_flexslider;
var is_flexslider_element;
var is_elevateZoom;
var is_elevateZoom_obj;
var is_easyzoom;
var is_easyzoom_element;
var is_easyzoom_flatsome;
var is_easyzoom_flatsome_element;
var is_wc27_gallery;
var is_wc27_gallery_element;
var wc27_zoom_target;
var wc_single_product_params;
var zoom_target_temp;
var is_zoom_enabled;
var zoom_images;
var gallery;
if(epoObject.is_associated){
return {};}
is_yith_wcmg=false;
yith_wcmg=$('.images');
yith_wcmg_zoom=$('.yith_magnifier_zoom');
yith_wcmg_default_zoom=yith_wcmg.find('.yith_magnifier_zoom').first().attr('href');
_yith_wcmg_default_zoom=yith_wcmg_default_zoom;
yith_wcmg_default_image=yith_wcmg.find('.yith_magnifier_zoom img').first().attr('src');
is_iosSlider=false;
is_iosSlider_element=$('.iosSlider.product-gallery-slider,.iosSlider.product-slider');
is_flexslider=false;
is_flexslider_element=product_element.find('.images .fusion-flexslider');
is_elevateZoom=img.data('elevateZoom')||false;
is_elevateZoom_obj=product_element.find('div.product-images .woocommerce-main-image');
is_easyzoom=false;
is_easyzoom_element=product_element.find('.images .easyzoom');
is_easyzoom_flatsome=false;
is_easyzoom_flatsome_element=product_element.find('.images .easyzoom');
is_wc27_gallery=false;
is_wc27_gallery_element=product_element.find('.woocommerce-product-gallery');
wc27_zoom_target=false;
wc_single_product_params=window.wc_single_product_params;
is_zoom_enabled=typeof $.fn.zoom==='function'&&wc_single_product_params&&wc_single_product_params.zoom_enabled;
zoom_images=false;
if(window.yith_magnifier_options&&yith_wcmg.data('yith_magnifier')){
is_yith_wcmg=true;
}
if(is_iosSlider_element.length&&is_iosSlider_element.iosSlider){
is_iosSlider=true;
}
if(is_flexslider_element.length&&is_flexslider_element.flexslider){
is_flexslider=true;
}
if(is_easyzoom_element.length&&is_easyzoom_element.filter('.images .easyzoom.first').data('easyZoom')){
is_easyzoom_element=is_easyzoom_element.filter('.images .easyzoom.first').data('easyZoom');
is_easyzoom=true;
}
if(! is_easyzoom){
is_easyzoom_flatsome_element=product_element.find('.images .has-image-zoom .slide');
if(is_easyzoom_flatsome_element.length&&is_easyzoom_flatsome_element.filter('.images .has-image-zoom .slide.first').data('easyZoom')){
is_easyzoom_flatsome_element=is_easyzoom_flatsome_element.filter('.images .has-image-zoom .slide.first').data('easyZoom');
is_easyzoom_flatsome=true;
}}
if(document.readyState==='complete'){
setTimeout(function(){
if(is_easyzoom_element.length&&is_easyzoom_element.data('easyZoom')){
is_easyzoom_element=is_easyzoom_element.data('easyZoom');
is_easyzoom=true;
}
if(is_easyzoom_flatsome_element.length&&is_easyzoom_flatsome_element.data('easyZoom')){
is_easyzoom_flatsome_element=is_easyzoom_flatsome_element.data('easyZoom');
is_easyzoom_flatsome=true;
}}, 150);
}else{
jWindow.on('load', function(){
setTimeout(function(){
if(is_easyzoom_element.length&&is_easyzoom_element.data('easyZoom')){
is_easyzoom_element=is_easyzoom_element.data('easyZoom');
is_easyzoom=true;
}
if(is_easyzoom_flatsome_element.length&&is_easyzoom_flatsome_element.data('easyZoom')){
is_easyzoom_flatsome_element=is_easyzoom_flatsome_element.data('easyZoom');
is_easyzoom_flatsome=true;
}}, 150);
});
}
if(is_wc27_gallery_element.length&&is_wc27_gallery_element.data('flexslider')){
is_wc27_gallery=true;
if(typeof $.fn.zoom==='function'&&wc_single_product_params&&wc_single_product_params.zoom_enabled){
zoom_target_temp=img.closest('.woocommerce-product-gallery__image');
if(zoom_target_temp.length > 0&&img.width() > $('.woocommerce-product-gallery').width()){
wc27_zoom_target=zoom_target_temp;
img.data.wc27_zoom_target=wc27_zoom_target;
}}
}
if(! is_wc27_gallery&&is_zoom_enabled){
zoom_images=product_element.find('.woocommerce-product-gallery__image');
}
gallery={
is_yith_wcmg: {
type: 'yith',
enabled: is_yith_wcmg,
element: yith_wcmg,
yith_wcmg_zoom: yith_wcmg_zoom,
_yith_wcmg_default_zoom: _yith_wcmg_default_zoom,
yith_wcmg_default_image: yith_wcmg_default_image
},
is_iosSlider: {
type: 'iosslider',
enabled: is_iosSlider,
element: is_iosSlider_element
},
is_flexslider: {
type: 'flexslider',
enabled: is_flexslider,
element: is_flexslider_element
},
is_elevateZoom: {
type: 'elevatezoom',
enabled: is_elevateZoom,
element: is_elevateZoom_obj
},
is_easyzoom: {
type: 'easyzoom',
enabled: is_easyzoom,
element: is_easyzoom_element
},
is_easyzoom_flatsome: {
type: 'easyzoom-flatsome',
enabled: is_easyzoom_flatsome,
element: is_easyzoom_flatsome_element
},
is_wc27_gallery: {
type: 'woocommerce',
enabled: is_wc27_gallery,
element: is_wc27_gallery_element
},
is_zoom_enabled: {
type: 'zoom',
enabled: ! is_wc27_gallery&&is_zoom_enabled,
element: zoom_images
}};
return gallery;
}
function tm_product_image_self(epoObject){
var this_epo_container=epoObject.is_associated ? epoObject.this_epo_container:epoObject.this_epo_container.not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector);
var variationsForm=epoObject.variations_form;
var main_product=epoObject.main_product;
var $form=epoObject.form;
var img;
var gallery_type;
var product_element=get_product_element(epoObject);
var last_active_field=[];
var t;
var el;
var el_current;
var imp;
var selector;
var data;
var eventNamePrefix=epoObject.is_associated ? 'tc_':'';
var main_tc_product_image_store;
img=get_main_product_image(epoObject, product_element);
gallery_type=get_gallery_type(epoObject, img, product_element);
if($(img).length > 0){
$form.on(eventNamePrefix + 'reset_image.tcpi', function(){
setTimeout(function(){
if(TMEPOJS.tm_epo_global_image_recalculate==='yes'){
img=get_main_product_image(epoObject, product_element);
$.tc_product_image_store=main_tc_product_image_store;
}
$.tc_product_image=$.tc_replace_object_values($.tc_product_image, $.tc_product_image_store);
last_active_field=[];
$(this_epo_container.find('.tm-product-image:checked,select.tm-product-image'))
.add(variationsForm.find('.tm-epo-variation-section').first().find('.tm-product-image:checked,select.tm-product-image'))
.each(function(){
t=$(this);
if(field_is_active(t)&&t.val()!==''){
last_active_field.push(t);
}});
if(last_active_field.length){
last_active_field[ last_active_field.length - 1 ].trigger('tm_trigger_product_image');
}else{
$.tc_product_image_store=$.tc_populate_store(img, product_element);
}}, window.tc_epo_product_image_change_delay||0);
});
$form.on(eventNamePrefix + 'found_variation.tcpi', function(){
setTimeout(function(){
if(TMEPOJS.tm_epo_global_image_recalculate==='yes'){
img=get_main_product_image(epoObject, product_element);
}
reset_saved_image(img, product_element);
last_active_field=[];
$(this_epo_container.find('.tm-product-image:checked,select.tm-product-image'))
.add(variationsForm.find('.tm-epo-variation-section').first().find('.tm-product-image:checked,select.tm-product-image'))
.each(function(){
t=$(this);
if(field_is_active(t)&&t.val()!==''){
last_active_field.push(t);
}});
if(last_active_field.length){
repopulate_backup_image_atts(img, product_element);
last_active_field[ last_active_field.length - 1 ].trigger('tm_trigger_product_image');
}}, window.tc_epo_product_image_change_delay||0);
});
$.tc_product_image_store=$.tc_maybe_copy_object_values_from_img($.tc_product_image_store, img, product_element);
main_tc_product_image_store=$.epoAPI.util.deepCopyArray($.tc_product_image_store);
main_product.off('tm_change_product_image').on('tm_change_product_image', function(evt, event_data){
evt.stopImmediatePropagation();
el=event_data.element;
el_current=event_data.element_current;
if(el&&el_current){
imp=el.data('imagep');
selector='';
if(imp!==''){
selector='imagep';
}else if(el.data('changes-product-image')==='images'){
selector='image';
}
data=event_data.element_current.data('image-variations');
if(data){
data=data[ selector ];
}
if(data===undefined){
return;
}
last_active_field=[];
$(this_epo_container.find('.tm-product-image:checked,select.tm-product-image'))
.add(variationsForm.find('.tm-epo-variation-section').first().find('.tm-product-image:checked,select.tm-product-image'))
.each(function(){
t=$(this);
if(t.is('option')){
t=t.closest('select');
}
if(field_is_active(t)&&t.val()!==''){
last_active_field.push(t);
}});
if(last_active_field.length){
if(! last_active_field[ last_active_field.length - 1 ].is(el)){
return;
}}
setTimeout(function(){
if(TMEPOJS.tm_epo_global_image_recalculate==='yes'){
img=get_main_product_image(epoObject, product_element);
}
image_update(data, img, product_element);
gallery_compatibility_actions(gallery_type, img, data.image_link, false, event_data, $form, product_element);
}, window.tc_epo_product_image_change_delay||0);
}});
main_product.off('tm_restore_product_image').on('tm_restore_product_image', function(evt, event_data){
evt.stopImmediatePropagation();
el=event_data.element;
last_active_field=[];
if(el){
$(this_epo_container.find('.tm-product-image:checked,select.tm-product-image'))
.add(variationsForm.find('.tm-epo-variation-section').first().find('.tm-product-image:checked,select.tm-product-image'))
.each(function(){
t=$(this);
if(field_is_active(t)&&t.val()!==''){
last_active_field.push(t);
}});
if(last_active_field.length){
if(! last_active_field[ last_active_field.length - 1 ].is(el)){
last_active_field[ last_active_field.length - 1 ].trigger('tm_trigger_product_image');
return;
}}
}
image_update(false, img, product_element);
gallery_compatibility_actions(gallery_type, false, img.attr('src'), false, event_data, $form, product_element);
});
last_active_field=[];
$(this_epo_container.find('.tm-product-image:checked,select.tm-product-image'))
.add(variationsForm.find('.tm-epo-variation-section').first().find('.tm-product-image:checked,select.tm-product-image'))
.each(function(){
t=$(this);
if(field_is_active(t)&&t.val()!==''){
last_active_field.push(t);
}});
if(last_active_field.length){
last_active_field[ last_active_field.length - 1 ].trigger('tm_trigger_product_image');
}}
jWindow.trigger('tm_product_image_loaded');
}
function tm_product_image_inline(epoObject){
var this_epo_container=epoObject.is_associated ? epoObject.this_epo_container:epoObject.this_epo_container.not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector);
var main_product=epoObject.main_product;
var product_id=epoObject.product_id;
var $form=epoObject.form;
var img;
var product_element=get_product_element(epoObject);
var gallery_type;
var a;
var img_src_original;
var img_width;
var img_height;
var last_active_field=[];
var t;
img=get_main_product_image(epoObject, product_element);
gallery_type=get_gallery_type(epoObject, img, product_element);
if($(img).length > 0){
img.data('tm-current-image', false);
a=img.closest('a');
img_src_original=img.attr('src');
img_width=img.width();
img_height=img.height();
main_product.off('tm_change_product_image').on('tm_change_product_image', function(evt, e){
var variation_element_section;
var is_variation_element;
var $this_epo_container;
var tm_last_visible_image_element;
var last_activate_field=[];
var tm_current_image_element_id;
var can_show_image;
var $main_product;
var $current_product_element;
var preload_width;
var preload_height;
var current_cloned_image;
var preloader;
var clone_image;
var preload_img;
var preload_img_onerror;
variation_element_section=e.element.closest('.cpf-section');
is_variation_element=variation_element_section.is('.tm-epo-variation-section');
$this_epo_container=e.epo_holder;
if(is_variation_element){
$this_epo_container=variation_element_section;
}
tm_last_visible_image_element=$this_epo_container.find('.tm-product-image:checked,select.tm-product-image');
last_activate_field=[];
tm_current_image_element_id=e.element.attr('id');
can_show_image=true;
$main_product=e.main_product;
$current_product_element=$main_product.closest('#product-' + product_id);
preload_width=img_width;
preload_height=img_height;
preloader=$("<div class='blockUI blockOverlay tm-preloader-img'></div>");
if($current_product_element.length <=0){
$current_product_element=$main_product.closest('.post-' + product_id);
}
current_cloned_image=$current_product_element.find('#' + tm_current_image_element_id + '_tmimage');
if(current_cloned_image.length===0){
current_cloned_image=img;
}
preload_img_onerror=function(){
preloader.remove();
$form.tc_image_update(false);
img.data('tm-current-image', false);
$current_product_element.find('.tm-clone-product-image').hide();
img.show();
};
if(e.src===current_cloned_image.attr('src')&&current_cloned_image.is(':visible')){
return;
}
if(e.src===false){
preload_img_onerror();
return;
}
preloader.css({
width: preload_width,
height: preload_height
});
tm_last_visible_image_element.each(function(){
t=$(this);
if(field_is_active(t) &&
has_active_changes_product_image(t) &&
tm_check_field_match({
element: t.closest('.cpf-element'),
operator: 'isnotempty',
value: ''
})
){
last_activate_field.push(t);
}});
if(last_activate_field.length){
tm_last_visible_image_element=last_activate_field[ last_activate_field.length - 1 ];
}
if(tm_last_visible_image_element.attr('id')!==e.element.attr('id')){
can_show_image=false;
}
clone_image=img.tcClone();
preload_img=new Image();
clone_image.removeAttr('data-o_src').removeAttr('data-o_title').removeAttr('data-o_alt').removeAttr('data-o_srcset').removeAttr('data-o_sizes').removeAttr('srcset').removeAttr('sizes');
if(can_show_image){
img.before(preloader);
}
gallery_type.is_yith_wcmg.yith_wcmg_default_zoom=gallery_type.is_yith_wcmg.element.find('.yith_magnifier_zoom').first().attr('href');
gallery_type.is_yith_wcmg.yith_wcmg_default_image=gallery_type.is_yith_wcmg.element.find('.yith_magnifier_zoom img').first().attr('src');
preload_img.onerror=function(){
preload_img_onerror();
};
preload_img.onload=function(){
if('naturalHeight' in this){
if(this.naturalHeight + this.naturalWidth===0){
this.onerror();
return;
}}else if(this.width + this.height===0){
this.onerror();
return;
}
$current_product_element.find('#' + tm_current_image_element_id + '_tmimage').remove();
$current_product_element.find('.tm-clone-product-image').hide();
clone_image.prop('src', preload_img.src).hide();
img.hide().after(clone_image);
clone_image.css('opacity', 0).show();
gallery_compatibility_actions(gallery_type, clone_image, preload_img.src);
preloader.animate({
opacity: 0
},
750,
'easeOutExpo',
function(){
preloader.remove();
}
);
clone_image.animate({
opacity: 1
},
window.tc_epo_image_animation_delay||1500,
'easeOutExpo',
function(){}
);
jWindow.trigger('tm_change_product_image_loaded', {
src: e.src,
element: e.element,
main_product: e.main_product,
epo_holder: e.epo_holder
});
};
clone_image
.attr('id', tm_current_image_element_id + '_tmimage')
.addClass('tm-clone-product-image')
.hide();
if(clone_image.attr('src-orig')){
clone_image.attr('src-orig', e.src);
}
if(can_show_image){
preload_img.src=e.src;
$form.tc_image_update(e.element, clone_image);
img.data('tm-current-image', tm_current_image_element_id);
jWindow.trigger('tm_change_product_image_show', {
src: e.src,
element: e.element,
main_product: e.main_product,
epo_holder: e.epo_holder
});
}else{
clone_image.prop('src', e.src).hide();
img.after(clone_image);
}
jWindow.trigger('tm_change_product_image_end', {
src: e.src,
element: e.element,
main_product: e.main_product,
epo_holder: e.epo_holder
});
});
main_product.off('tm_restore_product_image').on('tm_restore_product_image', function(evt, e){
var tm_current_image_element_id;
var $main_product;
var $current_product_element;
var variation_element_section;
var is_variation_element;
var current_element;
var current_image_replacement;
var found;
var is_it_visible;
var len;
var el_to_check;
var imgSrc;
var $this_epo_container;
var i;
jWindow.trigger('tm_restore_product_image_pre', {
element: e.element,
main_product: e.main_product,
epo_holder: e.epo_holder
});
tm_current_image_element_id=e.element.attr('id');
$main_product=e.main_product;
$current_product_element=$main_product.closest('#product-' + product_id);
variation_element_section=e.element.closest('.cpf-section');
is_variation_element=variation_element_section.is('.tm-epo-variation-section');
found=false;
imgSrc=img_src_original;
$this_epo_container=e.epo_holder;
if(is_variation_element){
$this_epo_container=variation_element_section;
}
if($current_product_element.length <=0){
$current_product_element=$main_product.closest('.post-' + product_id);
}
is_it_visible=$current_product_element.find('#' + tm_current_image_element_id + '_tmimage').is(':visible');
$current_product_element.find('#' + tm_current_image_element_id + '_tmimage').remove();
if($current_product_element.find('.tm-clone-product-image').length===0){
img.show();
img.data('tm-current-image', false);
$form.tc_image_update(false);
}else{
if(! is_it_visible){
jWindow.trigger('tm_restore_product_image_loaded_exit', {
element: e.element,
main_product: e.main_product,
epo_holder: e.epo_holder
});
return;
}
len=$current_product_element.find('.tm-clone-product-image').length;
tm_current_image_element_id=img.data('tm-current-image');
for(i=len - 1; i >=0; i -=1){
current_image_replacement=$current_product_element.find('.tm-clone-product-image').eq(i);
current_element=current_image_replacement.attr('id').replace('_tmimage', '');
el_to_check=$this_epo_container.find("[id='" + current_element + "']");
if(el_to_check.is(':checked')&&el_to_check.closest('.cpf-element').is(':visible')){
$current_product_element.find('.tm-clone-product-image').eq(i).show();
a.attr('href', $current_product_element.find('.tm-clone-product-image').eq(i).prop('src'));
img.data('tm-current-image', current_element);
found=true;
break;
}else{
$current_product_element.find('.tm-clone-product-image').eq(i).hide();
}}
if(! found){
img.show();
img.data('tm-current-image', false);
$form.tc_image_update(false);
}else{
$current_product_element.find('#' + tm_current_image_element_id + '_tmimage').remove();
}}
if(found){
imgSrc=current_image_replacement.attr('src');
}
gallery_compatibility_actions(gallery_type, false, imgSrc, $current_product_element.find('.tm-clone-product-image').filter(':visible').length);
jWindow.trigger('tm_restore_product_image_loaded', {
element: e.element,
main_product: e.main_product,
epo_holder: e.epo_holder
});
});
main_product.off('tm_attempt_product_image').on('tm_attempt_product_image', function(evt, e){
var $main_product;
var $current_product_element;
var variation_element_section;
var is_variation_element;
var $this_epo_container;
var tm_last_visible_image_element;
var last_activate_field;
var tm_last_visible_image_element_id;
var current_image_replacement;
var current_element;
var found;
var tm_current_image_element_id;
var len;
var imgSrc;
var el_to_check;
var tmcie_id;
var i;
$main_product=e.main_product;
$current_product_element=$main_product.closest('#product-' + product_id);
if(e.element){
variation_element_section=e.element.closest('.cpf-section');
}else{
variation_element_section=$($main_product.find('.tm-epo-variation-section').first(), e.epo_holder);
}
is_variation_element=variation_element_section.is('.tm-epo-variation-section');
$this_epo_container=e.epo_holder;
if(is_variation_element){
$this_epo_container=variation_element_section;
}
tm_last_visible_image_element=$this_epo_container.find('.tm-product-image:checked,select.tm-product-image');
last_activate_field=[];
tm_last_visible_image_element_id='';
found=false;
tm_current_image_element_id=img.data('tm-current-image');
imgSrc=img_src_original;
if($current_product_element.length <=0){
$current_product_element=$main_product.closest('.post-' + product_id);
}
$this_epo_container=$main_product.find('.tm-epo-variation-section').first().add(e.epo_holder);
tm_last_visible_image_element=$this_epo_container.find('.tm-product-image:checked,select.tm-product-image');
tm_last_visible_image_element.each(function(){
t=$(this);
if(field_is_active(t) &&
has_active_changes_product_image(t) &&
tm_check_field_match({
element: t.closest('.cpf-element'),
operator: 'isnotempty',
value: ''
})
){
last_activate_field.push(t);
}});
if(last_activate_field.length){
tm_last_visible_image_element=last_activate_field[ last_activate_field.length - 1 ];
tm_last_visible_image_element_id=tm_last_visible_image_element.attr('id');
}
if(last_activate_field.length&&tm_last_visible_image_element.length&&(! tm_current_image_element_id||tm_last_visible_image_element_id!==tm_current_image_element_id)){
tm_last_visible_image_element.last().trigger('tm_trigger_product_image');
return;
}
tmcie_id=$this_epo_container.find("[id='" + tm_current_image_element_id + "']").closest('.cpf-element');
if(! tm_current_image_element_id||(tmcie_id.data('isactive')!==false&&tmcie_id.closest('.cpf-section').data('isactive')!==false)){
return;
}
$current_product_element.find('#' + tm_current_image_element_id + '_tmimage').remove();
len=$current_product_element.find('.tm-clone-product-image').length;
if(len===0){
img.show();
img.data('tm-current-image', false);
$form.tc_image_update(false);
}else{
for(i=len - 1; i >=0; i -=1){
current_image_replacement=$current_product_element.find('.tm-clone-product-image').eq(i);
current_element=current_image_replacement.attr('id').replace('_tmimage', '');
el_to_check=$this_epo_container.find("[id='" + current_element + "']");
if(el_to_check.is(':checked')&&el_to_check.closest('.cpf-element').is(':visible')){
$current_product_element.find('.tm-clone-product-image').eq(i).show();
a.attr('href', $current_product_element.find('.tm-clone-product-image').eq(i).prop('src'));
img.data('tm-current-image', current_element);
found=true;
break;
}else{
$current_product_element.find('.tm-clone-product-image').eq(i).hide();
}}
if(! found){
img.show();
img.data('tm-current-image', false);
$form.tc_image_update(false);
}}
if(found){
imgSrc=current_image_replacement.attr('src');
}
gallery_compatibility_actions(gallery_type, false, imgSrc, $current_product_element.find('.tm-clone-product-image').filter(':visible').length);
});
$(this_epo_container.find('.tm-product-image:checked,select.tm-product-image'))
.add(main_product.find('.tm-epo-variation-section').first().find('.tm-product-image:checked,select.tm-product-image'))
.each(function(){
t=$(this);
if(field_is_active(t)&&t.val()!==''){
last_active_field.push(t);
}});
if(last_active_field.length){
last_active_field[ last_active_field.length - 1 ].trigger('tm_trigger_product_image');
}}
jWindow.trigger('tm_product_image_loaded');
}
function tm_product_image(epoObject){
setTimeout(function(){
if(TMEPOJS.tm_epo_global_product_image_mode==='inline'){
tm_product_image_inline(epoObject);
}else{
tm_product_image_self(epoObject);
}}, window.tc_epo_product_image_setup_delay||0);
}
function tc_compatibility(epoObject){
jWindow.trigger('tm-epo-compatibility', {
epo: epoObject
});
}
function setRangePickers(obj){
if(! noUiSlider){
return;
}
obj.find('.tm-range-picker')
.toArray()
.forEach(function(picker){
var el=$(picker);
var $decimals=el.attr('data-step').split('.');
var $tmfid=obj.find('#' + $.epoAPI.dom.id(el.attr('data-field-id')));
var $min=parseFloat(el.attr('data-min'));
var $max=parseFloat(el.attr('data-max'));
var $start=parseFloat(el.attr('data-start'));
var $step=parseFloat(el.attr('data-step'));
var $show_picker_value=el.attr('data-show-picker-value');
var $show_label=el.closest('li').find('.tm-show-picker-value');
var $noofpips=parseFloat(el.attr('data-noofpips'));
var $pips=null;
var $tmh;
if(el.data('tc-picker-init')){
return;
}
el.data('tc-picker-init', 1);
if($decimals.length===1){
$decimals=0;
}else{
$decimals=$decimals[ 1 ].length;
}
if(! Number.isFinite($min)){
$min=0;
}
if(! Number.isFinite($max)){
$max=0;
}
if($max <=$min){
$max=parseFloat($max) + 1;
}
$start=$.epoAPI.math.unformat($start, tcAPI.localDecimalSeparator);
if(! Number.isFinite($start)){
$start=0;
}
$start=formatPrice($start, { precision: $decimals });
if(! Number.isFinite($step)){
$step=0;
}
if(! Number.isFinite($noofpips)){
$noofpips=10;
}
if($noofpips < 2){
$noofpips=2;
}
if(el.attr('data-pips')==='yes'){
$pips={
mode: 'count',
values: $noofpips,
filter: function(value, type){
value=parseFloat($.epoAPI.math.toFixed(value, $decimals));
if($step <=0){
return 0;
}
if(type===1){
if(! Number.isInteger(value)){
return 2;
}}
return type;
},
format: {
from: function(value){
return $.epoAPI.math.unformat(value, tcAPI.localInputDecimalSeparator);
},
to: function(value){
return formatPrice(value, { precision: $decimals });
}},
density: 2
};}
noUiSlider.create(el.get(0), {
direction: TMEPOJS.text_direction,
start: $start,
step: $step,
connect: 'lower',
behaviour: 'tap',
format: {
from: function(value){
return $.epoAPI.math.unformat(value, tcAPI.localDecimalSeparator);
},
to: function(value){
return formatPrice(value, { precision: $decimals });
}},
range: {
min: [ $min ],
max: [ $max ]
},
pips: $pips,
tooltips: {
from: function(value){
return $.epoAPI.math.unformat(value, tcAPI.localInputDecimalSeparator);
},
to: function(value){
return formatPrice(value, { precision: $decimals });
}}
});
$tmh=el.find('.noui-handle-lower');
el.get(0).noUiSlider.on('slide', function(){
$tmfid.trigger('change.cpf');
});
el.get(0).noUiSlider.on('update', function(values, handle){
values[ handle ]=$.epoAPI.math.unformat(values[ handle ], tcAPI.localDecimalSeparator);
handle=0;
if($show_picker_value!=='left'&&$show_picker_value!=='right'){
$tmh.attr('title',
formatPrice(values[ handle ], { precision: $decimals })
);
}
$tmfid.val(values[ handle ]).trigger('change');
if($show_picker_value!==''){
$show_label.html(formatPrice(values[ handle ], { precision: $decimals })
);
}});
if($show_picker_value!==''){
$show_label.html($start);
}
if($show_picker_value!=='left'&&$show_picker_value!=='right'){
$tmh.attr('title', $start);
el.addClass('noui-show-tooltip');
}});
}
function setRangePickersEvents(){
if(! noUiSlider||jDocument.data('setRangePickersEvents')){
return;
}
jDocument.on('click', '.tm-show-picker-value', function(){
var $this=$(this);
var li=$this.closest('.tmcp-field-wrap');
var value=li.find('.tmcp-range').val();
var edit;
var html5Slider=$this.closest('.tmcp-field-wrap').find('.tm-range-picker');
$this.addClass('tc-hidden').after($('<input type="number" class="tm-show-picker-value-edit">'));
edit=li.find('.tm-show-picker-value-edit');
edit.focus().val(value).wrap('<div class="tm-show-picker-value-edit-wrap"></div>');
edit.attr('step', html5Slider.attr('data-step'));
edit.attr('min', html5Slider.attr('data-min'));
edit.attr('max', html5Slider.attr('data-max'));
jDocument.data('range-picker-edit', li.find('.tm-show-picker-value-edit'));
});
jDocument.on('change input', '.tm-show-picker-value-edit', function(){
var $this=$(this);
var html5Slider=$this.closest('.tmcp-field-wrap').find('.tm-range-picker');
var $decimals=html5Slider.attr('data-step').split('.');
var value=$this.val();
if($decimals.length===1){
$decimals=0;
}else{
$decimals=$decimals[ 1 ].length;
}
html5Slider.get(0).noUiSlider.set([ formatPrice(value, { precision: $decimals }), null ]);
});
jDocument.on('keydown', '.tm-show-picker-value-edit', function(event){
var key;
key=event.which;
if(key===13){
event.preventDefault();
}});
jDocument.on('click', function(event){
var $this;
if(! jDocument.data('range-picker-edit')||$(event.target).is('.tm-show-picker-value')){
return;
}
if($(event.target).closest('.tm-show-picker-value-edit-wrap').length===0){
$this=jDocument.data('range-picker-edit');
$this.closest('.tmcp-field-wrap').find('.tm-show-picker-value').data('has-edit', 0).removeClass('tc-hidden');
$this.closest('.tm-show-picker-value-edit-wrap').remove();
jDocument.removeData('range-picker-edit');
}});
jDocument.data('setRangePickersEvents', 1);
}
function validate_date_with_options(date, inputElement){
var input=$(inputElement);
var inst=$.tm_datepicker._getInst(input[ 0 ]);
var enabled_only_dates=input.data('tc-enabled_only_dates');
var disabled_weekdays=input.data('tc-disabled_weekdays');
var disabled_months=input.data('tc-disabled_months');
var disabled_dates=input.data('tc-disabled_dates');
var format=input.data('tc-format');
var day=date.getDay();
var month=date.getDay() + 1;
var string;
if(! $.tm_datepicker._isInRange(inst, date)){
return false;
}
if(enabled_only_dates!==''){
string=$.tm_datepicker.formatDate(format, date);
return enabled_only_dates.indexOf(string)!==-1;
}
if(disabled_weekdays.indexOf(day.toString())!==-1){
return false;
}
if(disabled_months.indexOf(month.toString())!==-1){
return false;
}
if(disabled_dates!==''){
string=$.tm_datepicker.formatDate(format, date);
return disabled_dates.indexOf(string)===-1;
}
return true;
}
function correctDate(days){
var sign, testDate, count, added, noOfDaysToAdd;
if(days.toString().isNumeric()){
sign=days===0 ? days:(days > 0 ? 1:-1);
if(sign!==0){
testDate=new Date();
count=1;
added=false;
noOfDaysToAdd=Math.abs(days);
while(count <=noOfDaysToAdd){
if(added===false){
added=0;
}
testDate.setDate(testDate.getDate() +(1 * sign));
added++;
if(testDate.getDay()!==0&&testDate.getDay()!==6){
count++;
}}
if(added!==false){
days=added * sign;
}}
}
return days;
}
function tm_set_datepicker(obj){
var inputIds;
var elem;
var timepickerSelector='.tm-epo-timepicker';
if(! $.tm_datepicker){
return;
}
inputIds=$('input')
.map(function(){
return this.id;
})
.get()
.join(' ');
elem=document.createElement('input');
elem.setAttribute('type', 'date');
if(elem.type==='text'){
timepickerSelector='.tm-epo-system-timepicker';
}
obj.find(timepickerSelector)
.toArray()
.forEach(function(el){
var field=$(el);
var _mintime=null;
var _maxtime=null;
var format=field.attr('data-time-format').trim();
var date_theme=field.attr('data-time-theme').trim();
var date_theme_size=field.attr('data-time-theme-size').trim();
var date_theme_position=field.attr('data-time-theme-position').trim();
var data_translation_hour=field.attr('data-tranlation-hour').trim();
var data_translation_minute=field.attr('data-tranlation-minute').trim();
var data_translation_second=field.attr('data-tranlation-second').trim();
field.attr('type', 'text');
if(field.attr('data-min-time').trim()!==''){
_mintime=field.attr('data-min-time').trim();
}
if(field.attr('data-max-time').trim()!==''){
_maxtime=field.attr('data-max-time').trim();
}
if(field.attr('data-custom-time-format').trim()!==''){
format=field.attr('data-custom-time-format').trim();
}
if(! data_translation_hour){
data_translation_hour=TMEPOJS.hourText;
}
if(! data_translation_minute){
data_translation_minute=TMEPOJS.minuteText;
}
if(! data_translation_second){
data_translation_second=TMEPOJS.secondText;
}
field.tm_timepicker(Object.assign({
isRTL: TMEPOJS.isRTL,
hourText: data_translation_hour,
minuteText: data_translation_minute,
secondText: data_translation_second,
timeFormat: format,
minTime: _mintime,
maxTime: _maxtime,
closeText: TMEPOJS.closeText,
showOn: 'both',
buttonText: '',
beforeShow: function(input, inst){
$(inst.dpDiv)
.removeClass(inputIds)
.removeClass('tm-ui-skin-epo tm-ui-skin-epo-black tm-datepicker-medium tm-datepicker-small tm-datepicker-large tm-datepicker-normal tm-datepicker-top tm-datepicker-bottom')
.addClass(this.id + ' tm-bsbb-all tm-ui-skin-' + date_theme + ' tm-timepicker tm-datepicker tm-datepicker-' + date_theme_position + ' tm-datepicker-' + date_theme_size)
.appendTo('body');
jDocument.off('click', '.tm-ui-dp-overlay').on('click', '.tm-ui-dp-overlay', function(){
field.tm_timepicker('hide');
});
jBody.addClass('tm-static');
field.prop('readonly', true);
jWindow.trigger({
type: 'tm-timepicker-beforeShow',
input: input,
inst: inst
});
},
onClose: function(){
jBody.removeClass('tm-static');
field.prop('readonly', false);
field.trigger('change');
}}, window.tmTimepickerSettings||window.timepicker_settings||{}));
$('#ui-tm-datepicker-div').hide();
});
obj.find('.tm-epo-datepicker')
.toArray()
.forEach(function(el){
var field=$(el);
var startDate=parseInt(field.attr('data-start-year').trim(), 10);
var endDate=parseInt(field.attr('data-end-year').trim(), 10);
var minDate=field.attr('data-min-date').trim();
var maxDate=field.attr('data-max-date').trim();
var disabled_dates=field.attr('data-disabled-dates').trim();
var enabled_only_dates=field.attr('data-enabled-only-dates').trim();
var exlude_disabled=field.attr('data-exlude-disabled').trim();
var disabled_weekdays=field.attr('data-disabled-weekdays').trim().split(',');
var disabled_months=field.attr('data-disabled-months').trim().split(',');
var format=field.attr('data-date-format').trim();
var show=field.attr('data-date-showon').trim();
var default_date=field.attr('data-date-defaultdate').trim();
var date_theme=field.attr('data-date-theme').trim();
var date_theme_size=field.attr('data-date-theme-size').trim();
var date_theme_position=field.attr('data-date-theme-position').trim();
var $split;
var $index;
var $split2;
var $index2;
if(disabled_dates!==''){
$split=disabled_dates.split(',');
$index=disabled_dates.indexOf(',');
if($index!==-1&&$split.length > 0){
disabled_dates=$split;
}}
if(enabled_only_dates!==''){
$split2=enabled_only_dates.split(',');
$index2=enabled_only_dates.indexOf(',');
if($index2!==-1&&$split2.length > 0){
enabled_only_dates=$split2;
}}
if(minDate===''){
if(startDate===''){
minDate=null;
}else{
minDate=new Date(startDate, 1 - 1, 1);
}}else if(exlude_disabled){
minDate=correctDate(minDate);
}
if(maxDate===''){
if(endDate===''){
maxDate=null;
}else{
maxDate=new Date(endDate, 12 - 1, 31);
}}else if(exlude_disabled){
maxDate=correctDate(maxDate);
}
field.data('tc-enabled_only_dates', enabled_only_dates);
field.data('tc-disabled_weekdays', disabled_weekdays);
field.data('tc-disabled_months', disabled_months);
field.data('tc-disabled_dates', disabled_dates);
field.data('tc-format', format);
field.tm_datepicker(Object.assign({
monthNames: TMEPOJS.monthNames,
monthNamesShort: TMEPOJS.monthNamesShort,
dayNames: TMEPOJS.dayNames,
dayNamesShort: TMEPOJS.dayNamesShort,
dayNamesMin: TMEPOJS.dayNamesMin,
isRTL: TMEPOJS.isRTL,
showOtherMonths: true,
selectOtherMonths: true,
showOn: show,
defaultDate: default_date,
buttonText: '',
showButtonPanel: true,
firstDay: TMEPOJS.first_day,
closeText: TMEPOJS.closeText,
currentText: TMEPOJS.currentText,
dateFormat: format,
minDate: minDate,
maxDate: maxDate,
onSelect: function(){
var input=$(this);
var id='#' + $.epoAPI.dom.id(input.attr('id'));
var date=input.tm_datepicker('getDate');
var day='';
var month='';
var year='';
var day_field=obj.find(id + '_day');
var month_field=obj.find(id + '_month');
var year_field=obj.find(id + '_year');
var string;
var ld;
if(date){
day=date.getDate();
month=date.getMonth() + 1;
year=date.getFullYear();
string=$.tm_datepicker.formatDate(format, date);
if(disabled_months.indexOf(month.toString())!==-1 ||
disabled_weekdays.indexOf(date.getDay().toString())!==-1 ||
disabled_dates.indexOf(string)!==-1 ||
(enabled_only_dates!==''&&enabled_only_dates.indexOf(string)===-1)
){
ld=input.data('tm-last-date');
if(input.data('tm-last-date')){
ld=input.data('tm-last-date');
}else{
ld='';
}
input.val(ld);
input.tm_datepicker('setDate', ld);
if(ld){
date=input.tm_datepicker('getDate');
day=date.getDate();
month=date.getMonth() + 1;
year=date.getFullYear();
}else{
day='';
month='';
year='';
}}
}
day_field.val(day);
month_field.val(month);
year_field.val(year);
input.data('tm-last-date', input.val());
},
beforeShow: function(input, inst){
$(inst.dpDiv)
.removeClass(inputIds)
.removeClass('tm-datepicker-normal tm-datepicker-top tm-datepicker-bottom')
.addClass(this.id + ' tm-bsbb-all tm-ui-skin-' + date_theme + ' tm-datepicker tm-datepicker-' + date_theme_position + ' tm-datepicker-' + date_theme_size)
.appendTo('body');
jDocument.off('click', '.tm-ui-dp-overlay').on('click', '.tm-ui-dp-overlay', function(){
field.tm_datepicker('hide');
});
jDocument.off('click', '.ui-tm-datepicker-current').on('click', '.ui-tm-datepicker-current', function(){
var tempDate=new Date(),
today=$.tm_datepicker._daylightSavingAdjust(new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate()));
var day=today.getDay();
var month=today.getMonth() + 1;
var id='#' + inst.id.replace(/\\\\/g, '\\');
var check=false;
var string;
var date=field.tm_datepicker('getDate');
if(enabled_only_dates!==''){
string=$.tm_datepicker.formatDate(format, date);
check=enabled_only_dates.indexOf(string)!==-1;
}else if(disabled_months.indexOf(month.toString())!==-1||disabled_weekdays.indexOf(day.toString())!==-1){
check=false;
}else{
if(disabled_dates!==''){
string=$.tm_datepicker.formatDate(format, date);
return [ disabled_dates.indexOf(string)===-1, '' ];
}
check=true;
}
if(check){
$.tm_datepicker._setDate(inst, today);
$.tm_datepicker._gotoToday(id);
}});
jBody.addClass('tm-static');
field.prop('readonly', true);
jWindow.trigger({
type: 'tm-datepicker-beforeShow',
input: input,
inst: inst
});
},
onClose: function(){
jBody.removeClass('tm-static');
field.prop('readonly', false);
field.trigger('change');
},
beforeShowDay: function(date){
var day=date.getDay();
var month=date.getMonth() + 1;
var string;
if(enabled_only_dates!==''){
string=$.tm_datepicker.formatDate(format, date);
return [ enabled_only_dates.indexOf(string)!==-1, '' ];
}
if(disabled_months.indexOf(month.toString())!==-1||disabled_weekdays.indexOf(day.toString())!==-1){
return [ false, '' ];
}
if(disabled_dates!==''){
string=$.tm_datepicker.formatDate(format, date);
return [ disabled_dates.indexOf(string)===-1, '' ];
}
return [ true, '' ];
}}, window.tmDatepickerSettings||{}));
$('#ui-tm-datepicker-div').hide();
});
obj.find('.tmcp-date-select')
.on('change.cpf', function(){
var id='#' + $.epoAPI.dom.id($(this).attr('data-tm-date'));
var input=obj.find(id);
var format=input.attr('data-date-format');
var day=obj.find(id + '_day').val();
var month=obj.find(id + '_month').val();
var year=obj.find(id + '_year').val();
var dateFormat=$.tm_datepicker.formatDate(format, new Date(year, parseInt(month, 10) - 1, day));
if(day > 0&&month > 0&&year > 0){
input.tm_datepicker('setDate', dateFormat);
input.trigger('change');
}else{
input.val('');
input.trigger('change.cpf');
}})
.on('focus.cpf', function(){
var id='#' + $.epoAPI.dom.id($(this).attr('data-tm-date'));
var input=obj.find(id);
var day_select=obj.find(id + '_day');
var month_select=obj.find(id + '_month');
var year_select=obj.find(id + '_year');
var day=day_select.val();
var month=month_select.val();
var year=year_select.val();
var _select=$(this);
if(( year!==''&&month!==''&&day!=='')||(year!==''&&month!==''&&day==='')||(day!==''&&year!==''&&month==='')||(day!==''&&month!==''&&year==='')){
_select
.find('option')
.toArray()
.forEach(function(element){
var option=$(element);
var val=option.val();
var date_string=year + '-' + month + '-' + day;
var d;
if(_select.is('.tmcp-date-day')){
if(year===''||month===''){
return;
}
date_string=year + '-' + month + '-' + val;
}else if(_select.is('.tmcp-date-month')){
if(year===''||day===''){
return;
}
date_string=year + '-' + val + '-' + day;
}else if(_select.is('.tmcp-date-year')){
if(day===''||month===''){
return;
}
date_string=val + '-' + month + '-' + day;
}
if(val!==''){
try {
d=$.tm_datepicker.parseDate('yy-mm-dd', date_string);
if(d){
if(validate_date_with_options(d, input)){
option.prop('disabled', false);
}else{
option.prop('disabled', true);
}}
} catch(err){
window.console.log(err);
option.prop('disabled', true);
errorObject=err;
}}
});
}else{
day_select.find('option').prop('disabled', false);
month_select.find('option').prop('disabled', false);
year_select.find('option').prop('disabled', false);
}});
jWindow.on('resizestart', function(){
var activeElement=$(document.activeElement);
if(activeElement.is('.hasDatepicker')){
activeElement.data('resizestarted', true);
if($(window).width() < 768){
activeElement.data('resizewidth', true);
return;
}
activeElement.tm_datepicker('hide');
}});
jWindow.on('resizestop', function(){
var activeElement=$(document.activeElement);
if(activeElement.is('.hasDatepicker')&&activeElement.data('resizestarted')){
if(activeElement.data('resizewidth')){
activeElement.tm_datepicker('hide');
}
activeElement.tm_datepicker('show');
}
activeElement.data('resizestarted', false);
activeElement.data('resizewidth', false);
});
}
function apply_submit_events(epoObject){
var epoEventId=epoObject.epoEventId;
var main_product=epoObject.main_product;
var type;
var form_is_submit = ! $.tcepo.formSubmitEvents[ epoEventId ].some(function(form_event){
return typeof form_event&&(typeof form_event.trigger==='function'||false)&&! form_event.trigger();
});
$.tcepo.formSubmitEvents[ epoEventId ].forEach(function(form_event){
type=typeof form_event;
if(type==='object'){
if(form_is_submit){
form_event.on_true();
}else{
form_event.on_false();
}}
});
if(! form_is_submit){
setTimeout(function(){
main_product.find(tcAPI.addToCartButtonSelector).first().removeClass('disabled').removeClass('loading').prop('disabled', false).removeClass('fpd-disabled');
}, 100);
}
jWindow.trigger('tm-apply-submit-events', {
epo: {
form_is_submit: form_is_submit
}});
return form_is_submit;
}
function tm_apply_validation(epoObject){
var form=epoObject.form;
var this_epo_container=epoObject.this_epo_container;
var main_product=epoObject.main_product;
var epoEventId=epoObject.epoEventId;
var validation_rules;
var has_rules;
if(TMEPOJS.tm_epo_global_enable_validation==='yes'){
validation_rules={};
this_epo_container
.find('.tmcp-ul-wrap')
.toArray()
.forEach(function(tmcpulwrap){
var field;
var field_name;
var subFieldName;
var subRule;
var productField;
tmcpulwrap=$(tmcpulwrap);
has_rules=tmcpulwrap.data('tm-validation');
if(has_rules&&$.tmType(has_rules)==='object'){
field=tmcpulwrap.find('.tm-epo-field');
field_name=field.first().attr('name');
if(tmcpulwrap.is('.tm-extra-product-options-radio.tm-element-ul-radio')){
field_name=field.last().attr('name');
validation_rules[ field_name ]=has_rules;
}else if(tmcpulwrap.is('.tm-extra-product-options-checkbox.tm-element-ul-checkbox')){
field.each(function(f, fname){
if('required' in has_rules){
has_rules.required=function(elem){
var len=tmcpulwrap.find('input.tm-epo-field.tmcp-checkbox:checked').length;
if(len===0){
if(field.last().attr('name')===$(elem).attr('name')){
return true;
}
return false;
}
return len <=0;
};}
validation_rules[ $(fname).attr('name') ]=has_rules;
});
}else if(tmcpulwrap.is('.tm-extra-product-options-product.tm-element-ul-product')){
if(field.is(':checkbox')){
field.each(function(f, fname){
if('required' in has_rules){
productField=$(fname);
if(productField.is(':checkbox')){
has_rules.required=function(elem){
var checkedFields=tmcpulwrap.find('input.tm-epo-field.tmcp-checkbox:checked');
var len=checkedFields.length;
var qtyCheck;
if(len===0){
if(field.last().attr('name')===$(elem).attr('name')){
return true;
}
return false;
}
qtyCheck=checkedFields.map(function(){
return $(this);
}).get().some(function(element){
return element.closest('.tc-epo-element-product-holder').find('.tm-qty').first().val() <=0;
});
if(len > 0){
return qtyCheck;
}
return len <=0;
};
if(productField.attr('data-type')==='variable'){
subFieldName=productField.closest('.tc-epo-element-product-holder').find('.product-variation-id').first().attr('name');
subRule={
required: function(elem){
var element=$(elem);
var holder=element.closest('.tc-epo-element-product-holder');
var checkbox=holder.find('.tc-epo-field-product');
if(field_is_active(checkbox, true)&&checkbox.is(':checked')){
return true;
}
return false;
}};
validation_rules[ subFieldName ]=subRule;
}}
}
validation_rules[ productField.attr('name') ]=has_rules;
});
}else if(field.is(':radio')){
has_rules.product_element_radio_qty=true;
validation_rules[ field.attr('name') ]=has_rules;
subFieldName=field.closest('.tc-element-container').find('.product-variation-id').first().attr('name');
subRule={
required: function(elem){
var element=$(elem);
var holder=element.closest('.tc-element-container');
var radiobutton=holder.find('.tc-epo-field-product:checked');
if(radiobutton.length&&radiobutton.attr('data-type')==='variable'&&field_is_active(radiobutton, true)&&radiobutton.is(':checked')){
return true;
}
return false;
}};
validation_rules[ subFieldName ]=subRule;
}else if(field.is('select')){
has_rules.product_element_select_qty=true;
validation_rules[ field.attr('name') ]=has_rules;
subFieldName=field.closest('.tc-element-container').find('.product-variation-id').first().attr('name');
subRule={
required: function(elem){
var element=$(elem);
var holder=element.closest('.tc-element-container');
var select=holder.find('.tc-epo-field-product');
if(select.length&&select.children(':selected').attr('data-type')==='variable'&&field_is_active(select, true)){
return true;
}
return false;
}};
validation_rules[ subFieldName ]=subRule;
}}else{
validation_rules[ field_name ]=has_rules;
}}
});
form.removeData('tc_validator');
form.tc_validate({
focusInvalid: false,
ignore:
tcAPI.qtySelector +
",.tcdisabled,.tmcp-upload-hidden,#wc_bookings_field_duration,input.tm-qty:hidden[type='number'],input.input-text.qty,.ignore,.variations select,.tc-epo-variable-product-selector,.tm-extra-product-options-variations input,.tm-extra-product-options-variations select,input:not(.tc-extra-product-options input),select:not(.tc-extra-product-options select)",
rules: validation_rules,
errorClass: 'tm-error',
validClass: 'tm-valid',
errorElement: 'label',
errorPlacement: function(error, element){
error.addClass('tc-cell tcwidth tcwidth-100');
if(TMEPOJS.tm_epo_global_error_label_placement==='before'){
element.closest('.tc-element-container').before(error);
}else{
element.closest('.tc-element-container').after(error);
}
return false;
},
invalidHandler: function(event, validator){
jWindow.trigger('tm-invalidHandler', {
epo: {
validator: validator
}});
setTimeout(function(){
if(! main_product.find(tcAPI.addToCartButtonSelector).first().is('.disabled')){
main_product.find(tcAPI.addToCartButtonSelector).first().removeClass('loading').prop('disabled', false).removeClass('fpd-disabled');
main_product.find(tcAPI.addToCartButtonSelector).first().removeClass('disabled').removeClass('loading').prop('disabled', false).removeClass('fpd-disabled');
}}, 100);
if(validator.errorList&&validator.errorList[ 0 ]&&validator.errorList[ 0 ].element){
goto_error_item($(validator.errorList[ 0 ].element), epoEventId);
}},
submitHandler: function(){
var ajaxSuccessFunc;
if(! epoObject.is_quickview){
main_product.find(tcAPI.addToCartButtonSelector).first().addClass('disabled');
ajaxSuccessFunc=function(){
main_product.find(tcAPI.addToCartButtonSelector).first().removeClass('disabled');
jDocument.off('ajaxSuccess', ajaxSuccessFunc);
};
jDocument.on('ajaxSuccess', ajaxSuccessFunc);
}
return apply_submit_events(epoObject);
}});
form.find(tcAPI.addToCartButtonSelector).on('click', function(e){
if(! form.tc_validate().form()){
e.preventDefault();
e.stopImmediatePropagation();
}});
return true;
}
return false;
}
function tm_form_submit_event(epoObject){
var form=epoObject.form;
var epoEventId=epoObject.epoEventId;
jWindow.trigger('tm-from-submit', {
epo: epoObject,
functions: {
tm_apply_validation: tm_apply_validation,
apply_submit_events: apply_submit_events
}});
if(! tm_apply_validation(epoObject)&&$.tcepo.formSubmitEvents[ epoEventId ].length){
form.on('submit', function(){
apply_submit_events(epoObject);
});
}
jWindow.on('tc_apply_validation', function(){
return tm_apply_validation(epoObject);
});
}
function found_variation_tmepo(dataObject){
var epoHolder=dataObject.epoHolder;
var totalsHolder=dataObject.totalsHolder;
var totalsHolderContainer=dataObject.totalsHolderContainer;
var currentCart=dataObject.currentCart;
var variationForm=dataObject.variationForm;
var variation=dataObject.variation;
var variations=totalsHolder.data('variations');
var product_price;
totalsHolder.data('current_variation', variation);
if(variation&&'display_price' in variation&&! totalsHolder.data('tm-epo-is-woocs')){
product_price=variation.display_price;
totalsHolder.data('priceIsWithDiscount', '1');
totalsHolder.removeData('tcprice');
}else if(variations&&variation&&variation.variation_id&&variations[ variation.variation_id ]!==undefined){
product_price=variations[ variation.variation_id ];
totalsHolder.removeData('tcprice');
}else if(variation&&$(variation.price_html).find('.amount:last').length){
product_price=$(variation.price_html).find('.amount:last').text();
product_price=product_price.replace(TMEPOJS.currency_format_thousand_sep, '');
product_price=product_price.replace(TMEPOJS.currency_format_decimal_sep, '.');
product_price=product_price.replace(/[^0-9.]/g, '');
product_price=parseFloat(product_price);
totalsHolder.removeData('tcprice');
}
product_price=tm_set_backend_price(product_price, totalsHolder, variation);
totalsHolder.data('price', product_price);
totalsHolderContainer.find('.cpf-product-price').val(product_price);
setTimeout(function(){
epoHolder.find('select.tm-epo-field').trigger('tm-select-change-html-all-math');
}, 100);
if(! variationForm.data('tm-styled-variations')){
currentCart.trigger({
type: 'tm-epo-update'
});
}}
function fetchOptionPrices(epoObject, epoHolder, selector, total, original_total, floatingBoxData, showTotal, forced, setPriceTax, useUndiscountedPrice, mathTotal, cumulative){
var obj;
var noDpd;
var priceArray;
var priceCacheSelector=epoHolder.attr('class') + epoHolder.attr('data-uniqid') + selector + epoObject.is_associated + setPriceTax + forced + setPriceTax + useUndiscountedPrice||'none';
var total_taxed;
var original_total_taxed;
var vat_total=0;
var currentTotalsContainer;
var epoinline;
var funcTotal;
var cumulativeTotal;
if(priceCacheSelector!=='none'&&priceCache!==true&&priceCache!==false&&priceCache[ priceCacheSelector ]!==undefined){
return priceCache[ priceCacheSelector ];
}
noDpd=useUndiscountedPrice ? 'undiscounted_':'';
obj=epoHolder.find(selector);
if(epoObject.is_associated===false){
obj=obj.not(tcAPI.associatedEpoSelector + ' ' + selector);
}
if(! forced){
obj=obj.filter('.tcenabled');
}
if(! total){
total=0;
}
if(! original_total){
original_total=0;
}
funcTotal=total;
cumulativeTotal=total;
total_taxed=total;
original_total_taxed=original_total;
if(! floatingBoxData){
floatingBoxData=[];
}
currentTotalsContainer=epoObject.this_epo_totals_container;
if(obj.length){
obj.toArray().forEach(function(tmcpfield){
var field=$(tmcpfield);
var _value='';
var fieldval;
var field_div=field.closest('.cpf-element');
var field_wrap=field.closest('.tmcp-field-wrap');
var field_label_show=field_div.attr('data-fblabelshow');
var field_value_show=field_div.attr('data-fbvalueshow');
var field_title='';
var option_quantity=field_wrap.find('.tm-qty').val();
var option_price;
var option_price_taxed;
var option_original_price;
var option_original_price_taxed;
var liw;
var cri;
var tl;
var options;
var forrangepicker;
var $decimals;
var _valueText='';
var setter;
var dofloatingBoxData=false;
if(selector==='.tc-epo-field-product'){
if(field_div.is('.cpf-type-product-thumbnailmultiple')||field_div.is('.cpf-type-product-checkbox')){
epoinline=field.closest('.tc-epo-element-product-holder').find('.tc-extra-product-options-inline');
}else if(field_div.is('.cpf-type-product-thumbnail')||field_div.is('.cpf-type-product-radio')||field_div.is('.cpf-type-product-dropdown')){
epoinline=field_div.find('.tc-epo-element-product-container[data-product_id="' + field.val() + '"]').find('.tc-extra-product-options-inline');
}else if(field_div.is('.cpf-type-product-single')){
epoinline=field_div.find('.tc-extra-product-options-inline');
}
currentTotalsContainer=$('.tc-epo-totals' + '.tm-product-id-' + epoinline.attr('data-product-id') + '[data-epo-id="' + epoinline.attr('data-epo-id') + '"]');
}
if(currentTotalsContainer.length){
if(field_label_show===''){
field_title=field_div.find('.tc-epo-element-label-text').html();
}
if(option_quantity===undefined){
option_quantity='';
}
if(mathTotal){
tm_element_epo_rules(epoObject, field, undefined, undefined, undefined, undefined, funcTotal, cumulativeTotal);
}
if(field.is(':checkbox, :radio, :input')){
option_price=0;
option_price_taxed=0;
option_original_price=0;
option_original_price_taxed=0;
if(field.is('.tmcp-checkbox, .tmcp-radio')){
if(forced||field.is(':checked')){
option_price=field.data(noDpd + 'raw_price');
option_price_taxed=field.data(noDpd + 'price');
option_original_price=field.data(noDpd + 'raw_original_price');
option_original_price_taxed=field.data(noDpd + 'original_price');
showTotal=true;
field.data('isset', 1);
liw=field.closest('li.tmcp-field-wrap');
cri=liw.find('.tc-image');
_value='';
_valueText='';
tl=field.closest('li.tmcp-field-wrap').find('.tc-label-text');
if(tl.length){
_value=tl.html();
_valueText=_value;
}
if(cri.length){
cri=cri.closest('.tc-label-wrap').clone().addClass('tc-img-floating');
cri.find('.tc-label, .tc-epo-style-wrapper, .tc-input-wrap').remove();
_value=cri[ 0 ].outerHTML + '<span class="tc-label-text">' + _value + '</span>';
}
dofloatingBoxData=true;
}else{
field.data('isset', 0);
}}else if(field.is('.tmcp-select')){
setter=field.find('option:selected');
option_price=setter.data(noDpd + 'raw_price');
option_price_taxed=setter.data(noDpd + 'price');
option_original_price=setter.data(noDpd + 'raw_original_price');
option_original_price_taxed=setter.data(noDpd + 'original_price');
options=field.children('option:selected');
if(!(options.val()===''&&options.attr('data-rulestype')==='')){
showTotal=true;
}
field.find('option').data('isset', 0);
setter.data('isset', 1);
if(!(setter.val()===''&&setter.attr('data-rulestype')==='')){
_value=setter.attr('data-text');
dofloatingBoxData=true;
_valueText=_value;
}}else if(field.is('.tmcp-selectmultiple')){
setter=field.find('option:selected');
setter.toArray().forEach(function(setterel){
setterel=$(setterel);
option_price=option_price + $.epoAPI.math.toFloat(setterel.data(noDpd + 'raw_price'));
option_price_taxed=option_price_taxed + $.epoAPI.math.toFloat(setterel.data(noDpd + 'price'));
option_original_price=option_original_price + $.epoAPI.math.toFloat(setterel.data(noDpd + 'raw_original_price'));
option_original_price_taxed=option_original_price_taxed + $.epoAPI.math.toFloat(setterel.data(noDpd + 'original_price'));
options=field.children('option:selected');
if(!(options.val()===''&&options.attr('data-rulestype')==='')){
showTotal=true;
}
field.find('option').data('isset', 0);
setterel.data('isset', 1);
if(!(setterel.val()===''&&setterel.attr('data-rulestype')==='')){
_value=setterel.attr('data-text');
dofloatingBoxData=true;
_valueText=_value;
}});
}else{
fieldval=field.val();
if(field.is("[type='file']")){
fieldval=fieldval.replace('C:\\fakepath\\', '');
}
if(fieldval){
if(field.is('.tmcp-range')&&fieldval==='0'){
field.data('isset', 0);
}else{
option_price=field.data(noDpd + 'raw_price');
option_price_taxed=field.data(noDpd + 'price');
option_original_price=field.data(noDpd + 'raw_original_price');
option_original_price_taxed=field.data(noDpd + 'original_price');
showTotal=true;
field.data('isset', 1);
_value=fieldval;
if(field.is('.tmcp-range')){
forrangepicker=field.closest('.tmcp-field-wrap').find('.tm-range-picker');
$decimals=forrangepicker.attr('data-step').split('.');
if($decimals.length===1){
$decimals=0;
}else{
$decimals=$decimals[ 1 ].length;
}
_value=formatPrice(_value, { precision: $decimals });
}
dofloatingBoxData=true;
_valueText=fieldval;
}}else{
field.data('isset', 0);
}}
if(! option_price){
option_price=0;
}
if(! option_original_price){
option_original_price=0;
}
if(! option_price_taxed){
option_price_taxed=0;
}
if(! option_original_price_taxed){
option_original_price_taxed=0;
}
if(dofloatingBoxData){
floatingBoxData.push({
title: field_title,
value: _value,
valueText: _valueText,
price: option_price_taxed,
original_price: option_original_price_taxed,
quantity: option_quantity,
label_show: field_label_show,
value_show: field_value_show,
input_type: field.attr('type')
});
}
option_price_taxed=tm_set_tax_price(option_price, currentTotalsContainer, field, undefined, undefined, undefined, true);
option_original_price_taxed=tm_set_tax_price(option_original_price, currentTotalsContainer, field, undefined, undefined, undefined, true);
if(setPriceTax){
option_price=option_price_taxed;
option_original_price=option_original_price_taxed;
}
total=$.epoAPI.math.toFloat(total) + $.epoAPI.math.toFloat(option_price);
total=$.epoAPI.math.toFloat($.epoAPI.math.round(total, 10));
original_total=$.epoAPI.math.toFloat(original_total) + $.epoAPI.math.toFloat(option_original_price);
original_total=$.epoAPI.math.toFloat($.epoAPI.math.round(original_total, 10));
total_taxed=$.epoAPI.math.toFloat(total_taxed) + $.epoAPI.math.toFloat(option_price_taxed);
total_taxed=$.epoAPI.math.toFloat($.epoAPI.math.round(total_taxed, 10));
vat_total=vat_total + $.epoAPI.math.toFloat(calculateTaxAmount(option_price_taxed, currentTotalsContainer));
original_total_taxed=$.epoAPI.math.toFloat(original_total_taxed) + $.epoAPI.math.toFloat(option_original_price_taxed);
original_total_taxed=$.epoAPI.math.toFloat($.epoAPI.math.round(original_total_taxed, 10));
if(cumulative){
cumulativeTotal=total;
}}
}});
}
priceArray={
total: total,
original_total: original_total,
total_taxed: total_taxed,
original_total_taxed: original_total_taxed,
vat_total: vat_total,
floatingBoxData: floatingBoxData,
showTotal: showTotal,
elementsLength: obj.length
};
if(priceCache===true){
priceCache={};
priceCache[ priceCacheSelector ]=priceArray;
}else if(priceCache!==true&&priceCache!==false){
priceCache[ priceCacheSelector ]=priceArray;
}
return priceArray;
}
function show_product_html(thisEpoObject, thisMainProduct, thisVariableProductContainer, type, $this, currentCart, variableProductContainers, isTrigger, qtyalt){
var epoObjectCopy=$.extend(true, {}, thisEpoObject);
var item_tm_extra_product_options=thisVariableProductContainer.find(tcAPI.associatedEpoSelector);
var item=thisVariableProductContainer;
var newEpoObject;
var showOnly=true;
if(item.closest('.cpf-element').is('.tc-hidden')){
return;
}
variableProductContainers.addClass('tm-hidden');
if(variableProductContainers.length){
toggleState(variableProductContainers, true);
}
if(type==='variable'){
if(! thisVariableProductContainer.is('.tc-init-variations')){
thisVariableProductContainer.addClass('variations_form');
setTimeout(function(){
newEpoObject=tm_init_epo(item, false, item_tm_extra_product_options.attr('data-product-id'), item_tm_extra_product_options.attr('data-epo-id'), $this, epoObjectCopy);
thisVariableProductContainer.addClass('tc-init-variations');
thisVariableProductContainer.tc_product_variation_form($this, currentCart, variableProductContainers, newEpoObject);
}, 40);
showOnly=false;
}else{
thisVariableProductContainer.trigger('refresh.tc-variation-form');
}}else if(! thisVariableProductContainer.is('.tc-init-product')){
thisVariableProductContainer.addClass('tc-init-product');
variableProductContainers.find('.tc-epo-element-variable-product').removeClass('variations_form');
variableProductContainers.find('.tc-epo-element-variations').removeClass('variations');
setTimeout(function(){
tm_init_epo(item, false, item_tm_extra_product_options.attr('data-product-id'), item_tm_extra_product_options.attr('data-epo-id'), $this, epoObjectCopy);
}, 20);
showOnly=false;
}
setTimeout(function(){
if(variableProductContainers.length){
toggleState(thisVariableProductContainer, false);
}}, 200);
setTimeout(function(){
if(qtyalt.length){
qtyalt.trigger('change');
}
if(thisVariableProductContainer.find(tcAPI.epoSelector).length===0){
thisVariableProductContainer.addClass('no-epo');
}
thisVariableProductContainer.removeClass('tm-hidden');
if(showOnly){
jWindow.trigger('cpflogicdone');
thisVariableProductContainer.find('.tm-quantity').trigger('showhide.cpfcustom');
}
if(isTrigger===undefined&&TMEPOJS.tm_epo_global_product_element_scroll==='yes'){
jWindow.tcScrollTo(thisVariableProductContainer, 200, $.epoAPI.math.toFloat(TMEPOJS.tm_epo_global_product_element_scroll_offset));
}}, 210);
}
function epoEventHandlers(epoObject, cartContainer, alternativeCart){
var product_id=epoObject.product_id;
var main_product=epoObject.main_product;
var main_cart=epoObject.main_cart;
var this_epo_container=epoObject.this_epo_container;
var this_totals_container=epoObject.this_totals_container;
var this_epo_totals_container=epoObject.this_epo_totals_container;
var epoEventId=epoObject.epoEventId;
var main_epo_inside_form=epoObject.main_epo_inside_form;
var epo_id_selector=epoObject.epo_id_selector;
var epo_id=epoObject.epo_id;
var product_id_selector=epoObject.product_id_selector;
var itemId='main';
var epoHolder;
var totalsHolderContainer;
var totalsHolder;
var currentCart;
var variation_id_selector;
var this_product_type;
var variationForm;
var qtyElement;
var finalTotalBoxMode;
var finalTotalBoxShowFinal;
var finalTotalBoxShowOptions;
var eventName=epoObject.is_associated ? 'tc-variation-form':'wc-variation-form';
var eventNamePrefix=epoObject.is_associated ? 'tc_':'';
var epoVariationSection;
var thismaxlength;
var epoFieldAll;
var selectSelector;
var epoFieldText;
var epoResetRadio;
var epoFieldUpload;
var epoFieldHasClearButton;
var tmQty;
var tmQuantity;
if(alternativeCart&&cartContainer){
itemId=$.epoAPI.applyFilter('tc_get_item_id', cartContainer.attr('data-item_id'), cartContainer);
epoHolder=main_product.find('.tm-extra-product-options.tm-cart-' + itemId);
totalsHolderContainer=main_product.find('.tm-totals-form-' + itemId);
totalsHolder=main_product.find('.tm-epo-totals.tm-cart-' + itemId);
variationForm=cartContainer.find('.variations_form').first();
}else{
if(! main_cart||main_cart.length===0){
if(this_epo_container.is('.tc-shortcode')){
main_cart=main_product;
}else{
main_cart=get_main_cart(main_product, main_product, 'form', product_id);
}}
cartContainer=main_cart.parent();
epoHolder=this_epo_container;
totalsHolderContainer=this_totals_container;
totalsHolder=this_epo_totals_container;
variationForm=epoObject.variations_form;
}
if(epoObject.is_associated){
itemId=epoHolder.attr('data-cart-id');
}
currentCart=alternativeCart||main_cart;
totalsHolder.data('tm_for_cart', currentCart);
variation_id_selector=getVariationIdSelector(currentCart);
qtyElement=getQtyElement(currentCart);
totalsHolder.data('variationIdElement', getVariationIdElement(currentCart, '.wceb_picker_wrap ' + variation_id_selector));
totalsHolder.data('qty_element', qtyElement);
this_product_type=totalsHolder.data('type');
variationForm.data('tc_product_id', product_id);
finalTotalBoxMode=totalsHolder.attr('data-tm-epo-final-total-box');
finalTotalBoxShowFinal=totalsHolder.attr('data-tm-epo-show-final-total');
finalTotalBoxShowOptions=totalsHolder.attr('data-tm-epo-show-options-total');
jWindow.on('epoCalculateRules', function(event, dataObject){
if(event&&dataObject&&dataObject.currentCart){
tm_epo_rules(epoObject, dataObject.currentCart);
}});
if(currentCart.is('form')){
currentCart.on('reset', function(){
var form=$(this);
setTimeout(function(){
$(form.data('epo_id_selector')).find('.tm-epo-field').trigger('change');
}, 1);
});
}
tm_epo_rules(epoObject, currentCart);
epoFieldAll=epoHolder.find('.tm-epo-field');
if(! epoObject.is_associated){
epoFieldAll=epoFieldAll.not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector + ' .tm-epo-field');
}
epoFieldText=epoHolder.find('.tm-epo-field.tmcp-textarea,.tm-epo-field.tmcp-textfield');
if(! epoObject.is_associated){
epoFieldText=epoFieldText.not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector + ' .tm-epo-field');
}
epoResetRadio=epoHolder.find('.tm-epo-reset-radio');
if(! epoObject.is_associated){
epoResetRadio=epoResetRadio.not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector + ' .tm-epo-reset-radio');
}
epoFieldUpload=epoHolder.find('.tm-epo-field.tmcp-upload');
if(! epoObject.is_associated){
epoFieldUpload=epoFieldUpload.not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector + ' .tm-epo-field.tmcp-upload');
}
epoFieldHasClearButton=epoHolder.find('.tm-has-clearbutton .tm-epo-field');
if(! epoObject.is_associated){
epoFieldHasClearButton=epoFieldHasClearButton.not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector + ' .tm-has-clearbutton .tm-epo-field');
}
tmQty=epoHolder.find('.tm-quantity .tm-qty');
if(! epoObject.is_associated){
tmQty=tmQty.not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector + ' .tm-quantity .tm-qty');
}
tmQuantity=epoHolder.find('.tm-quantity');
if(! epoObject.is_associated){
tmQuantity=tmQuantity.not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector + ' .tm-quantity');
}
selectSelector=epoHolder.find('select.tm-epo-field');
if(! epoObject.is_associated){
selectSelector=selectSelector.not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector + ' select.tm-epo-field');
}
selectSelector
.off('tm-select-change-html')
.on('tm-select-change-html', function(){
var field=$(this);
var formatted_price;
var original_formatted_price;
var e_tip;
var e_description;
var sign;
if(field.is('.tc-epo-field-product')||field.is('.tmcp-selectmultiple')){
return;
}
if(main_cart&&main_cart.data('per_product_pricing')!==undefined&&! main_cart.data('per_product_pricing')){
return;
}
formatted_price=tm_set_price(field.find('option:selected').data('price'), totalsHolder, true, false, field);
original_formatted_price=tm_set_price(field.find('option:selected').data('original_price'), totalsHolder, true, false, field);
e_tip=field.closest('.tmcp-field-wrap').find('.tc-tooltip');
e_description=field.closest('.tmcp-field-wrap').find('.tc-inline-description');
tm_update_price(field.closest('.tmcp-field-wrap').find('.tc-price'), field.find('option:selected').data('price'), formatted_price, field.find('option:selected').data('original_price'), original_formatted_price);
if(e_tip.length > 0){
e_tip.attr('data-tm-tooltip-html', field.find('option:selected').attr('data-tm-tooltip-html')).trigger('tc-tooltip-html-changed');
}
if(e_description.length > 0){
if(field.find('option:selected').attr('data-tm-tooltip-html')){
e_description.html(field.find('option:selected').attr('data-tm-tooltip-html'));
}else{
e_description.html('');
}}
if((field.find('option:selected').attr('data-hide-amount')==='0'||TMEPOJS.tm_epo_show_price_inside_option_hidden_even==='yes') &&
TMEPOJS.tm_epo_show_price_inside_option==='yes' &&
field.find('option:selected').attr('data-text') &&
field.find('option:selected').data('price')
){
if((TMEPOJS.tm_epo_auto_hide_price_if_zero==='yes'&&$.tmempty(field.find('option:selected').data('price'))===false) ||
(TMEPOJS.tm_epo_auto_hide_price_if_zero!=='yes'&&field.find('option:selected').attr('data-price')!=='')
){
sign='';
field.find('option:selected').html(field.find('option:selected').attr('data-text') + ' (' + sign + formatted_price + ')');
}}
if(field.val()===''){
e_tip.addClass('tm-hidden');
}else if(field.find('option:selected').attr('data-tm-tooltip-html')){
e_tip.removeClass('tm-hidden');
}else{
e_tip.addClass('tm-hidden');
}})
.off('tm-math-select-change-html-all tm-select-change-html-all tm-select-change-html-all-math')
.on('tm-math-select-change-html-all tm-select-change-html-all tm-select-change-html-all-math', function(event){
var field=$(this);
var e_tip;
var e_description;
var thisoption;
var divider;
var thisformatted_price;
if(field.is('.tc-epo-field-product')){
return;
}
e_tip=field.closest('.tmcp-field-wrap').find('.tc-tooltip');
e_description=field.closest('.tmcp-field-wrap').find('.tc-inline-description');
if(e_tip.length > 0){
e_tip.attr('data-tm-tooltip-html', field.find('option:selected').attr('data-tm-tooltip-html')).trigger('tc-tooltip-html-changed');
}
if(field.val()===''){
e_tip.addClass('tm-hidden');
}else if(field.find('option:selected').attr('data-tm-tooltip-html')){
e_tip.removeClass('tm-hidden');
}else{
e_tip.addClass('tm-hidden');
}
if(e_description.length > 0){
if(field.find('option:selected').attr('data-tm-tooltip-html')){
e_description.html(field.find('option:selected').attr('data-tm-tooltip-html'));
}else{
e_description.html('');
}}
if(main_cart&&main_cart.data('per_product_pricing')!==undefined&&! main_cart.data('per_product_pricing')){
return;
}
if(TMEPOJS.tm_epo_show_price_inside_option==='yes'){
field.find('option').each(function(){
thisoption=$(this);
if(! thisoption.val()){
return true;
}
if(event.type==='tm-select-change-html-all'){
thisoption.removeClass('tm-epo-late-field').removeData('tm-price-for-late islate');
tm_element_epo_rules(epoObject, field, undefined, thisoption, 1);
}else if(event.type==='tm-math-select-change-html-all'){
tm_element_epo_rules(epoObject, field, undefined, thisoption, 1, true);
}else if(event.type==='tm-select-change-html-all-math'){
thisoption.removeClass('tm-epo-late-field').removeData('tm-price-for-late islate');
tm_element_epo_rules(epoObject, field, undefined, thisoption, 1, true);
}
divider=1;
if(TMEPOJS.tm_epo_multiply_price_inside_option!=='yes'){
divider=field.data('tm-quantity');
}
if(! divider){
divider=1;
}
if(thisoption.data('price')){
thisformatted_price=tm_set_price(thisoption.data('price') / divider, totalsHolder, true, false, field);
if(( thisoption.attr('data-hide-amount')==='0'||TMEPOJS.tm_epo_show_price_inside_option_hidden_even==='yes')&&thisoption.attr('data-text')){
if(( TMEPOJS.tm_epo_auto_hide_price_if_zero==='yes'&&$.tmempty(thisoption.data('price'))===false)||(TMEPOJS.tm_epo_auto_hide_price_if_zero!=='yes'&&thisoption.attr('data-price')!=='')){
thisoption.html(thisoption.attr('data-text') + ' (' + thisformatted_price + ')');
}}
}});
}})
.off('tm-select-change')
.on('tm-select-change', function(){
var field=$(this);
var thisElementId=field.closest('.cpf-element').attr('data-uniqid');
if(field.is('.tc-epo-field-product')){
return;
}
if(main_cart&&main_cart.data('per_product_pricing')!==undefined&&! main_cart.data('per_product_pricing')){
return;
}
field.removeData('addedtcEpoBeforeOptionPriceCalculation');
field.removeData('addedfieldtcEpoBeforeOptionPriceCalculation');
jWindow.off('tcEpoBeforeOptionPriceCalculation.math' + thisElementId);
jWindow.off('tcEpoAfterOptionPriceCalculation.math' + thisElementId);
field.trigger('tm-select-change-html');
field.trigger('tm-select-change-html-all');
currentCart.trigger({
type: 'tm-epo-update',
norules: 1,
element: field
});
}).trigger('tm-select-change-html-all');
tmQty
.off('focus.cpf')
.on('focus.cpf', function(){
var qtyField=$(this);
var field=qtyField.closest('.tmcp-field-wrap').find('.tm-epo-field');
var currentVal=parseFloat(qtyField.val());
var max=parseFloat(qtyField.attr('max'));
var min=parseFloat(qtyField.attr('min'));
var step=qtyField.attr('step');
var check1=tm_limit_c_selection(field, false);
var check2=tm_exact_c_selection(field, false);
var check3=true;
if(! currentVal||currentVal===''||currentVal==='NaN'){
currentVal=0;
}
if(max===''||max==='NaN'){
max='';
}
if(min===''||min==='NaN'){
min=0;
}
if(step==='any'||step===''||step===undefined||parseFloat(step)==='NaN'){
step=1;
}
if(currentVal < min||currentVal > max){
check3=false;
}
if(check1&&check2&&check3){
qtyField.data('tm-prev-value', currentVal);
}else{
qtyField.data('tm-prev-value', min);
}})
.off('change.cpf')
.on('change.cpf', function(event, data){
var qtyField=$(this);
var field=qtyField.closest('.tmcp-field-wrap').find('.tm-epo-field');
var currentVal=parseFloat(qtyField.val());
var max=parseFloat(qtyField.attr('max'));
var min=parseFloat(qtyField.attr('min'));
var step=qtyField.attr('step');
var check1=tm_limit_c_selection(field, false);
var check2=tm_exact_c_selection(field, false);
var check3=true;
if(! currentVal||currentVal===''||currentVal==='NaN'){
currentVal=0;
}
if(max===''||max==='NaN'){
max='';
}
if(min===''||min==='NaN'){
min=0;
}
if(step==='any'||step===''||step===undefined||parseFloat(step)==='NaN'){
step=1;
}
if(currentVal < min||currentVal > max){
check3=false;
}
if(check1&&check2&&check3){
if(! epoObject.noEpoUpdate){
field.data('tm-quantity', qtyField.val()).trigger('change', data);
}else{
field.data('tm-quantity', qtyField.val()).trigger('change.cpf', data).trigger('change.cpfproduct', data);
}
field.trigger('tm-select-change-html-all');
}else if(qtyField.data('tm-prev-value')){
qtyField.val(qtyField.data('tm-prev-value'));
}else{
qtyField.val(min);
}
qtyField.trigger('cpf-changed');
})
.off('tmaddquantity')
.on('tmaddquantity', function(){
var qtyField=$(this);
var field=qtyField.closest('.tmcp-field-wrap').find('.tm-epo-field');
field.data('tm-quantity', qtyField.val());
});
thismaxlength=epoHolder.find('.tmcp-textfield.tm-epo-field[maxlength],textarea.tm-epo-field[maxlength]');
if(! epoObject.is_associated){
thismaxlength=thismaxlength.not(tcAPI.epoSelector + ' ' + tcAPI.associatedEpoSelector + ' .tm-epo-field');
}
thismaxlength.each(function(){
var field=$(this);
var innerWrap=field.closest('.tmcp-field-wrap-inner');
var html=$.epoAPI.template.html(tcAPI.templateEngine.tc_chars_remanining, {
maxlength: field.attr('maxlength'),
characters_remaining: TMEPOJS.i18n_characters_remaining
});
innerWrap.append($(html));
});
thismaxlength
.off('change.tc_maxlen input.tc_maxlen')
.on('change.tc_maxlen input.tc_maxlen', function(){
var field=$(this);
field
.closest('.tmcp-field-wrap')
.find('.tc-chars-remanining')
.html(parseInt(field.attr('maxlength'), 10) - parseInt(field.val().length, 10));
});
epoFieldAll
.off('tm_trigger_product_image')
.on('tm_trigger_product_image', function(){
var field=$(this);
var currentElement;
var uic;
var variation_element_section;
var is_variation_element;
var src;
if(field.is('.tm-product-image:checkbox, .tm-product-image:radio, select.tm-product-image')){
uic=field.closest('.tmcp-field-wrap').find('label img');
variation_element_section=field.closest('.cpf-section');
is_variation_element=variation_element_section.is('.tm-epo-variation-section');
currentElement=field;
if(field.is('select.tm-product-image')){
currentElement=field.children('option:selected');
}
if($(uic).length > 0 ||
(is_variation_element&&currentElement.attr('data-image')!==undefined) ||
(currentElement.attr('data-image')!==undefined&&currentElement.attr('data-image')!=='') ||
(currentElement.attr('data-imagep')!==undefined&&currentElement.attr('data-imagep')!=='')
){
if(field.is(':checked')||(field.is('select.tm-product-image')&&field.val()!==''&&(field.find('option:selected').attr('data-rules')!==''||field.is('.tm-epo-variation-element')))){
src=$(uic).first().attr('data-original');
if(! src&&! is_variation_element){
src=$(uic).first().attr('src');
}
if(! src){
src=currentElement.attr('data-image');
}
if(currentElement.attr('data-imagep')){
src=currentElement.attr('data-imagep');
}
if(src){
main_product.trigger('tm_change_product_image', {
src: src,
element: field,
element_current: currentElement,
main_product: main_product,
epo_holder: epoHolder
});
}else{
main_product.trigger('tm_change_product_image', {
src: false,
element: field,
element_current: currentElement,
main_product: main_product,
epo_holder: epoHolder
});
}}else{
main_product.trigger('tm_restore_product_image', {
element: field,
element_current: currentElement,
main_product: main_product,
epo_holder: epoHolder
});
}}else{
main_product.trigger('tm_restore_product_image', {
element: field,
element_current: currentElement,
main_product: main_product,
epo_holder: epoHolder
});
}}else{
main_product.trigger('tm_attempt_product_image', {
element: field,
element_current: currentElement,
main_product: main_product,
epo_holder: epoHolder
});
}});
tmQuantity
.off('showhide.cpfcustom')
.on('showhide.cpfcustom', function(){
var quantity_selector=$(this);
var field=quantity_selector.closest('.tmcp-field-wrap').find('.tm-epo-field');
var show=false;
var tmqty;
var tmqtyval;
var tmqtymin;
var radios;
if(! field.is('.tm-epo-variation-element')){
if(field.is('select')){
if(field.val()!==''){
show=true;
}}else if(field.is(':checkbox')){
if(field.is(':checked')){
show=true;
}}else if(field.is(':radio')){
if(field.is(':checked')){
show=true;
if(TMEPOJS.tm_epo_show_only_active_quantities==='yes'){
radios=field.closest('.tc-element-inner-wrap').find('.tm-epo-field.tmcp-radio');
radios.each(function(){
$(this).closest('.tmcp-field-wrap').find('.tm-quantity').hide();
});
}}
}else if(field.val()){
show=true;
}
tmqty=quantity_selector.find('.tm-qty');
tmqtyval=tmqty.val();
tmqtymin=tmqty.attr('min')||'';
if(show){
if(TMEPOJS.tm_epo_show_only_active_quantities==='yes'){
quantity_selector.show();
}
tmqty.removeClass('ignore').prop('disabled', false);
}else{
if(TMEPOJS.tm_epo_show_only_active_quantities==='yes'){
quantity_selector.hide();
if(! tmqtyval){
tmqty.val(tmqtymin);
}}
tmqty.addClass('ignore').prop('disabled', true);
}
if(epoHolder.is('.tc-show')){
setTimeout(function(){
quantity_selector.closest('.tcowl-carousel').trigger('refresh.owl.carousel');
}, 200);
}}
});
epoFieldAll
.off('change.cpfcustom')
.on('change.cpfcustom', function(){
$(this).closest('.tmcp-field-wrap').find('.tm-quantity').trigger('showhide.cpfcustom');
});
epoFieldAll
.off('change.cpf')
.on('change.cpf', function(event, data){
var field=$(this);
var is_li=field.closest('.tmcp-field-wrap');
var is_ul=field.closest('.tmcp-ul-wrap');
var is_replace;
var connector=is_ul.attr('data-tm-connector');
if(field.is(':checkbox, :radio')){
if(field.is(':radio')){
if(! data){
if(connector!==undefined){
$('[data-tm-connector="' + connector + '"]').find('.tmcp-field-wrap').removeClass('tc-active').find('.tm-epo-reset-radio').addClass('tm-hidden');
}else{
is_ul.find('.tmcp-field-wrap').removeClass('tc-active');
}}
if(connector!==undefined){
$('[data-tm-connector="' + connector + '"]').find('.tmcp-field-wrap').removeClass('tc-active').find('.tm-epo-reset-radio').addClass('tm-hidden');
}}
if(field.is(':checked')){
is_li.addClass('tc-active');
}else{
is_li.removeClass('tc-active');
}}
if(! field.is('.tm-epo-variation-element')){
if(field.is('.use_images:checkbox, .use_images:radio')&&field.attr('data-imagec')){
is_replace=is_li.find('.radio-image,.checkbox-image').first();
if(is_replace.length > 0){
if(field.is(':checked')){
is_replace.prop('src', field.attr('data-imagec'));
}else{
is_replace.prop('src', field.attr('data-image'));
}}
}
if(field.is('.use_images:radio')){
field
.closest('.cpf-type-radio')
.find('.use_images:radio')
.not(field)
.each(function(){
var r=$(this);
r.closest('.tmcp-field-wrap').find('.radio-image').first().prop('src', r.attr('data-image'));
});
}
if(field.is('.tmcp-range')){
field.trigger('change.cpflogic');
}
if(field.is('select')){
field.trigger('tm-select-change');
}else{
if(field.is('.tmcp-radio')){
field
.closest('.cpf-element')
.find('.tm-quantity .tm-qty')
.each(function(){
if(! $(this).closest('li.tmcp-field-wrap').find('.tmcp-radio').is(':checked')){
$(this).attr('disabled', 'disabled');
}else{
$(this).prop('disabled', false);
}});
}
priceCache=true;
currentCart.trigger({
type: 'tm-epo-update',
norules: 1,
element: field
});
priceCache=false;
}}
field.trigger('tm_trigger_product_image');
if(epoHolder.is('.tc-show')){
setTimeout(function(){
$('.tm-owl-slider').each(function(){
$(this).trigger('refresh.owl.carousel');
});
}, 200);
}
main_product.trigger('tm_attempt_product_image', {
element: field,
main_product: main_product,
epo_holder: epoHolder
});
});
epoFieldAll
.filter(':checkbox:checked, :radio:checked')
.each(function(){
$(this).closest('.tmcp-field-wrap').addClass('tc-active');
$(this).trigger('change.cpf');
});
epoFieldHasClearButton
.off('change.cpfclearbutton')
.on('change.cpfclearbutton cpfclearbutton', function(){
var field=$(this);
var radioResetElement;
var fieldWrap=field.closest('.tmcp-field-wrap');
var fieldSearch;
if(field.is(':checked')){
fieldSearch=field.closest('.tc-element-inner-wrap');
if(fieldSearch.find('.tc-epo-element-product-li-container').length){
fieldSearch=fieldSearch.find('.tmcp-ul-wrap').first().children('.tmcp-field-wrap').not('.tc-epo-element-product-li-container');
}
radioResetElement=fieldSearch.find('.tm-epo-reset-radio');
if(! radioResetElement.length){
radioResetElement=field.closest('.tc-element-inner-wrap').find('.tm-epo-reset-radio').first();
}
radioResetElement.removeClass('tm-hidden');
fieldWrap.append(radioResetElement);
}});
epoResetRadio
.off('click.cpf')
.on('click.cpf', function(){
var radioResetElement=$(this);
var fieldContainer=radioResetElement.closest('.tc-element-inner-wrap');
var checkedRadios=fieldContainer.find('.tm-epo-field.tmcp-radio:checked');
if(checkedRadios.length){
checkedRadios.prop('checked', false);
checkedRadios.trigger('change', { forced: 1 });
}
radioResetElement.addClass('tm-hidden');
});
if(_&&_.debounce){
epoFieldText.on('keyup',
_.debounce(function(){
var $this=$(this);
if(TMEPOJS.tm_epo_global_enable_validation==='yes'&&$.tc_validator&&$this.closest('.tmcp-ul-wrap').data('tm-validation')&&$this.tc_rules()){
currentCart.tc_validate().element($this);
}
$this.trigger('change.cpf');
$this.closest('.tmcp-field-wrap').find('.tm-quantity').trigger('showhide.cpfcustom');
}, 10)
);
}
epoFieldUpload
.off('change.cpfv tcupload')
.on('change.cpfv tcupload', function(){
var field=$(this);
var label=field.closest('label');
var li=field.closest('.tmcp-field-wrap');
var cpfUploadContainer=li.find('.cpf-upload-container');
var name=li.find('.tm-filename');
var val=field.val().replace('C:\\fakepath\\', '');
var valHidden=[];
var num_uploads;
var windowURL=window.URL||window.webkitURL;
var files;
var image;
var uploadPreview=li.find('.tc-upload-preview');
var addImage;
var uniqid;
if(cpfUploadContainer.length&&name.length <=0){
name=$('<span class="tm-filename"></span>');
label.after(name);
}
if(val===undefined||val==='undefined'){
val='';
}
field.next('.tmcp-upload-hidden').remove();
valHidden=field.attr('data-file');
valHidden=valHidden ? valHidden.split('|'):[];
if(this.files){
files=Array.from(this.files);
}else if(valHidden.length > 0){
files=valHidden;
}
if(files.length > 1){
name.html('' + files.length + ' ' +(files.length===1 ? TMEPOJS.i18n_file:TMEPOJS.i18n_files));
}else if(files.length===1){
name.html(val);
}else{
name.empty();
}
if(! uploadPreview.length){
uploadPreview=$('<div class="tc-upload-preview tc-hidden"></div>');
li.append(uploadPreview);
}
uploadPreview.empty();
num_uploads=epoHolder.data('num_uploads');
if(! num_uploads){
num_uploads=[];
}
uniqid=field.closest('.cpf-element').attr('data-uniqid');
if(! num_uploads[ uniqid ]){
num_uploads[ uniqid ]=[];
}
if(( val||files.length > 0)&&windowURL&&windowURL.createObjectURL){
if(TMEPOJS.tm_epo_upload_inline_image_preview==='yes'){
if(files.length > 1){
uploadPreview.addClass('multiple');
}else{
uploadPreview.removeClass('multiple');
}
uploadPreview.removeClass('tc-hidden');
}
addImage=function(dataFile, src, i, fileHolder, ext){
var size=field[ 0 ].files&&field[ 0 ].files[ i ]&&field[ 0 ].files[ i ].size ? field[ 0 ].files[ i ].size:0;
var imageHTML='<div class="tc-upload-image">';
if(src){
imageHTML=imageHTML + '<img src="' + src + '">';
}else{
imageHTML=imageHTML + '<div class="tc-file-ext-overlay"></div>';
}
imageHTML=imageHTML + '<div class="tc-file-name">' + dataFile.name + '</div>';
if(ClipboardEvent||DataTransfer){
imageHTML=imageHTML + '<button type="button" class="tc-upload-remove"><svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M11.586 13l-2.293 2.293a1 1 0 0 0 1.414 1.414L13 14.414l2.293 2.293a1 1 0 0 0 1.414-1.414L14.414 13l2.293-2.293a1 1 0 0 0-1.414-1.414L13 11.586l-2.293-2.293a1 1 0 0 0-1.414 1.414L11.586 13z" fill="currentColor" fill-rule="nonzero"/></svg></button>';
}
if(ext){
imageHTML=imageHTML + '<div class="tc-file-ext">' + ext + '</div>';
}
imageHTML=imageHTML + '<div class="tc-file-size">' + readableFileSize(size) + '</div>';
imageHTML=imageHTML + '</div>';
fileHolder.append(imageHTML);
};
files.forEach(function(dataFile, i){
var fileHolder;
if(TMEPOJS.tm_epo_upload_inline_image_preview==='yes'){
fileHolder=$('<div class="tc-upload-file"></div>');
uploadPreview.append(fileHolder);
image=new Image();
image.onload=function(){
addImage(dataFile, this.src, i, fileHolder);
};
image.onerror=function(){
addImage(dataFile, false, i, fileHolder, dataFile.name.split('.').pop());
};
if(valHidden.length > 0){
image.src=valHidden[ i ];
}else{
image.src=windowURL.createObjectURL(dataFile);
windowURL.revokeObjectURL(dataFile);
}}
num_uploads[ uniqid ].push(dataFile.name);
});
epoHolder.data('num_uploads', num_uploads);
}else{
delete num_uploads[ uniqid ];
}
if(num_uploads[ uniqid ]&&num_uploads[ uniqid ].length===0){
delete num_uploads[ uniqid ];
}});
jDocument.on('click', '.tc-upload-remove', function(){
var $this=$(this);
var val;
var cpfElement;
var input;
var fileWrap;
var li;
var uploadPreview;
var name;
var index;
var files;
var dT;
var num_uploads;
var uniqid;
var uploadHidden;
var dataFiles;
if(ClipboardEvent||DataTransfer){
cpfElement=$this.closest('.cpf-element');
input=cpfElement.find('.tm-epo-field');
fileWrap=$this.closest('.tc-upload-file');
li=$this.closest('.tmcp-field-wrap');
uploadPreview=li.find('.tc-upload-preview');
name=li.find('.tm-filename');
index=fileWrap.index();
val=input.val().replace('C:\\fakepath\\', '');
if(val===undefined||val==='undefined'){
val='';
}
files=Array.from(input[ 0 ].files);
files.splice(index, 1);
dT=new ClipboardEvent('').clipboardData||new DataTransfer();
files.forEach(function(dataFile){
dT.items.add(dataFile);
});
if(files.length > 1){
uploadPreview.addClass('multiple');
}else{
uploadPreview.removeClass('multiple');
}
input[ 0 ].files=dT.files;
fileWrap.remove();
if(dT.files.length > 1){
name.html('' + dT.files.length + ' ' +(dT.files.length===1 ? TMEPOJS.i18n_file:TMEPOJS.i18n_files));
}else if(dT.files.length===1){
name.html(val);
}else{
name.empty();
}
num_uploads=epoHolder.data('num_uploads');
if(! num_uploads){
num_uploads=[];
}
uniqid=cpfElement.closest('.cpf-element').attr('data-uniqid');
if(! num_uploads[ uniqid ]){
num_uploads[ uniqid ]=[];
}
num_uploads[ uniqid ].splice(index, 1);
if(num_uploads[ uniqid ].length===0){
delete num_uploads[ uniqid ];
input.val('');
}
uploadHidden=input.next('.tmcp-upload-hidden');
if(uploadHidden.length){
dataFiles=uploadHidden.val().split('|');
if(dataFiles.length > 0){
dataFiles.splice(index, 1);
}
if(dataFiles.length===0){
uploadHidden.remove();
}else{
uploadHidden.val(dataFiles.join('|'));
}}
epoHolder.data('num_uploads', num_uploads);
}});
qtyElement
.off('change.cpf input.cpf')
.on('change.cpf input.cpf', function(){
var field=$(this);
currentCart.trigger('tm-epo-check-dpd');
field.data('tm-prev-value', field.val());
currentCart.trigger({
type: 'tm-epo-update',
norules: 2
});
})
.data('tm-prev-value', qtyElement.val());
epoHolder
.find('.cpf-type-product')
.off('tc-logic')
.on('tc-logic', function(){
var $this=$(this);
if($this.find('.tc-init').length){
return;
}
if($this.data('isactive')&&! $this.data('donetclogic')){
$this.data('donetclogic', true);
$this.find('.tc-epo-field-product').trigger('change.cpfproduct', { forced: 3 });
}});
epoHolder
.find('.cpf-type-product .tc-epo-field-product.tc-epo-field-product-checkbox')
.off('change.cpfrequired')
.on('change.cpfrequired', function(){
var $this=$(this);
var cpfElement=$this.closest('.cpf-element');
var checkboxes;
var checkboxesChecked;
var checkboxesNotChecked;
if(cpfElement.is('.tc-is-required')){
checkboxes=cpfElement.find('.tmcp-field.tc-epo-field-product-checkbox');
checkboxesNotChecked=checkboxes.not(':checked');
checkboxesChecked=cpfElement.find('.tmcp-field.tc-epo-field-product-checkbox:checked');
if(checkboxesChecked.length > 0){
checkboxesNotChecked.prop('required', false);
checkboxesChecked.prop('required', true);
}else{
checkboxes.attr('required', true);
checkboxes.prop('required', true);
}}
});
epoHolder
.find('.cpf-type-product .tc-epo-field-product')
.off('change.cpfproduct')
.on('change.cpfproduct', function(e, data){
var $this=$(this);
var value;
var type;
var selected;
var variableProductContainers;
var thisVariableProductContainer;
var elementContainer=$this.closest('.cpf-element');
var productContainerWraps=elementContainer.find('.tc-epo-element-product-container-wrap');
var thisProductContainerWrap=$this.closest('.tmcp-field-wrap').find('.tc-epo-element-product-container-wrap');
var hasProductContainerWrap=thisProductContainerWrap.length > 0;
var postData;
var skip=false;
var isTrigger=1000;
var qtyalt;
var associatedSetter=$this;
var associatedElement;
var isFilled;
var productPrice;
var originalProductPrice;
var epoField=elementContainer.find('.tm-epo-field').not('.tc-epo-element-product-li-container .tm-epo-field');
var checked=epoField.filter(':checked');
var qty;
var counter=$this.attr('data-counter');
if(false===elementContainer.data('isactive')){
return;
}
if(data&&data.forced===2){
return;
}
if(e.isTrigger!==undefined&&$this.data('triggeredonce')&&!(data&&data.forced)){
return;
}
$this.data('triggeredonce', 1);
if(! $this.is(':checkbox')){
isTrigger=e.isTrigger;
}
if(epoField.is(':radio')){
if(checked.length > 0){
qty=checked.closest('.tmcp-field-wrap').find('input.tm-qty');
}}else if(epoField.is(':checkbox')){
if(checked.length > 0){
qty=$this.closest('.tmcp-field-wrap').find('input.tm-qty');
}}else{
qty=epoField.closest('.tmcp-field-wrap').find('input.tm-qty');
}
if($this.is(':checkbox')){
if($this.is('.tc-epo-field-product-hidden')){
if($this.is(':checked')){
productContainerWraps.addClass('tc-active-product');
}else{
productContainerWraps.removeClass('tc-active-product');
}
value=$this.val();
type=$this.attr('data-type');
elementContainer.find('.tc-epo-element-product-li-container').removeClass('tm-hidden');
}else{
if(! $this.is(':checked')){
if(hasProductContainerWrap){
thisProductContainerWrap.addClass('tm-hidden');
}
if(!(data&&data.forced)){
return;
}
skip=true;
}else if(hasProductContainerWrap){
thisProductContainerWrap.removeClass('tm-hidden');
}
if(! skip){
value=$this.val();
type=$this.attr('data-type');
elementContainer.find('.tc-epo-element-product-li-container').removeClass('tm-hidden');
}}
}else if($this.is(':radio')){
if(! $this.is(':checked')){
if(hasProductContainerWrap){
thisProductContainerWrap.addClass('tm-hidden');
}
if(!(data&&data.forced)){
return;
}
skip=true;
}else if(hasProductContainerWrap){
productContainerWraps.addClass('tm-hidden');
thisProductContainerWrap.removeClass('tm-hidden');
}
if(! skip){
value=$this.val();
type=$this.attr('data-type');
elementContainer.find('.tc-epo-element-product-li-container').removeClass('tm-hidden');
}}else if($this.is('select')){
selected=$this.children(':selected');
associatedSetter=selected;
counter=selected.index();
if($this.children(':first').val()===''){
counter--;
}
value=$this.val();
type=selected.attr('data-type');
elementContainer.find('.tc-epo-element-product-li-container').removeClass('tm-hidden');
}
if($this.is('.tc-epo-field-product-checkbox')){
variableProductContainers=thisProductContainerWrap.find('.tc-epo-element-product-container');
}else{
variableProductContainers=elementContainer.find('.tc-epo-element-product-container');
}
thisVariableProductContainer=variableProductContainers.filter('[data-product_id="' + value + '"]');
qtyalt=thisVariableProductContainer.find(tcAPI.associateQtySelector);
if(productContainerWraps.html()!==''&&qty&&qty.length > 0&&qtyalt.length===0){
qty.val(0);
}
if($this.is(':checkbox')){
if($this.is('.tc-epo-field-product-hidden')){
if($this.is(':checked')){
if(qtyalt.val()==='0'){
if(qtyalt.attr('min')!=='0'){
qtyalt.val(qtyalt.attr('min')).trigger('change');
}}
}else{
qtyalt.val(0);
qtyalt.closest('.tm-quantity-alt').removeClass('tm-hidden');
if(data.forced!==1){
qtyalt.closest('.tm-quantity-alt').find('.single_add_to_cart_product').trigger('cpfqtybutton');
}
productContainerWraps.find(tcAPI.associatedEpoCart).trigger('tm-epo-update');
}}
}else if($this.is(':radio')){
if($this.val()&&! $this.data('set_initial')){
if(qtyalt.val()==='0'){
if(qtyalt.attr('min')!=='0'){
qtyalt.val(qtyalt.attr('min')).trigger('change');
}
$this.data('set_initial', 1);
}}
}else if($this.is('select')){
if($this.val()&&! $this.data('set_initial')){
if(qtyalt.val()==='0'){
if(qtyalt.attr('min')!=='0'){
qtyalt.val(qtyalt.attr('min')).trigger('change');
}
$this.data('set_initial', 1);
}}
}else{
return;
}
if(! value){
variableProductContainers.addClass('tm-hidden');
productPrice=$.epoAPI.util.parseJSON(associatedSetter.attr('data-rules'));
productPrice=productPrice[ 0 ]||0;
originalProductPrice=$.epoAPI.util.parseJSON(associatedSetter.attr('data-original-rules'));
originalProductPrice=originalProductPrice||0;
if(associatedSetter.is('.tcenabled')){
associatedSetter.data('associated_price_set', 1);
}
associatedSetter.data('price_set', 1);
associatedSetter.data('raw_price', productPrice);
associatedSetter.data('raw_original_price', originalProductPrice);
associatedSetter.data('price', productPrice);
associatedSetter.data('original_price', originalProductPrice);
associatedElement=associatedSetter;
if(associatedElement.is('option')){
associatedElement=associatedSetter.closest('select');
}
isFilled=false;
if(associatedElement.is('.tc-epo-field-product')){
if(associatedElement.is('select')){
if(associatedElement.val()!==''){
isFilled=true;
}}else if(( associatedElement.is(':checkbox')||associatedElement.is(':radio'))){
if(associatedElement.is(':checked')){
isFilled=true;
}}else if(associatedElement.val()!==''){
isFilled=true;
}}
tm_force_update_price(
associatedSetter
.closest('.tmcp-field-wrap')
.find('.tc-price')
.not(tcAPI.associatedEpoSelector + ' .tc-price'),
productPrice,
isFilled ? tm_set_price_totals(productPrice):associatedSetter.data('price-html'),
originalProductPrice,
isFilled ? tm_set_price_totals(originalProductPrice):''
);
qtyElement.trigger('change.cpf');
return;
}
if(thisVariableProductContainer.length===0){
postData={
action: 'wc_epo_get_associated_product_html',
product_id: value,
parent_id: epoHolder.attr('data-product-id'),
mode: elementContainer.attr('data-mode'),
layout_mode: elementContainer.attr('data-product-layout-mode'),
uniqid: elementContainer.attr('data-uniqid'),
name: $this.attr('name'),
counter: counter,
quantity_min: elementContainer.attr('data-quantity-min'),
quantity_max: elementContainer.attr('data-quantity-max'),
priced_individually: elementContainer.attr('data-priced-individually'),
discount: elementContainer.attr('data-discount'),
discount_type: elementContainer.attr('data-discount-type'),
discount_exclude_addons: elementContainer.attr('data-discount-exclude-addons'),
show_image: elementContainer.attr('data-show-image'),
show_title: elementContainer.attr('data-show-title'),
show_price: elementContainer.attr('data-show-price'),
show_description: elementContainer.attr('data-show-description'),
show_meta: elementContainer.attr('data-show-meta'),
disable_epo: elementContainer.attr('data-disable-epo')
};
elementContainer.block({ message: null, overlayCSS: { background: '#fff', opacity: 0.6 }});
$.ajax({
url: TMEPOJS.ajax_url,
type: 'POST',
data: postData,
dataType: 'json',
success: function(response){
if(response.result===200){
thisVariableProductContainer=$(response.html);
if(hasProductContainerWrap){
$this.closest('.tmcp-field-wrap').find('.tc-epo-element-product-container-wrap').empty().append(thisVariableProductContainer);
}else{
elementContainer.find('.tc-epo-element-product-container-wrap').append(thisVariableProductContainer);
}
show_product_html(epoObject, main_product, thisVariableProductContainer, type, $this, currentCart, variableProductContainers, isTrigger, qtyalt);
thisVariableProductContainer.find(tcAPI.associateQtySelector).trigger('change');
}},
complete: function(){
elementContainer.unblock();
}});
}else{
show_product_html(epoObject, main_product, thisVariableProductContainer, type, $this, currentCart, variableProductContainers, isTrigger, qtyalt);
thisVariableProductContainer.find(tcAPI.associateQtySelector).trigger('change');
}});
jDocument
.off('click.cpfqtybutton cpfqtybutton', '.cpf-type-product .single_add_to_cart_product')
.on('click.cpfqtybutton cpfqtybutton', '.cpf-type-product .single_add_to_cart_product', function(){
var $this=$(this);
var qtyalt=$this.closest('.tm-quantity-alt').find(tcAPI.associateQtySelector);
var isAdd=$this.is('.alt');
var productContainerWraps=$this.closest('.cpf-element').find('.tc-epo-element-product-container-wrap');
var qtyMin;
var qtyMax;
if($this.data('inittriggeredonce')){
qtyMin=$.epoAPI.math.toInt(qtyalt.attr('data-min'));
qtyMax=$.epoAPI.math.toInt(qtyalt.attr('data-max'));
if(isAdd){
productContainerWraps.addClass('tc-active-product');
qtyalt.attr('min', qtyMin);
if(qtyMax){
qtyalt.attr('max', qtyMax);
}
if(qtyalt.val()==='0'){
if(qtyalt.attr('min')==='0'){
qtyalt.val(1).trigger('change');
}else{
qtyalt.val(qtyalt.attr('min')).trigger('change');
}}
$this.removeClass('alt').text($this.attr('data-remove'));
}else{
productContainerWraps.removeClass('tc-active-product');
qtyalt.val(0).trigger('change');
qtyalt.closest('.tm-quantity-alt').removeClass('tm-hidden');
$this.addClass('alt').text($this.attr('data-add'));
}}
$this.data('inittriggeredonce', 1);
productContainerWraps.find(tcAPI.associatedEpoCart).trigger('tm-epo-update');
});
jDocument
.off('change.cpfqtyalt input.cpfqtyalt', '.cpf-type-product ' + tcAPI.associateQtySelector)
.on('change.cpfqtyalt input.cpfqtyalt', '.cpf-type-product ' + tcAPI.associateQtySelector, function(){
var $this=$(this);
var epoField=$this.closest('.cpf-element').find('.tm-epo-field').not('.tc-epo-element-product-li-container .tm-epo-field');
var addButton=$this.closest('.tm-quantity-alt').find('.single_add_to_cart_product');
var checked=epoField.filter(':checked');
var qty;
var qtyMin;
var qtyMax;
var associatedEpoCart;
qtyMin=$.epoAPI.math.toInt($this.attr('min'));
qtyMax=$.epoAPI.math.toInt($this.attr('max'));
if(epoField.is('.tc-epo-field-product-hidden')&&epoField.is(':checkbox')){
if(checked.length===0&&$this.val()!=='0'){
epoField.prop('checked', true).trigger('change');
checked=epoField.filter(':checked');
}else if($this.val()==='0'&&checked.length){
epoField.prop('checked', false).trigger('change');
}}
if(epoField.is(':radio')){
if(checked.length===0){
return;
}
qty=checked.closest('.tmcp-field-wrap').find('input.tm-qty').not('.tc-element-qty');
}else if(epoField.is(':checkbox')){
if(checked.length===0){
return;
}
qty=$this.closest('.tmcp-field-wrap').find('input.tm-qty').not('.tc-element-qty');
}else{
qty=epoField.closest('.tmcp-field-wrap').find('input.tm-qty').not('.tc-element-qty');
}
if(qty.length===0){
return;
}
qty.attr('min', qtyMin);
if(qtyMax){
qty.attr('max', qtyMax);
}
associatedEpoCart=$this.closest('.tc-epo-element-product-container').find(tcAPI.associatedEpoCart);
associatedEpoCart.trigger('tm-epo-update');
qty.val($this.val());
if($.epoAPI.math.toFloat($this.val()) > 0){
associatedEpoCart.find('.tm-epo-field.tcenabled').removeClass('ignore');
$this.removeClass('ignore');
}else{
associatedEpoCart.find('.tm-epo-field.tcenabled').addClass('ignore');
$this.addClass('ignore');
}
epoField.trigger('change.cpfproduct', { forced: 2 });
if(addButton.data('inittriggeredonce')){
if($this.val()==='0'){
addButton.removeClass('alt');
}else{
addButton.addClass('alt');
}}
addButton.trigger('cpfqtybutton');
});
currentCart.off('tm-epo-update').on('tm-epo-update', function(event){
var cart=$(this);
var bundleid;
var productPrice=false;
var rawProductPrice=0;
var productRegularPrice=false;
var rawProductRegularPrice=0;
var total=0;
var original_total=0;
var showTotal=false;
var cartQty;
var elementQty=1;
var priceOverrideMode;
var perProductPricing=true;
var floatingBoxData=[];
var currentVariation;
var cart_fee_options_total=0;
var cart_fee_options_original_total=0;
var _total;
var _original_total;
var late_total_price;
var tc_totals_ob={};
var formatted_options_total;
var formatted_options_original_total;
var formatted_fees_total;
var formatted_fees_original_total;
var formatted_final_total;
var formatted_final_original_total;
var extraFee=0;
var raw_extraFee=0;
var product_total_price;
var product_total_original_price;
var calculateFinalProductPrice;
var total_plus_fee;
var original_total_plus_fee;
var product_total_price_without_options;
var unit_price;
var unit_original_price;
var formatted_unit_price;
var formatted_unit_original_price;
var html;
var show_options_total=false;
var show_vat_options_total=false;
var show_fees_total=false;
var formatted_extra_fee='';
var show_extra_fee=false;
var show_final_total=false;
var hide_native_price;
var update_native_html;
var _fprice;
var _f_regular_price;
var customerPriceFormat;
var currentEpoObject;
var raw_total;
var raw__total;
var raw_original_total;
var raw__original_total;
var raw_cart_fee_options_total;
var raw_cart_fee_options_original_total;
var raw_total_plus_fee;
var raw_original_total_plus_fee;
var raw_product_total_price_without_options;
var raw_product_total_price;
var raw_product_total_original_price;
var fetch;
var customer_price_format_wrap_start='';
var customer_price_format_wrap_end='';
var associatedSetter;
var associatedPrice;
var associatedRawPrice;
var associatedOriginalPrice;
var associatedRawOriginalPrice;
var associatedFormattedPrice;
var associatedFormattedOriginalPrice;
var nativeProductPriceSelector;
var elementsLength;
var productFieldSyncVatTotal=0;
var productFieldSyncTotal=0;
var productFieldSyncOriginalTotal=0;
var productFieldSyncTotalTaxed=0;
var productFieldSyncOriginalTotalTaxed=0;
var totalProductField=0;
var originalTotalProductField=0;
var totalProductFieldTaxed=0;
var originalTotalProductFieldTaxed=0;
var _ftotal;
var _foriginal_total;
var totalsHolder_tc_totals_ob;
var temp;
var vat_options_total;
var vat_options_total_plus_fee;
var formatted_vat_options_total;
var formatted_vat_options_total_plus_fee;
var vat_total;
var formatted_vat_total;
var vat_product_base;
var formatted_vat_product_base;
var pricesIncludeTax;
if(event.epoObject){
currentEpoObject=$.extend(true, {}, event.epoObject);
}else{
currentEpoObject=$.extend(true, {}, epoObject);
}
if(! currentEpoObject){
return;
}
if(currentEpoObject.noEpoUpdate){
return;
}
jWindow.trigger('tcEpoUpdateStart', {
epo: currentEpoObject,
alternativeCart: currentEpoObject,
this_product_type: this_product_type,
cart: cart,
totalsHolder: totalsHolder,
fetchOptionPrices: fetchOptionPrices,
epoHolder: epoHolder
});
bundleid=$.epoAPI.applyFilter('tc_get_bundleid', cart.attr('data-product_id'), cart, currentEpoObject);
priceOverrideMode=totalsHolder.attr('data-price-override');
cartQty=getCurrentQty(cart);
currentVariation=getCurrentVariation(cart);
if(currentEpoObject.associated_connect&&currentEpoObject.associated_connect.length===1){
cartQty=parseFloat(
currentEpoObject.main_product
.find(tcAPI.associateQtySelector)
.not(tcAPI.associatedEpoSelector + ' ' + tcAPI.qtySelector)
.last()
.val()
);
}
event.stopImmediatePropagation();
productPrice=$.epoAPI.applyFilter('tcGetCurrentProductPrice', tm_calculate_product_price(totalsHolder, true), currentCart, totalsHolder);
rawProductPrice=productPrice;
productRegularPrice=$.epoAPI.applyFilter('tcGetCurrentProductRegularPrice', tm_calculate_product_regular_price(totalsHolder, true), currentCart, totalsHolder);
rawProductRegularPrice=productRegularPrice;
productPrice=$.epoAPI.applyFilter('tcCalculateCurrentProductPrice', productPrice, {
epo: currentEpoObject,
alternativeCart: alternativeCart,
cart: cart,
main_product: main_product
});
if(! Number.isFinite(cartQty)){
if(totalsHolder.attr('data-is-sold-individually')||getQtyElement(cart).length===0){
cartQty=1;
}}
totalsHolder_tc_totals_ob={
qty: cartQty,
product_price: rawProductPrice,
original_product_price: rawProductRegularPrice
};
totalsHolder.data('totalsHolder_tc_totals_ob', totalsHolder_tc_totals_ob);
if(! event.norules){
tm_epo_rules(currentEpoObject, cart);
}else if(event.norules){
if(event.norules===1){
tm_element_epo_rules(currentEpoObject, event.element);
}
$.tcepo.lateFieldsPrices[ epoEventId ]=[];
epoHolder
.find('.tm-epo-late-field')
.toArray()
.forEach(function(setter){
setter=$(setter);
setter.data('price', 0);
$.tcepo.lateFieldsPrices[ epoEventId ].push({
setter: setter,
price: setter.data('tm-price-for-late'),
original_price: setter.data('tm-original-price-for-late'),
bundleid: bundleid,
pricetype: get_price_type(currentEpoObject, setter)
});
});
}
if(currentEpoObject.associated_connect&&currentEpoObject.associated_connect.length===1){
associatedSetter=currentEpoObject.associated_connect;
if(currentEpoObject.associated_connect.is('select')){
associatedSetter=currentEpoObject.associated_connect.find('option:selected');
}}
if(productPrice===false){
totalsHolder.data('tm-floating-box-data', []);
totalsHolder.empty();
if(currentEpoObject.associated_connect&&currentEpoObject.associated_connect.length===1){
tm_force_update_price(
associatedSetter
.closest('.tmcp-field-wrap')
.find('.tc-price')
.not(tcAPI.associatedEpoSelector + ' .tc-price'),
0,
'',
0,
''
);
}
main_cart.trigger('tm-epo-short-update', {
container: cartContainer
});
return;
}
elementQty=$.epoAPI.applyFilter('tcAlterElementQty', elementQty, {
epo: currentEpoObject,
alternativeCart: alternativeCart,
currentCart: currentCart,
main_product: main_product
});
if(currentCart.data('per_product_pricing')!==undefined){
perProductPricing=currentCart.data('per_product_pricing');
}
perProductPricing=$.epoAPI.applyFilter('tcCalculatePerProductPricing', perProductPricing, {
epo: currentEpoObject,
alternativeCart: alternativeCart,
cart: cart,
main_product: main_product
});
if(main_epo_inside_form&&TMEPOJS.tm_epo_totals_box_placement==='woocommerce_before_add_to_cart_button'){
if(( this_product_type==='variable'||this_product_type==='variable-subscription')&&! totalsHolder.data('moved_inside')){
totalsHolder.data('moved_inside', 1);
}}
jWindow.trigger('tcEpoBeforeOptionPriceCalculation', {
epo: currentEpoObject,
alternativeCart: currentEpoObject,
this_product_type: this_product_type,
cart: cart,
totalsHolder: totalsHolder,
fetchOptionPrices: fetchOptionPrices,
epoHolder: epoHolder,
total: total,
original_total: original_total,
floatingBoxData: floatingBoxData,
showTotal: showTotal,
cart_fee_options_total: cart_fee_options_total,
cart_fee_options_original_total: cart_fee_options_original_total
});
if(! currentEpoObject.associated_connect&&! event.noassociated){
if(TMEPOJS.tm_epo_global_product_element_quantity_sync==='yes'&&! cart.is($.tcAPI().associatedEpoCart)){
cart.find($.tcAPI().associatedEpoCart).filter(':visible').toArray().forEach(function(acart){
$(acart).trigger({
type: 'tm-epo-update',
noassociated: 1
});
});
}}
fetch=fetchOptionPrices(currentEpoObject, epoHolder, '.tmcp-field:not(.tc-epo-field-product, .tc-is-math-special, .tc-is-math-cumulative)', total, original_total, floatingBoxData, showTotal);
total=fetch.total;
original_total=fetch.original_total;
floatingBoxData=fetch.floatingBoxData;
showTotal=fetch.showTotal;
elementsLength=fetch.elementsLength;
fetch=fetchOptionPrices(currentEpoObject, epoHolder, '.tc-epo-field-product', productFieldSyncTotal, productFieldSyncOriginalTotal, floatingBoxData, showTotal);
productFieldSyncTotal=fetch.total;
productFieldSyncOriginalTotal=fetch.original_total;
productFieldSyncTotalTaxed=fetch.total_taxed;
productFieldSyncOriginalTotalTaxed=fetch.original_total_taxed;
productFieldSyncVatTotal=fetch.vat_total;
floatingBoxData=fetch.floatingBoxData;
showTotal=showTotal&&fetch.showTotal;
elementsLength=elementsLength + fetch.elementsLength;
totalsHolder.data('tm-floating-box-data', floatingBoxData);
fetch=fetchOptionPrices(currentEpoObject, epoHolder, '.tmcp-fee-field', cart_fee_options_total, cart_fee_options_original_total, floatingBoxData, showTotal, false, true);
cart_fee_options_total=fetch.total;
cart_fee_options_original_total=fetch.original_total;
floatingBoxData=fetch.floatingBoxData;
showTotal=fetch.showTotal;
elementsLength=elementsLength + fetch.elementsLength;
jWindow.trigger('tcEpoAfterOptionPriceCalculation', {
epo: currentEpoObject,
alternativeCart: currentEpoObject,
this_product_type: this_product_type,
cart: cart,
totalsHolder: totalsHolder,
fetchOptionPrices: fetchOptionPrices,
epoHolder: epoHolder,
total: total,
original_total: original_total,
floatingBoxData: floatingBoxData,
showTotal: showTotal,
cart_fee_options_total: cart_fee_options_total,
cart_fee_options_original_total: cart_fee_options_original_total
});
$.tcepo.oneOptionIsSelected[ epoEventId ]=showTotal;
currentEpoObject=addShowHidetoEpoObject(currentEpoObject, epoEventId, elementsLength);
tm_show_hide_add_to_cart_button(main_product, currentEpoObject);
_total=total;
_original_total=original_total;
late_total_price=add_late_fields_prices(currentEpoObject, parseFloat(productPrice), parseFloat(rawProductRegularPrice), parseFloat(_total + productFieldSyncTotal), parseFloat(_original_total + productFieldSyncOriginalTotal), bundleid, totalsHolder);
fetch=fetchOptionPrices(currentEpoObject, epoHolder, '.tmcp-field.tc-is-math-special', total, original_total, floatingBoxData, showTotal, undefined, undefined, undefined, true);
total=fetch.total;
original_total=fetch.original_total;
floatingBoxData=fetch.floatingBoxData;
showTotal=fetch.showTotal;
elementsLength=fetch.elementsLength;
_total=total;
_original_total=original_total;
_total=_total + late_total_price.normal[ 0 ];
_original_total=_original_total + late_total_price.normal[ 1 ];
cart_fee_options_total=cart_fee_options_total + late_total_price.fees[ 0 ];
cart_fee_options_original_total=cart_fee_options_original_total + late_total_price.fees[ 1 ];
total=_total;
original_total=_original_total;
fetch=fetchOptionPrices(currentEpoObject, epoHolder, '.tmcp-field.tc-is-math-cumulative', total, original_total, floatingBoxData, showTotal, undefined, undefined, undefined, true, true);
total=fetch.total;
original_total=fetch.original_total;
floatingBoxData=fetch.floatingBoxData;
showTotal=fetch.showTotal;
elementsLength=fetch.elementsLength;
_total=total;
_original_total=original_total;
if(cart_fee_options_total > 0){
showTotal=true;
}
if(alternativeCart&&! perProductPricing){
showTotal=false;
}
if(finalTotalBoxMode==='enable' ||
finalTotalBoxMode==='hideifoptionsiszero' ||
finalTotalBoxMode==='hideiftotaliszero'
){
showTotal=true;
}
if(cartQty > 1){
showTotal=true;
}
if(( this_product_type==='variable'||this_product_type==='variable-subscription')&&! $.epoAPI.math.toFloat(currentVariation)){
showTotal=false;
}
if(finalTotalBoxMode==='disable'){
showTotal=false;
}
if(TMEPOJS.tm_epo_change_variation_price==='yes'||TMEPOJS.tm_epo_change_original_price==='yes'){
showTotal=true;
}
if(currentEpoObject.is_associated&&! perProductPricing){
showTotal=false;
}
if(TMEPOJS.tm_epo_total_price_as_unit_price==='yes'){
cartQty=1;
}
product_total_price=parseFloat(productPrice * cartQty);
if(TMEPOJS.extraFee){
extraFee=parseFloat(TMEPOJS.extraFee);
if(! Number.isFinite(extraFee)){
extraFee=0;
}}
calculateFinalProductPrice=$.epoAPI.applyFilter('tcCalculateFinalProductPrice', false, {
alternativeCart: alternativeCart,
product_price: productPrice,
product_total_price: product_total_price,
v_product_price: rawProductPrice,
tm_set_tax_price: tm_set_tax_price,
main_product: main_product,
totalsHolder: totalsHolder,
cartQty: cartQty
});
if(calculateFinalProductPrice!==false &&
typeof calculateFinalProductPrice==='object' &&
Object.prototype.hasOwnProperty.call(calculateFinalProductPrice, 'productPrice') &&
Object.prototype.hasOwnProperty.call(calculateFinalProductPrice, 'productTotalPrice')
){
productPrice=calculateFinalProductPrice.productPrice;
product_total_price=calculateFinalProductPrice.productTotalPrice;
}
_total=$.epoAPI.applyFilter('tc_adjust_options_price_per_unit', _total, product_total_price);
total=parseFloat(_total * cartQty * elementQty);
total=$.epoAPI.applyFilter('tc_adjust_options_total_price', total, cartQty, elementQty, _total, totalsHolder);
if(TMEPOJS.tm_epo_global_product_element_quantity_sync==='no'){
totalProductField=parseFloat(productFieldSyncTotal);
totalProductFieldTaxed=parseFloat(productFieldSyncTotalTaxed);
}else{
totalProductField=parseFloat(productFieldSyncTotal * cartQty * elementQty);
totalProductFieldTaxed=parseFloat(productFieldSyncTotalTaxed * cartQty * elementQty);
}
totalProductField=$.epoAPI.applyFilter('tc_adjust_options_productfield_total_price', totalProductField, cartQty, elementQty, _total, totalsHolder);
totalProductFieldTaxed=$.epoAPI.applyFilter('tc_adjust_options_productfield_total_price_taxed', totalProductFieldTaxed, cartQty, elementQty, _total, totalsHolder);
_original_total=$.epoAPI.applyFilter('tc_adjust_options_price_per_unit', _original_total, product_total_price);
original_total=parseFloat(_original_total * cartQty * elementQty);
original_total=$.epoAPI.applyFilter('tc_adjust_options_original_total_price', original_total, cartQty, elementQty, _original_total, totalsHolder);
if(TMEPOJS.tm_epo_global_product_element_quantity_sync==='no'){
originalTotalProductField=parseFloat(productFieldSyncOriginalTotal);
originalTotalProductFieldTaxed=parseFloat(productFieldSyncOriginalTotalTaxed);
}else{
originalTotalProductField=parseFloat(productFieldSyncOriginalTotal * cartQty * elementQty);
originalTotalProductFieldTaxed=parseFloat(productFieldSyncOriginalTotalTaxed * cartQty * elementQty);
}
originalTotalProductField=$.epoAPI.applyFilter('tc_adjust_options_productfield_original_total_price', originalTotalProductField, cartQty, elementQty, _original_total, totalsHolder);
originalTotalProductFieldTaxed=$.epoAPI.applyFilter('tc_adjust_options_productfield_original_total_price_taxed', originalTotalProductFieldTaxed, cartQty, elementQty, _original_total, totalsHolder);
if(priceOverrideMode==='1'&&parseFloat(total) > 0){
productPrice=0;
rawProductPrice=0;
product_total_price=0;
}
product_total_price=$.epoAPI.applyFilter('tc_adjust_product_total_price_without_options', product_total_price);
total=$.epoAPI.applyFilter('tcAdjustTotal', total, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
cart: cart,
main_product: main_product
});
totalProductField=$.epoAPI.applyFilter('tcAdjustProductFieldTotal', totalProductField, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
cart: cart,
main_product: main_product
});
totalProductFieldTaxed=$.epoAPI.applyFilter('tcAdjustProductFieldTotalTaxed', totalProductFieldTaxed, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
cart: cart,
main_product: main_product
});
original_total=$.epoAPI.applyFilter('tcAdjustOriginalTotal', original_total, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
cart: cart,
main_product: main_product
});
originalTotalProductField=$.epoAPI.applyFilter('tcAdjustProductFieldOriginalTotal', originalTotalProductField, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
cart: cart,
main_product: main_product
});
originalTotalProductFieldTaxed=$.epoAPI.applyFilter('tcAdjustProductFieldOriginalTotalTaxed', originalTotalProductFieldTaxed, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
cart: cart,
main_product: main_product
});
total=parseFloat($.epoAPI.applyFilter('tc_adjust_total', total, totalsHolder));
cart_fee_options_total=parseFloat($.epoAPI.applyFilter('tc_adjust_totals_fee', cart_fee_options_total, totalsHolder));
original_total=parseFloat($.epoAPI.applyFilter('tc_adjust_original_total', original_total, totalsHolder));
cart_fee_options_original_total=parseFloat($.epoAPI.applyFilter('tc_adjust_original_total_fee', cart_fee_options_original_total, totalsHolder));
raw_extraFee=extraFee;
total_plus_fee=total + cart_fee_options_total;
original_total_plus_fee=original_total + cart_fee_options_original_total;
raw_total=total;
raw__total=_total;
raw_cart_fee_options_total=cart_fee_options_total;
raw_total_plus_fee=total_plus_fee;
raw_original_total=original_total;
raw__original_total=_original_total;
raw_cart_fee_options_original_total=cart_fee_options_original_total;
raw_original_total_plus_fee=original_total_plus_fee;
raw_product_total_price_without_options=product_total_price;
raw_product_total_price=parseFloat(product_total_price + total_plus_fee + raw_extraFee);
raw_product_total_original_price=parseFloat(rawProductRegularPrice + original_total_plus_fee + raw_extraFee);
productPrice=tm_set_tax_price(productPrice, totalsHolder, undefined, undefined, undefined, undefined, true);
productRegularPrice=tm_set_tax_price(productRegularPrice, totalsHolder, undefined, undefined, undefined, undefined, true);
product_total_price=tm_set_tax_price(product_total_price, totalsHolder, undefined, undefined, undefined, undefined, true);
total=tm_set_tax_price(total, totalsHolder, undefined, undefined, undefined, undefined, true);
_total=tm_set_tax_price(_total, totalsHolder, undefined, undefined, undefined, undefined, true);
cart_fee_options_total=tm_set_tax_price(cart_fee_options_total, totalsHolder, undefined, undefined, undefined, undefined, true);
total_plus_fee=parseFloat(cart_fee_options_total) + parseFloat(total);
original_total=tm_set_tax_price(original_total, totalsHolder, undefined, undefined, undefined, undefined, true);
_original_total=tm_set_tax_price(_original_total, totalsHolder, undefined, undefined, undefined, undefined, true);
cart_fee_options_original_total=tm_set_tax_price(cart_fee_options_original_total, totalsHolder, undefined, undefined, undefined, undefined, true);
original_total_plus_fee=parseFloat(cart_fee_options_original_total) + parseFloat(original_total);
extraFee=tm_set_tax_price(extraFee, totalsHolder, undefined, undefined, undefined, undefined, true);
product_total_price_without_options=product_total_price;
product_total_price=$.epoAPI.applyFilter('tc_adjust_product_total_price', parseFloat(product_total_price + total_plus_fee + extraFee), product_total_price_without_options, total_plus_fee, extraFee, total, cart_fee_options_total, totalsHolder);
product_total_original_price=$.epoAPI.applyFilter('tc_adjust_product_total_original_price', parseFloat(product_total_price_without_options + original_total_plus_fee + extraFee), product_total_price_without_options, original_total_plus_fee, extraFee, original_total, cart_fee_options_original_total, totalsHolder);
pricesIncludeTax=totalsHolder.attr('data-prices-include-tax')||TMEPOJS.prices_include_tax;
if(pricesIncludeTax==='1'){
vat_options_total=productFieldSyncVatTotal + parseFloat(calculateTaxAmount(total, totalsHolder));
vat_options_total_plus_fee=productFieldSyncVatTotal + parseFloat(calculateTaxAmount(total_plus_fee, totalsHolder));
vat_total=productFieldSyncVatTotal + parseFloat(calculateTaxAmount(product_total_price, totalsHolder));
vat_product_base=parseFloat(calculateTaxAmount(product_total_price_without_options, totalsHolder));
}else{
vat_options_total=productFieldSyncVatTotal + parseFloat(total - raw_total);
vat_options_total_plus_fee=productFieldSyncVatTotal + parseFloat(total_plus_fee - raw_total_plus_fee);
vat_total=productFieldSyncVatTotal + parseFloat(product_total_price - raw_product_total_price);
vat_product_base=parseFloat(product_total_price_without_options - raw_product_total_price_without_options);
}
raw_total=raw_total + totalProductField;
raw__total=raw__total + totalProductField;
raw_total_plus_fee=raw_total_plus_fee + totalProductField;
raw_original_total=raw_original_total + originalTotalProductField;
raw__original_total=raw__original_total + originalTotalProductField;
raw_original_total_plus_fee=raw_original_total_plus_fee + originalTotalProductField;
raw_product_total_price=raw_product_total_price + totalProductField;
raw_product_total_original_price=raw_product_total_original_price + originalTotalProductField;
total=total + totalProductFieldTaxed;
_total=_total + totalProductFieldTaxed;
total_plus_fee=total_plus_fee + totalProductFieldTaxed;
original_total=original_total + originalTotalProductFieldTaxed;
_original_total=_original_total + originalTotalProductFieldTaxed;
original_total_plus_fee=original_total_plus_fee + originalTotalProductFieldTaxed;
product_total_price=product_total_price + totalProductFieldTaxed;
product_total_original_price=product_total_original_price + originalTotalProductFieldTaxed;
unit_price=parseFloat(productPrice + parseFloat(_total));
unit_original_price=parseFloat(productPrice + parseFloat(_original_total));
if(TMEPOJS.tm_epo_fees_on_unit_price==='yes'){
unit_price=parseFloat(productPrice + parseFloat(_total) + parseFloat(parseFloat(cart_fee_options_total) / cartQty));
unit_original_price=parseFloat(productPrice + parseFloat(_original_total) + parseFloat(parseFloat(cart_fee_options_original_total) / cartQty));
}
formatted_unit_price=tm_set_price_totals(parseFloat(productPrice + parseFloat(_total) + parseFloat(parseFloat(cart_fee_options_total) / cartQty)), totalsHolder, true, true);
formatted_unit_original_price=tm_set_price_totals(parseFloat(productPrice + parseFloat(_original_total) + parseFloat(parseFloat(cart_fee_options_original_total) / cartQty)), totalsHolder, true, true);
if(extraFee){
show_extra_fee=true;
formatted_extra_fee=tm_set_price_totals(extraFee, totalsHolder, true, true);
}
formatted_final_total=tm_set_price_totals(product_total_price, totalsHolder, true, true);
formatted_final_original_total=tm_set_price_totals(product_total_original_price, totalsHolder, true, true);
formatted_options_total=tm_set_price_totals(total, totalsHolder, true, true);
formatted_fees_total=tm_set_price_totals(cart_fee_options_total, totalsHolder, true, true);
formatted_options_original_total=tm_set_price_totals(original_total, totalsHolder, true, true);
formatted_fees_original_total=tm_set_price_totals(cart_fee_options_original_total, totalsHolder, true, true);
formatted_vat_options_total=tm_set_price_totals(vat_options_total);
formatted_vat_options_total_plus_fee=tm_set_price_totals(vat_options_total_plus_fee);
formatted_vat_total=tm_set_price_totals(vat_total);
formatted_vat_product_base=tm_set_price_totals(vat_product_base);
formatted_unit_price=$.epoAPI.applyFilter('tc_adjust_formatted_unit_price', formatted_unit_price, productPrice, _total, cart_fee_options_total, cartQty);
formatted_options_total=$.epoAPI.applyFilter('tc_adjust_formatted_options_total', formatted_options_total, total, _total, cartQty);
formatted_fees_total=$.epoAPI.applyFilter('tc_adjust_formatted_fees_total', formatted_fees_total, cart_fee_options_total);
formatted_final_total=$.epoAPI.applyFilter('tc_adjust_formatted_final_total', formatted_final_total, product_total_price, product_total_price_without_options, total_plus_fee, extraFee, cartQty);
formatted_unit_price=$.epoAPI.applyFilter('tcAdjustFormattedUnitPrice', formatted_unit_price, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
event: event,
unit_price: unit_price,
productPrice: productPrice,
_total: _total,
total_plcart_fee_options_totals_fee: cart_fee_options_total,
cartQty: cartQty
});
formatted_unit_original_price=$.epoAPI.applyFilter('tcAdjustFormattedUnitOriginalPrice', formatted_unit_original_price, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
event: event,
unit_original_price: unit_original_price,
productPrice: productPrice,
_original_total: _original_total,
total_plcart_fee_options_totals_fee: cart_fee_options_total,
cartQty: cartQty
});
formatted_options_total=$.epoAPI.applyFilter('tcAdjustFormattedOptionsTotal', formatted_options_total, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
event: event,
total: total,
_total: _total,
total_plus_fee: total_plus_fee,
extraFee: extraFee,
cartQty: cartQty
});
formatted_options_original_total=$.epoAPI.applyFilter('tcAdjustFormattedOptionsOriginalTotal', formatted_options_original_total, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
event: event,
original_total: original_total,
_original_total: _original_total,
original_total_plus_fee: original_total_plus_fee,
extraFee: extraFee,
cartQty: cartQty
});
formatted_fees_total=$.epoAPI.applyFilter('tcAdjustFormattedFeesTotal', formatted_fees_total, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
event: event,
cart_fee_options_total: cart_fee_options_total,
extraFee: extraFee,
cartQty: cartQty
});
formatted_fees_original_total=$.epoAPI.applyFilter('tcAdjustFormattedFeesOriginalTotal', formatted_fees_original_total, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
event: event,
cart_fee_options_original_total: cart_fee_options_original_total,
extraFee: extraFee,
cartQty: cartQty
});
formatted_final_total=$.epoAPI.applyFilter('tcAdjustFormattedFinalTotal', formatted_final_total, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
event: event,
product_total_price: product_total_price,
product_total_price_without_options: product_total_price_without_options,
total_plus_fee: total_plus_fee,
extraFee: extraFee,
cartQty: cartQty
});
formatted_final_original_total=$.epoAPI.applyFilter('tcAdjustFormattedFinalOriginalTotal', formatted_final_original_total, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
event: event,
product_total_original_price: product_total_original_price,
product_total_price_without_options: product_total_price_without_options,
original_total_plus_fee: original_total_plus_fee,
extraFee: extraFee,
cartQty: cartQty
});
if(( total > 0&&finalTotalBoxShowOptions==='showtgz')||finalTotalBoxShowOptions==='show'){
show_options_total=true;
if(TMEPOJS.tm_epo_enable_vat_options_total==='yes'){
show_vat_options_total=true;
}}
if(cart_fee_options_total!==0){
show_fees_total=true;
}
if(formatted_final_total&&finalTotalBoxShowFinal==='show'){
show_final_total=true;
}
tc_totals_ob={
qty: cartQty,
product_price: productPrice,
raw_product_price: rawProductPrice,
product_regular_price: productRegularPrice,
raw_product_regular_price: rawProductRegularPrice,
formatted_product_price: tm_set_price_totals(parseFloat(productPrice) * cartQty),
late_total_prices: late_total_price,
late_total_price: tm_set_tax_price(late_total_price[ 0 ], totalsHolder),
late_total_original_price: tm_set_tax_price(late_total_price[ 1 ], totalsHolder),
raw_options_price_per_unit: raw__total,
raw_options_total_price: raw_total,
raw_cart_fee_options_total_price: raw_cart_fee_options_total,
raw_total_plus_fee: raw_total_plus_fee,
raw_options_original_price_per_unit: raw__original_total,
raw_options_original_total_price: raw_original_total,
raw_cart_fee_options_original_total_price: raw_cart_fee_options_original_total,
raw_original_total_plus_fee: raw_original_total_plus_fee,
raw_product_total_price: raw_product_total_price,
raw_product_total_original_price: raw_product_total_original_price,
raw_product_total_price_without_options: raw_product_total_price_without_options,
options_price_per_unit: _total,
options_total_price: total,
cart_fee_options_total_price: cart_fee_options_total,
total_plus_fee: total_plus_fee,
options_original_price_per_unit: _original_total,
options_original_total_price: original_total,
cart_fee_options_total_original_price: cart_fee_options_original_total,
original_total_plus_fee: original_total_plus_fee,
vat_options_total: vat_options_total,
vat_options_total_plus_fee: vat_options_total_plus_fee,
formatted_vat_options_total: formatted_vat_options_total,
formatted_vat_options_total_plus_fee: formatted_vat_options_total_plus_fee,
vat_total: vat_total,
formatted_vat_total: formatted_vat_total,
vat_product_base: vat_product_base,
formatted_vat_product_base: formatted_vat_product_base,
product_total_price: product_total_price,
product_total_original_price: product_total_original_price,
product_total_price_without_options: product_total_price_without_options,
product_unit_price: unit_price,
product_unit_original_price: unit_original_price,
formatted_unit_price: formatted_unit_price,
formatted_options_total: formatted_options_total,
formatted_fees_total: formatted_fees_total,
formatted_final_total: formatted_final_total,
formatted_unit_original_price: formatted_unit_original_price,
formatted_options_original_total: formatted_options_original_total,
formatted_fees_original_total: formatted_fees_original_total,
formatted_final_original_total: formatted_final_original_total,
formatted_extra_fee: formatted_extra_fee,
show_options_total: show_options_total,
show_fees_total: show_fees_total,
show_extra_fee: show_extra_fee,
show_final_total: show_final_total,
show_options_vat: show_vat_options_total,
unit_price: TMEPOJS.i18n_unit_price,
show_unit_price: TMEPOJS.tm_epo_show_unit_price==='yes',
options_total: TMEPOJS.i18n_options_total,
fees_total: TMEPOJS.i18n_fees_total,
extra_fee: TMEPOJS.i18n_extra_fee,
final_total: TMEPOJS.i18n_final_total,
options_vat_total: TMEPOJS.i18n_vat_options_total,
totals_box_before_unit_price: TMEPOJS.totals_box_before_unit_price,
totals_box_after_unit_price: TMEPOJS.totals_box_after_unit_price,
totals_box_before_vat_options_totals_price: TMEPOJS.totals_box_before_vat_options_totals_price,
totals_box_after_vat_options_totals_price: TMEPOJS.totals_box_after_vat_options_totals_price,
totals_box_before_options_totals_price: TMEPOJS.totals_box_before_options_totals_price,
totals_box_after_options_totals_price: TMEPOJS.totals_box_after_options_totals_price,
totals_box_before_fee_totals_price: TMEPOJS.totals_box_before_fee_totals_price,
totals_box_after_fee_totals_price: TMEPOJS.totals_box_after_fee_totals_price,
totals_box_before_extra_fee_price: TMEPOJS.totals_box_before_extra_fee_price,
totals_box_after_extra_fee_price: TMEPOJS.totals_box_after_extra_fee_price,
totals_box_before_final_totals_price: TMEPOJS.totals_box_before_final_totals_price,
totals_box_after_final_totals_price: TMEPOJS.totals_box_after_final_totals_price
};
if(TMEPOJS.customer_price_format){
customer_price_format_wrap_start=TMEPOJS.customer_price_format_wrap_start;
customer_price_format_wrap_end=TMEPOJS.customer_price_format_wrap_end;
customerPriceFormat=TMEPOJS.customer_price_format;
}
if(formatted_options_total&&total > 0){
_ftotal=formatPrice(total);
_foriginal_total=formatPrice(original_total);
if(customerPriceFormat){
_ftotal=customerPriceFormat.replace('__PRICE__', _ftotal).replace('__CODE__', TMEPOJS.current_currency);
if(! totalsHolder.data('is-on-sale')){
_foriginal_total=customerPriceFormat.replace('__PRICE__', _foriginal_total).replace('__CODE__', TMEPOJS.current_currency);
}}
_ftotal=$.epoAPI.applyFilter('tcFilterFormattedFTotal', _ftotal, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
event: event,
total: total,
_total: _total,
total_plus_fee: total_plus_fee,
extraFee: extraFee,
cartQty: cartQty
});
_foriginal_total=$.epoAPI.applyFilter('tcFilterFormattedFOriginalTotal', _foriginal_total, {
epo: currentEpoObject,
totalsHolder: totalsHolder,
event: event,
original_total: original_total,
total: original_total,
_total: _total,
total_plus_fee: total_plus_fee,
extraFee: extraFee,
cartQty: cartQty
});
if(TMEPOJS.tm_epo_enable_original_final_total==='yes'&&total!==original_total){
tc_totals_ob.formatted_options_total=$.epoAPI.util.decodeHTML($.epoAPI.template.html(tcAPI.templateEngine.tc_formatted_sale_price, {
price: _foriginal_total,
sale_price: _ftotal,
customer_price_format_wrap_start: customer_price_format_wrap_start,
customer_price_format_wrap_end: customer_price_format_wrap_end
})
);
tc_totals_ob._foriginal_total=_foriginal_total;
tc_totals_ob._ftotal=_ftotal;
}else{
tc_totals_ob.formatted_options_total=$.epoAPI.util.decodeHTML($.epoAPI.util.decodeHTML($.epoAPI.template.html(tcAPI.templateEngine.tc_formatted_price, {
price: _ftotal,
customer_price_format_wrap_start: customer_price_format_wrap_start,
customer_price_format_wrap_end: customer_price_format_wrap_end
})
)
);
}}
if(formatted_final_total&&product_total_price >=0){
_fprice=formatPrice(product_total_price);
if(priceOverrideMode==='1'&&parseFloat(total) > 0){
_f_regular_price=parseFloat(raw_original_total_plus_fee + extraFee);
}else{
_f_regular_price=parseFloat(parseFloat(rawProductRegularPrice * cartQty) + raw_original_total_plus_fee + extraFee);
}
if(customerPriceFormat){
_fprice=customerPriceFormat.replace('__PRICE__', _fprice).replace('__CODE__', TMEPOJS.current_currency);
if(! totalsHolder.data('is-on-sale')){
_f_regular_price=customerPriceFormat.replace('__PRICE__', _f_regular_price).replace('__CODE__', TMEPOJS.current_currency);
}}
_fprice=$.epoAPI.applyFilter('tc_adjust_native_price', _fprice, product_total_price);
_f_regular_price=tm_set_tax_price(_f_regular_price, totalsHolder, undefined, undefined, undefined, undefined, true);
_f_regular_price=formatPrice(_f_regular_price);
_f_regular_price=$.epoAPI.applyFilter('tc_adjust_native_regular_price', _f_regular_price, product_total_price);
if(TMEPOJS.tm_epo_enable_original_final_total==='yes'&&(( totalsHolder.data('is-on-sale')&&priceOverrideMode!=='1')||_f_regular_price!==_fprice)){
tc_totals_ob.formatted_final_total=$.epoAPI.util.decodeHTML($.epoAPI.template.html(tcAPI.templateEngine.tc_formatted_sale_price, {
price: _f_regular_price,
sale_price: _fprice,
customer_price_format_wrap_start: customer_price_format_wrap_start,
customer_price_format_wrap_end: customer_price_format_wrap_end
})
);
}else{
tc_totals_ob.formatted_final_total=$.epoAPI.util.decodeHTML($.epoAPI.util.decodeHTML($.epoAPI.template.html(tcAPI.templateEngine.tc_formatted_price, {
price: _fprice,
customer_price_format_wrap_start: customer_price_format_wrap_start,
customer_price_format_wrap_end: customer_price_format_wrap_end
})
)
);
}
tc_totals_ob._f_regular_price=_f_regular_price;
tc_totals_ob._fprice=_fprice;
}
tc_totals_ob=replace_suffixes('formatted_fees_original_total', 'cart_fee_options_total_original_price', tc_totals_ob, totalsHolder);
tc_totals_ob=replace_suffixes('formatted_fees_total', 'cart_fee_options_total_price', tc_totals_ob, totalsHolder);
tc_totals_ob=replace_suffixes('formatted_final_original_total', 'product_total_original_price', tc_totals_ob, totalsHolder);
tc_totals_ob=replace_suffixes('formatted_final_total', 'product_total_price', tc_totals_ob, totalsHolder);
tc_totals_ob=replace_suffixes('formatted_options_original_total', 'options_original_total_price', tc_totals_ob, totalsHolder);
tc_totals_ob=replace_suffixes('formatted_options_total', 'options_total_price', tc_totals_ob, totalsHolder);
tc_totals_ob=replace_suffixes('formatted_unit_original_price', 'product_unit_original_price', tc_totals_ob, totalsHolder);
tc_totals_ob=replace_suffixes('formatted_unit_price', 'product_unit_price', tc_totals_ob, totalsHolder);
if($.tcepo.showHideTotal!==undefined&&$.tcepo.showHideTotal[ epoEventId ]!==undefined){
showTotal=$.tcepo.showHideTotal[ epoEventId ];
}
tc_totals_ob=$.epoAPI.applyFilter('tc_adjust_tc_totals_ob', tc_totals_ob, {
epo_object: currentEpoObject,
showTotal: showTotal,
epoHolder: epoHolder,
totalsHolder: totalsHolder,
tm_set_price: tm_set_price,
tm_set_price_totals: tm_set_price_totals,
product_total_price: product_total_price,
product_price: productPrice,
qty: cartQty
});
if(tc_totals_ob.showTotal!==undefined){
showTotal=tc_totals_ob.showTotal;
}
currentEpoObject.tc_totals_ob=tc_totals_ob;
showTotal=$.epoAPI.applyFilter('tcFinalTotalsBoxVisibility', showTotal, {
epo: currentEpoObject,
alternativeCart: alternativeCart,
cart: cart,
main_product: main_product,
totalsHolder: totalsHolder,
this_epo_totals_container: this_epo_totals_container
});
html=$.epoAPI.template.html(tcAPI.templateEngine.tc_final_totals, tc_totals_ob);
totalsHolder.data('tm-html', html);
totalsHolder.data('tc_totals_ob', tc_totals_ob);
if(currentEpoObject.associated_connect&&currentEpoObject.associated_connect.length===1){
if(currentEpoObject.associated_connect.attr('data-no-price')==='1'){
associatedPrice=0;
associatedRawPrice=0;
associatedOriginalPrice=0;
associatedRawOriginalPrice=0;
associatedFormattedPrice='';
associatedFormattedOriginalPrice='';
tm_force_update_price(
associatedSetter
.closest('.tmcp-field-wrap')
.find('.tc-price')
.not(tcAPI.associatedEpoSelector + ' .tc-price'),
associatedPrice,
associatedFormattedPrice,
associatedOriginalPrice,
associatedFormattedOriginalPrice
);
}else{
associatedPrice=tc_totals_ob.product_price + tc_totals_ob.options_price_per_unit +(tc_totals_ob.cart_fee_options_total_price / tc_totals_ob.qty);
associatedRawPrice=tc_totals_ob.raw_product_price + tc_totals_ob.raw_options_price_per_unit +(tc_totals_ob.raw_cart_fee_options_total_price / tc_totals_ob.qty);
associatedOriginalPrice=tc_totals_ob.product_regular_price + tc_totals_ob.options_original_price_per_unit +(tc_totals_ob.cart_fee_options_total_original_price / tc_totals_ob.qty);
associatedRawOriginalPrice=tc_totals_ob.raw_product_regular_price + tc_totals_ob.raw_options_original_price_per_unit +(tc_totals_ob.raw_cart_fee_options_original_total_price / tc_totals_ob.qty);
associatedFormattedPrice=tm_set_price(associatedPrice, currentEpoObject.this_epo_totals_containe, false, false, associatedSetter);
associatedFormattedOriginalPrice=tm_set_price(associatedOriginalPrice, currentEpoObject.this_epo_totals_containe, false, false, associatedSetter);
tm_force_update_price(
associatedSetter
.closest('.tmcp-field-wrap')
.find('.tc-price')
.not(tcAPI.associatedEpoSelector + ' .tc-price'),
associatedPrice,
associatedFormattedPrice,
associatedOriginalPrice,
associatedFormattedOriginalPrice
);
currentEpoObject.associated_connect.data('tm-quantity', tc_totals_ob.qty);
if(currentEpoObject.associated_connect.data('tm-quantity')){
associatedPrice=associatedPrice * parseFloat(currentEpoObject.associated_connect.data('tm-quantity'));
associatedRawPrice=associatedRawPrice * parseFloat(currentEpoObject.associated_connect.data('tm-quantity'));
associatedOriginalPrice=associatedOriginalPrice * parseFloat(currentEpoObject.associated_connect.data('tm-quantity'));
associatedRawOriginalPrice=associatedRawOriginalPrice * parseFloat(currentEpoObject.associated_connect.data('tm-quantity'));
}
associatedFormattedPrice=tm_set_price(associatedPrice, currentEpoObject.this_epo_totals_containe, false, false, associatedSetter);
associatedFormattedOriginalPrice=tm_set_price(associatedOriginalPrice, currentEpoObject.this_epo_totals_containe, false, false, associatedSetter);
}
currentEpoObject.associated_connect.data('price_set', 1);
if(associatedSetter.is('.tcenabled')){
associatedSetter.data('associated_price_set', 1);
}
associatedSetter.data('price_set', 1);
associatedSetter.data('raw_price', associatedRawPrice);
associatedSetter.data('raw_original_price', associatedRawOriginalPrice);
associatedSetter.data('price', tm_set_tax_price(associatedPrice, currentEpoObject.this_epo_totals_containe, associatedSetter));
associatedSetter.data('original_price', tm_set_tax_price(associatedOriginalPrice, currentEpoObject.this_epo_totals_containe, associatedSetter));
currentEpoObject.associated_connect.data('price-changed', 1);
setTimeout(function(){
if(!(currentEpoObject.associated_connect&&event.noassociated)){
currentEpoObject.mainEpoObject.main_cart.trigger({
type: 'tm-epo-update',
norules: 2
});
}}, 20);
}
jWindow.trigger('tcEpoAfterCalculateTotals', {
epo: currentEpoObject,
alternativeCart: alternativeCart,
this_product_type: this_product_type,
cart: cart,
bundleid: bundleid,
totalsObject: tc_totals_ob,
main_product: main_product,
per_product_pricing: perProductPricing
});
hide_native_price=$.epoAPI.applyFilter('hide_native_price', true);
if(cartQty > 0){
if(TMEPOJS.tm_epo_change_variation_price==='yes'){
if(hide_native_price===true&&finalTotalBoxMode!=='disable'){
tm_get_native_prices_block(cart).hide();
}else{
tm_get_native_prices_block(cart).show();
}}
if(! showTotal ||
finalTotalBoxMode==='disable' ||
(finalTotalBoxMode==='hideiftotaliszero'&&product_total_price===0) ||
(finalTotalBoxMode==='hideifoptionsiszero'&&total_plus_fee===0)
){
html='';
totalsHolder.html(html);
totalsHolder.data('tm-floating-box-data', []);
}else{
totalsHolder.html(html);
jWindow.trigger('tc-totals-container', {
epo: tc_totals_ob,
totals_holder: totalsHolder,
data: {
epo_object: currentEpoObject,
tm_set_price: tm_set_price,
tm_set_price_totals: tm_set_price_totals,
product_total_price: product_total_price,
product_price: productPrice,
qty: cartQty
},
tm_epo_js: TMEPOJS
});
}
if(formatted_final_total&&product_total_price >=0){
update_native_html=tm_get_native_prices_block(cart);
if(TMEPOJS.tm_epo_change_variation_price==='yes'){
if(totalsHolder.data('is-on-sale')){
temp=$.epoAPI.util.decodeHTML($.epoAPI.template.html(tcAPI.templateEngine.tc_formatted_sale_price, {
price: _f_regular_price,
sale_price: _fprice,
customer_price_format_wrap_start: customer_price_format_wrap_start,
customer_price_format_wrap_end: customer_price_format_wrap_end,
before_price_text: TMEPOJS.variation_price_before_price_text,
after_price_text: TMEPOJS.variation_price_after_price_text
})
);
temp={
formatted: temp,
raw: tc_totals_ob.product_total_price
};
temp=replace_suffixes('formatted', 'raw', temp, totalsHolder);
temp=temp.formatted;
update_native_html
.html(temp)
.show();
}else{
temp=$.epoAPI.util.decodeHTML($.epoAPI.template.html(tcAPI.templateEngine.tc_formatted_price, {
price: _fprice,
customer_price_format_wrap_start: customer_price_format_wrap_start,
customer_price_format_wrap_end: customer_price_format_wrap_end,
before_price_text: TMEPOJS.variation_price_before_price_text,
after_price_text: TMEPOJS.variation_price_after_price_text
})
);
temp={
formatted: temp,
raw: tc_totals_ob.product_total_price
};
temp=replace_suffixes('formatted', 'raw', temp, totalsHolder);
temp=temp.formatted;
update_native_html
.html(temp)
.show();
}}
if(TMEPOJS.tm_epo_change_original_price==='yes'){
if(! alternativeCart||main_product.find('.cpf-bto-price').length===0){
if(currentEpoObject.associated_connect){
nativeProductPriceSelector=currentEpoObject.main_product.find(tcAPI.associatedNativeProductPriceSelector);
}else{
nativeProductPriceSelector=$(tcAPI.nativeProductPriceSelector);
}
if(nativeProductPriceSelector.length===0&&main_product.is('.tc-after-shop-loop')){
nativeProductPriceSelector=main_product.closest('.product').find('.price');
}
if(nativeProductPriceSelector.data('tc-original-html')===undefined){
nativeProductPriceSelector.data('tc-original-html', nativeProductPriceSelector.html());
}
if(product_total_price > 0){
if(totalsHolder.data('is-on-sale')){
temp=$.epoAPI.util.decodeHTML($.epoAPI.template.html(tcAPI.templateEngine.tc_formatted_sale_price, {
price: _f_regular_price,
sale_price: _fprice,
customer_price_format_wrap_start: customer_price_format_wrap_start,
customer_price_format_wrap_end: customer_price_format_wrap_end,
before_price_text: TMEPOJS.product_price_before_price_text,
after_price_text: TMEPOJS.product_price_after_price_text
})
);
temp={
formatted: temp,
raw: tc_totals_ob.product_total_price
};
temp=replace_suffixes('formatted', 'raw', temp, totalsHolder);
temp=temp.formatted;
nativeProductPriceSelector
.html(temp)
.show();
}else{
temp=$.epoAPI.util.decodeHTML($.epoAPI.template.html(tcAPI.templateEngine.tc_formatted_price, {
price: _fprice,
customer_price_format_wrap_start: customer_price_format_wrap_start,
customer_price_format_wrap_end: customer_price_format_wrap_end,
before_price_text: TMEPOJS.product_price_before_price_text,
after_price_text: TMEPOJS.product_price_after_price_text
})
);
temp={
formatted: temp,
raw: tc_totals_ob.product_total_price
};
temp=replace_suffixes('formatted', 'raw', temp, totalsHolder);
temp=temp.formatted;
nativeProductPriceSelector
.html(temp)
.show();
}}else if(this_product_type&&this_product_type!=='composite'){
if(currentEpoObject.associated_connect){
if(currentEpoObject.variations_form.length){
temp=currentEpoObject.this_epo_totals_container.data('variationIdElement');
if(temp.length > 0){
temp=parseFloat(temp.val());
if(!(! temp||temp===0)){
nativeProductPriceSelector.html($.epoAPI.util.decodeHTML(TMEPOJS.assoc_current_free_text));
}}
}else{
nativeProductPriceSelector.html($.epoAPI.util.decodeHTML(TMEPOJS.assoc_current_free_text));
}}else{
nativeProductPriceSelector.html($.epoAPI.util.decodeHTML(TMEPOJS.current_free_text));
}}
}
jWindow.trigger('tcEpoMaybeChangePriceHtml', {
epo: currentEpoObject,
alternativeCart: alternativeCart,
this_product_type: this_product_type,
cart: cart,
bundleid: bundleid,
totalsObject: tc_totals_ob,
main_product: main_product,
nativePrice: _fprice
});
}}
if(alternativeCart){
main_cart.trigger({
type: 'tm-epo-update',
norules: 1
});
}else{
this_epo_totals_container.data('is_active', true);
}}else{
if(currentEpoObject.associated_connect){
nativeProductPriceSelector=currentEpoObject.main_product.find(tcAPI.associatedNativeProductPriceSelector);
nativeProductPriceSelector.html(nativeProductPriceSelector.data('tc-original-html'));
}
tm_get_native_prices_block(cart).each(function(){
var $npb=$(this);
if(! $npb.data('tm-original-html')){
$npb.data('tm-original-html', $npb.html());
}else{
$npb.html($npb.data('tm-original-html'));
}});
if(rawProductPrice===0&&TMEPOJS.tm_epo_remove_free_price_label==='yes'){
tm_get_native_prices_block(cart).hide();
}else if(TMEPOJS.tm_epo_change_variation_price==='yes'&&!(hide_native_price===true&&finalTotalBoxMode!=='disable')){
tm_get_native_prices_block(cart).show();
}
totalsHolder.empty();
if(alternativeCart){
main_cart.trigger({
type: 'tm-epo-update',
norules: 1
});
}}
main_cart.trigger('tm-epo-after-update', {
container: cartContainer
});
jWindow.trigger('tc-epo-after-update', {
epo: tc_totals_ob,
totals_holder: totalsHolder,
data: {
epo_object: currentEpoObject,
add_late_fields_prices: add_late_fields_prices,
tm_set_price: tm_set_price,
tm_set_price_totals: tm_set_price_totals,
product_total_price: product_total_price,
product_price: productPrice,
qty: cartQty,
bundleid: bundleid,
currentCart: currentCart
},
tm_epo_js: TMEPOJS
});
});
if(this_product_type==='variable'||this_product_type==='variable-subscription'){
epoVariationSection=epoHolder.find('.tm-epo-variation-section').first();
epoVariationSection
.find('.tm-epo-reset-variation')
.off('click.cpfv')
.on('click.cpfv', function(){
var field=$(this);
var id=$.epoAPI.dom.id(field.attr('data-tm-for-variation'));
var section=field.closest('.cpf-type-variations');
var inputs=field.closest('.cpf-element').find('.tm-epo-variation-element');
var lis=field.closest('.cpf-element').find('.tmcp-field-wrap');
inputs.prop('checked', false);
lis.removeClass('tc-active');
variationForm
.find("[data-attribute_name='attribute_" + id + "']")
.val('')
.trigger('change');
variationForm.find("[data-attribute_name='attribute_" + id + "']").trigger('focusin');
main_product
.find('.cpf-type-variations')
.not(section)
.each(function(i, el){
variationForm.find("[data-attribute_name='attribute_" + $.epoAPI.dom.id($(el).find('.tm-epo-variation-element').first().attr('data-tm-for-variation')) + "']").trigger('focusin');
});
field.trigger('blur');
variationForm.trigger('woocommerce_update_variation_values_tmlogic');
});
epoVariationSection
.find('input.tm-epo-variation-element,input.tm-epo-variation-element + span')
.off('mouseup.cpfv')
.on('mouseup.cpfv', function(){
var field=$(this);
var id;
if(field.is('span')){
field=field.prev('input');
}
if(field.attr('disabled')){
variationForm.find('.reset_variations').trigger('click');
}
id=$.epoAPI.dom.id(field.attr('data-tm-for-variation'));
variationForm.find("[data-attribute_name='attribute_" + id + "']").trigger('focusin');
});
epoVariationSection
.off('click.' + eventName + '.tmepo', '.reset_variations, .tc-epo-element-variable-reset-variations')
.on('click.' + eventName + '.tmepo', '.reset_variations, .tc-epo-element-variable-reset-variations', { _epoObject: epoObject }, function(event){
var _nativeProductPriceSelector;
if(TMEPOJS.tm_epo_change_original_price==='yes'){
if(! alternativeCart||main_product.find('.cpf-bto-price').length===0){
if(event.data._epoObject.associated_connect){
_nativeProductPriceSelector=event.data._epoObject.main_product.find(tcAPI.associatedNativeProductPriceSelector);
}else{
_nativeProductPriceSelector=$(tcAPI.nativeProductPriceSelector);
}
if(_nativeProductPriceSelector.data('tc-original-html')){
_nativeProductPriceSelector.html(_nativeProductPriceSelector.data('tc-original-html'));
}}
}
variationForm.find('.variations .reset_variations, .tc-epo-element-variable-reset-variations').first().trigger('click');
});
epoVariationSection
.find('.tm-epo-variation-element')
.off('change.cpfv tm_epo_variation_element_change')
.on('change.cpfv tm_epo_variation_element_change', function(e){
var field=$(this);
var id=$.epoAPI.dom.id(field.attr('data-tm-for-variation'));
var value=field.val();
var section=field.closest('.cpf-type-variations');
var nativeSelect=variationForm.find("[data-attribute_name='attribute_" + id + "']");
var exists;
if(field.closest('.tm-epo-variation-section').is('.tm-hidden')){
return;
}
if(!(e&&e.type&&e.type==='tm_epo_variation_element_change')){
exists=false;
nativeSelect.each(function(){
if(this.value===value){
exists=true;
return false;
}});
if(! exists){
nativeSelect.trigger('focusin');
}
nativeSelect.val(value).trigger('change');
}
if(! value){
nativeSelect.trigger('focusin');
}
main_product
.find('.cpf-type-variations')
.not(section)
.each(function(){
variationForm.find('#' + $.epoAPI.dom.id($(this).find('.tm-epo-variation-element').first().attr('data-tm-for-variation'))).trigger('focusin');
});
field.trigger('blur');
variationForm.trigger('woocommerce_update_variation_values_tmlogic');
})
.off('focusin.cpfv')
.on('focusin.cpfv', function(){
var field=$(this);
var id;
if(! field.is('select')){
return;
}
id=$.epoAPI.dom.id(field.attr('data-tm-for-variation'));
variationForm.find("[data-attribute_name='attribute_" + id + "']").trigger('focusin');
variationForm.trigger('woocommerce_update_variation_values_tmlogic');
});
variationForm.off(eventNamePrefix + 'found_variation.tmepo tm_fix_stock', '.single_variation_wrap').on(eventNamePrefix + 'found_variation.tmepo tm_fix_stock', '.single_variation_wrap', function(){
fix_stock($(this), cartContainer);
});
variationForm
.off(eventNamePrefix + 'found_variation.tmepo')
.on(eventNamePrefix + 'found_variation.tmepo', function(event, variation){
var form=$(this);
totalsHolder.data('is-on-sale', variation.tc_is_on_sale);
totalsHolder.data('regular-price', tm_set_backend_price(variation.display_regular_price, totalsHolder, variation));
jWindow.trigger('tm-epo-found-variation', {
epo: epoObject,
totalsHolder: totalsHolder,
totalsHolderContainer: totalsHolderContainer,
currentCart: currentCart,
variationForm: form,
variation: variation
});
found_variation_tmepo({
epoHolder: epoHolder,
totalsHolder: totalsHolder,
totalsHolderContainer: totalsHolderContainer,
currentCart: currentCart,
variationForm: form,
variation: variation
});
fix_stock(form, cartContainer);
})
.off(eventNamePrefix + 'hide_variation.tmepo')
.on(eventNamePrefix + 'hide_variation.tmepo', { _epoObject: epoObject }, function(event){
var _nativeProductPriceSelector;
if(TMEPOJS.tm_epo_change_original_price==='yes'){
if(! alternativeCart||main_product.find('.cpf-bto-price').length===0){
if(event.data._epoObject.associated_connect){
_nativeProductPriceSelector=event.data._epoObject.main_product.find(tcAPI.associatedNativeProductPriceSelector);
}else{
_nativeProductPriceSelector=$(tcAPI.nativeProductPriceSelector);
}
if(_nativeProductPriceSelector.data('tc-original-html')){
_nativeProductPriceSelector.html(_nativeProductPriceSelector.data('tc-original-html'));
}}
}
totalsHolder.data('price', false);
totalsHolder.removeData('tcprice');
currentCart.trigger({
type: 'tm-epo-update',
norules: 2
});
})
.off(eventNamePrefix + 'check_variations.tmepo')
.on(eventNamePrefix + 'check_variations.tmepo', function(){
var data={};
var chosen=0;
var reset=epoVariationSection.find('.reset_variations');
variationForm.find('.variations select, .tc-epo-variable-product-selector').each(function(){
var attribute_name=$(this).data('attribute_name')||$(this).attr('name');
var value=$(this).val()||'';
if(value.length > 0){
chosen++;
}
data[ attribute_name ]=value;
});
if(chosen > 0){
if(reset.css('visibility')==='hidden'){
reset.css('visibility', 'visible').hide().fadeIn();
}}else{
reset.css('visibility', 'hidden');
}})
.trigger(eventNamePrefix + 'check_variations');
tm_custom_variations(epoObject, cartContainer, itemId, main_product, epoHolder);
}
selectSelector.trigger('tm-select-change-html');
tmQty.trigger('change.cpf', { init: 1 });
tmQuantity.trigger('showhide.cpfcustom');
epoFieldHasClearButton.filter(':checked').trigger('cpfclearbutton');
jWindow.on('tm-do-epo-update', function(){
currentCart.trigger({
type: 'tm-epo-update'
});
});
jWindow.trigger('tm-epo-init-events', {
epo: {
epo_id: epo_id,
form: epoObject.form,
currentCart: currentCart,
cart_container: cartContainer,
epo_holder: epoHolder,
totals_holder_container: totalsHolderContainer,
totals_holder: totalsHolder,
main_cart: main_cart,
main_epo_inside_form: main_epo_inside_form,
product_id_selector: product_id_selector,
epo_id_selector: epo_id_selector,
product_id: product_id,
this_epo_container: this_epo_container,
this_totals_container: this_totals_container,
this_epo_totals_container: this_epo_totals_container
}});
jWindow.trigger('epoEventHandlers', {
epo: epoObject,
currentCart: currentCart,
cartContainer: cartContainer,
qtyElement: qtyElement,
epoHolder: epoHolder,
totalsHolderContainer: totalsHolderContainer,
totalsHolder: totalsHolder,
variationForm: variationForm,
variation_id_selector: variation_id_selector,
main_epo_inside_form: main_epo_inside_form,
this_product_type: this_product_type,
get_price_excluding_tax: get_price_excluding_tax,
get_price_including_tax: get_price_including_tax
});
if(finalTotalBoxMode!=='disable'){
totalsHolderContainer.addClass('tc-show');
}
jWindow.trigger('epo_options_before_visible');
if(TMEPOJS.tm_epo_progressive_display==='yes'){
setTimeout(function(){
epoHolder
.css('opacity', 0)
.addClass('tc-show')
.animate({
opacity: 1
},
tcAPI.epoAnimationDelay,
'easeOutExpo',
function(){
jWindow.trigger('epo_options_visible');
jWindow.trigger('tmlazy');
}
);
}, tcAPI.epoDelay);
}else{
epoHolder.addClass('tc-show');
jWindow.trigger('epo_options_visible');
jWindow.trigger('tmlazy');
}
main_product.addClass('tc-init');
}
function run_wc_variation_form_cpf(epoObject){
var form=epoObject.variations_form;
var cart=epoObject.main_cart;
var this_epo_container=epoObject.this_epo_container;
var eventName=epoObject.is_associated ? 'tc_variation_form.cpf':'wc_variation_form.cpf';
form.off(eventName).on(eventName, function(){
if(form.data('epo_loaded')){
return;
}
cpf_section_logic(this_epo_container);
cpf_element_logic(this_epo_container);
$.tcepo.lateFieldsPrices[ epoObject.epoEventId ]=[];
epoEventHandlers(epoObject);
tm_set_upload_fields(epoObject);
tm_product_image(epoObject);
epoObject.noEpoUpdate=false;
setTimeout(function(){
run_cpfdependson(this_epo_container);
cart.trigger({
type: 'tm-epo-update',
rules: 'init'
});
}, 10);
form.data('epo_loaded', true);
});
if(variationsFormIsLoaded){
form.trigger(eventName);
}
jWindow.trigger('epo-after-init', { epo: epoObject });
}
function detect_variation_swatches_interval(epoObject){
var $id=requestAnimationFrame(function(){
detect_variation_swatches_interval(epoObject);
});
var obj=epoObject.variations_form;
var bound=obj.data('bound');
var eventName=epoObject.is_associated ? 'tc_variation_form.cpf':'wc_variation_form.cpf';
if(bound){
cancelAnimationFrame($id);
run_wc_variation_form_cpf(epoObject);
obj.trigger(eventName);
}}
function manualInitEPO(epoObject, item, itemCart, itemEpoContainer, main_product){
var epoObjectOriginal=$.extend(true, {}, epoObject);
var product_id=itemEpoContainer.attr('data-product-id');
var epo_id=itemEpoContainer.attr('data-epo-id');
var product_id_selector='.tm-product-id-' + product_id;
var epo_id_selector="[data-epo-id='" + epo_id + "']";
var epoEventId='p' + product_id + 'e' + epo_id;
var this_epo_container=$('.tc-extra-product-options' + product_id_selector + epo_id_selector);
var this_totals_container=$('.tc-totals-form' + product_id_selector + epo_id_selector);
var this_epo_totals_container=$('.tc-epo-totals' + product_id_selector + epo_id_selector);
epoObject.isManual=true;
$.tcepo.formSubmitEvents[ epoEventId ]=[];
$.tcepo.errorObject[ epoEventId ]=false;
$.tcepo.initialActivation[ epoEventId ]=false;
epoObject.product_id=product_id;
epoObject.product_id_selector=product_id_selector;
epoObject.epo_id=epo_id;
epoObject.epo_id_selector=epo_id_selector;
epoObject.epoEventId=epoEventId;
epoObject.noEpoUpdate=true;
epoObject.thisForm=item;
epoObject.this_epo_container=this_epo_container;
epoObject.this_totals_container=this_totals_container;
epoObject.this_epo_totals_container=this_epo_totals_container;
tm_lazyload();
main_product.find('.tm-collapse').tmtoggle();
main_product.find('.tm-section-link').tmsectionpoplink();
tm_set_datepicker(item);
setRangePickers(item);
setRangePickersEvents();
tm_set_repeaters(item, epoObject);
tm_css_styles(item);
tm_set_color_pickers(itemEpoContainer);
tm_set_lightbox(itemEpoContainer.find('.tc-lightbox-image').not('.tm-extra-product-options-variations .radio-image'));
cpf_section_logic(itemEpoContainer);
cpf_element_logic(itemEpoContainer);
run_cpfdependson(itemEpoContainer);
$.tcToolTip(item.find('.tm-tooltip'));
epoEventHandlers(epoObject, item, itemCart);
epoObject.noEpoUpdate=false;
itemCart.trigger({
type: 'tm-epo-update',
norules: 2
});
setTimeout(function(){
epoObject.main_cart.trigger({
type: 'tm-epo-update',
epoObject: epoObjectOriginal,
norules: 1
});
}, 200);
fix_stock(itemCart, item);
}
function tm_init_epo(main_product, is_quickview, product_id, epo_id, associated_connect, mainEpoObject, reactivate){
var main_cart=false;
var main_epo_inside_form=false;
var main_totals_inside_form=false;
var epoEventId;
var has_epo=typeof product_id!=='undefined';
var not_has_epo=false;
var add_to_cart_field;
var product_id_selector;
var epo_id_selector;
var this_epo_container;
var this_totals_container;
var this_epo_totals_container;
var epo_object;
var variations_form;
var detect_variation_swatches=$('.variation_form_section .variations-table').length > 0;
var is_associated=false;
main_product=$(main_product);
if(main_product.is('.tc-init')&&! reactivate){
return true;
}
if(is_quickview){
errorContainer=main_product;
}else{
errorContainer=$(window);
}
jWindow.trigger('tm-epo-init-start');
if(! has_epo){
if(main_product.is('.product')){
not_has_epo=true;
has_epo=jBody.find(tcAPI.epoSelector).length;
}}
if(! has_epo&&TMEPOJS.tm_epo_enable_final_total_box_all==='no'&&! main_product.is('.tm-no-options-composite')){
jWindow.trigger('tm-epo-init-end-no-options');
return;
}
if(not_has_epo){
jWindow.trigger('tm-epo-init-no-options');
if(main_product.is('.product')&&!(main_product.is('.tm-no-options-pxq')||main_product.is('.tm-no-options-composite'))){
main_product=jBody;
}}
if(! product_id){
add_to_cart_field=main_product.find(tcAPI.addToCartSelector).last();
if(add_to_cart_field.length > 0){
product_id=add_to_cart_field.val();
}else{
add_to_cart_field=$('.tc-totals-form.tm-totals-form-main');
product_id=add_to_cart_field.attr('data-product-id');
}
if(! product_id){
product_id='';
}}
if(! epo_id){
epo_id=parseInt(main_product.find('input.tm-epo-counter').last().val(), 10);
if(! Number.isFinite(epo_id)){
epo_id='';
}}
product_id_selector='.tm-product-id-' + product_id;
epo_id_selector="[data-epo-id='" + epo_id + "']";
this_epo_container=$('.tc-extra-product-options' + product_id_selector + epo_id_selector);
this_totals_container=$('.tc-totals-form' + product_id_selector + epo_id_selector);
this_epo_totals_container=$('.tc-epo-totals' + product_id_selector + epo_id_selector);
variations_form=main_product.find('.variations_form').not('.composite_component .variations_form').first();
epoEventId='p' + product_id + 'e' + epo_id;
if(variations_form&&variations_form.attr('data-product_id')){
if(variations_form.attr('data-product_id')!==product_id){
variations_form=main_product.find(".variations_form[data-product_id='" + product_id + "']");
}}
main_cart=get_main_cart(main_product, main_product, 'form', product_id);
if(main_cart.length===0){
if(main_product.is('.tc-shortcode-wrap')){
main_cart=get_main_cart(this_totals_container, this_totals_container, '.tc-totals-form', product_id);
}else if(main_product.is('.tc-epo-element-product-container')){
main_cart=main_product.find(tcAPI.associatedEpoCart);
if(main_cart.length===0){
main_cart=this_epo_container.parent(tcAPI.associatedEpoSelector);
if(main_cart.length===0){
main_cart=main_product.find('.tc-epo-element-product-container-right');
}}
is_associated=true;
}}
if(is_associated&&variations_form.length===0&&main_product.is('.variations_form')){
variations_form=main_product;
}
$.tcepo.formSubmitEvents[ epoEventId ]=[];
$.tcepo.errorObject[ epoEventId ]=false;
$.tcepo.initialActivation[ epoEventId ]=false;
if(main_cart.find(tcAPI.epoSelector).length > 0){
main_epo_inside_form=true;
}
if(main_cart.find('.tc-totals-form').length > 0){
main_totals_inside_form=true;
}
if(! main_totals_inside_form){
$.tcepo.formSubmitEvents[ epoEventId ][ $.tcepo.formSubmitEvents[ epoEventId ].length ]={
trigger: function(){
return true;
},
on_true: function(){
var epos_hidden=$('.tc-totals-form.tm-product-id-' + product_id + "[data-epo-id='" + epo_id + "']").tcClone();
var formepo=$('<div class="tm-hidden tm-formepo-normal"></div>');
main_cart.find('.tm-formepo-normal').remove();
formepo.append(epos_hidden);
main_cart.append(formepo);
return true;
},
on_false: function(){
setTimeout(function(){
$('.tm-formepo-normal').remove();
}, 100);
}};}
if(! main_epo_inside_form){
$.tcepo.formSubmitEvents[ epoEventId ][ $.tcepo.formSubmitEvents[ epoEventId ].length ]={
trigger: function(){
return true;
},
on_true: function(){
var epos=$(tcAPI.epoSelector + '.tm-product-id-' + product_id + "[data-epo-id='" + epo_id + "']")
.tcClone()
.addClass('formepo');
var formepo=$('<div class="tm-hidden tm-formepo"></div>');
main_cart.find('.tm-formepo').remove();
formepo.append(epos);
main_cart.append(formepo);
return true;
},
on_false: function(){
setTimeout(function(){
$('.tm-formepo').remove();
}, 100);
}};}
epo_object={
main_product: main_product,
main_cart: main_cart,
epo_id: epo_id,
form: get_main_form(main_product),
main_epo_inside_form: main_epo_inside_form,
product_id_selector: product_id_selector,
epo_id_selector: epo_id_selector,
product_id: product_id,
this_epo_container: this_epo_container,
this_totals_container: this_totals_container,
this_epo_totals_container: this_epo_totals_container,
qtySelector: tcAPI.qtySelector,
manualInitEPO: manualInitEPO,
epoEventId: epoEventId,
variations_form: variations_form,
has_epo: has_epo,
is_quickview: is_quickview,
is_associated: is_associated,
is_epo_shortcode: this_epo_container.is('.tc-shortcode'),
mainEpoObject: mainEpoObject,
associated_connect: associated_connect,
noEpoUpdate: true
};
$(epo_object.form).data('epo_object', epo_object);
main_cart.data('product_id', product_id).data('epo_id', epo_id).data('product_id_selector', product_id_selector).data('epo_id_selector', epo_id_selector);
tm_set_checkboxes_rules(epo_object);
tm_set_upload_rules(epo_object);
tm_set_datepicker(this_epo_container);
setRangePickers(this_epo_container);
setRangePickersEvents();
tm_set_repeaters(this_epo_container, epo_object);
tm_set_url_fields();
$.tcToolTip(this_epo_container.find('.tm-tooltip'));
this_epo_container.find('.tm-collapse').tmtoggle();
this_epo_container.find('.tm-section-link').tmsectionpoplink();
if(reactivate){
this_epo_container.addClass('reactivate');
}
if(variations_form.length > 0){
if(reactivate){
variations_form.data('epo_loaded', false);
}
this_epo_totals_container.data('price', false);
if(detect_variation_swatches){
detect_variation_swatches_interval(epo_object);
}else{
run_wc_variation_form_cpf(epo_object);
}}else{
setTimeout(function(){
cpf_section_logic(this_epo_container);
cpf_element_logic(this_epo_container);
run_cpfdependson(this_epo_container);
$.tcepo.lateFieldsPrices[ epoEventId ]=[];
epoEventHandlers(epo_object);
tm_set_upload_fields(epo_object);
tm_product_image(epo_object);
jWindow.trigger('epo-after-init-in-timeout', { epo: epo_object });
main_cart.trigger('tm-epo-check-dpd');
epo_object.noEpoUpdate=false;
main_cart.trigger({
type: 'tm-epo-update',
rules: 'init'
});
}, 20);
jWindow.trigger('epo-after-init', { epo: epo_object });
}
tm_lazyload();
tm_css_styles(this_epo_container);
tm_set_color_pickers(this_epo_container);
tm_set_lightbox(this_epo_container.find('.tc-lightbox-image').not('.tm-extra-product-options-variations .radio-image'));
tm_theme_specific_actions(epo_object);
tc_compatibility(epo_object);
if(! is_associated){
tm_floating_totals(this_epo_totals_container, is_quickview, main_cart);
tm_form_submit_event(epo_object);
epo_object=addShowHidetoEpoObject(epo_object, epoEventId, epo_object);
tm_show_hide_add_to_cart_button(main_product, epo_object);
}
jWindow.trigger('tm-epo-init-end', { epo: epo_object });
return epo_object;
}
function manual_init(container, reactivate){
var $this=$(container);
var product_id=$this.attr('data-product-id');
var epo_id=$this.attr('data-epo-id');
var quickview_floating=false;
var testForm=$this.parent();
if(! testForm.is('form')){
testForm=$this.closest('form');
if(! testForm.is('form')){
testForm=$this.parent();
}}
testForm=testForm.parent();
tm_init_epo(testForm, quickview_floating, product_id, epo_id, undefined, undefined, reactivate);
}
function init_epo_plugin(){
var epo_container;
var epo_options_container;
if(TMEPOJS.tm_epo_no_lazy_load==='no'){
$.extend($.lazyLoadXT, {
autoInit: false,
selector: 'img.tmlazy',
srcAttr: 'data-original',
visibleOnly: false,
updateEvent: $.lazyLoadXT.updateEvent + ' tmlazy'
});
}
epo_container=$('.tm-no-options-pxq, .tm-no-options-composite');
if(epo_container.length > 0){
epo_container.addClass('initializing');
epo_container.each(function(loop_index, product_wrap){
var inputepoid;
product_wrap=$(product_wrap);
inputepoid=product_wrap.find('input.tm-epo-counter');
if(inputepoid.length > 1){
inputepoid.each(function(){
var currentepoid=$(this);
var currentcart=currentepoid.closest('.cart');
var currentcartparent=currentcart.parent();
if(currentcartparent.is('form')){
currentcartparent=currentcartparent.parent();
}
if(! currentcartparent.is('.initializing')){
tm_init_epo(currentcartparent, false, undefined, parseInt(currentepoid.val(), 10));
}});
}else{
tm_init_epo(product_wrap, false);
}
epo_container.removeClass('initializing');
});
}
setTimeout(function(){
try {
epo_options_container=$(tcAPI.epoSelector).not(tcAPI.associatedEpoSelector + ' ' + tcAPI.epoSelector + ', .tm-no-options-pxq, .tm-no-options-composite, .wc-product-table ' + tcAPI.epoSelector);
if(epo_options_container.length > 0){
epo_container.addClass('initializing');
epo_options_container.each(function(){
var $this=$(this);
var product_id=$this.attr('data-product-id');
var epo_id=$this.attr('data-epo-id');
var quickview_floating=false;
var jProductWrap;
var addInputs=false;
var inputepoid;
jProductWrap=$this.closest('.tc-after-shop-loop.tm-has-options');
if(jProductWrap.length===0){
jProductWrap=$(tcAPI.tcAddToCartSelector + "[data-epo-id='" + epo_id + "'][value='" + product_id + "']")
.closest('form,.cart')
.first()
.parent();
if(jProductWrap.length===0){
jProductWrap=$(tcAPI.addToCartSelector + "[value='" + product_id + "']")
.closest('form,.cart')
.first()
.parent();
if(jProductWrap.length===0){
jProductWrap=$this.closest('form,.cart').first().parent('.tm-has-options');
if(jProductWrap.length===0){
if($this.is('.tc-shortcode')){
jProductWrap=$this.wrap('<div class="tc-shortcode-wrap tc-wrap-' + epo_id + '"></div>');
jProductWrap=$this.parent();
}
if(jProductWrap.length > 0){
addInputs=true;
}}
}}
}else{
addInputs=true;
}
if(jProductWrap.length > 0){
if(addInputs){
quickview_floating=true;
$this
.closest('form,.cart')
.first()
.append($('<input name="add-to-cart" value="' + product_id + '" type="hidden">'));
$this.closest('form,.cart').first().append($('<input type="hidden" value="" class="variation_id" name="variation_id">'));
}
if(jProductWrap.is('form')){
jProductWrap=jProductWrap.parent();
}
inputepoid=jProductWrap.find('input.tm-epo-counter');
if(inputepoid.length > 1){
inputepoid.each(function(){
var currentepoid=$(this);
var currentcart=currentepoid.closest('.cart');
var currentcartparent=currentcart.parent();
if(currentcartparent.is('form')){
currentcartparent=currentcartparent.parent();
}
if(! currentcartparent.is('.initializing')){
tm_init_epo(currentcartparent, quickview_floating, product_id, parseInt(currentepoid.val(), 10));
}});
}else{
tm_init_epo(jProductWrap, quickview_floating, product_id, epo_id);
}}
});
epo_container.removeClass('initializing');
}} catch(err){
window.console.log(err);
errorObject=err;
}}, 1);
}
$.tcepo.tm_init_epo=function(main_product, is_quickview, product_id, epo_id){
tm_init_epo(main_product, is_quickview, product_id, epo_id);
};
$.tcepo.tmLazyloadContainer=function(container){
tmLazyloadContainer=container;
};
jWindow.on('tc_manual_init', function(evt, container){
var reactivate;
if('container' in container&&'reactivate' in container){
reactivate=container.reactivate;
container=container.container;
}
manual_init(container, reactivate);
});
$(function(){
tcAPI=$.epoAPI.applyFilter('tc_api', tcAPI);
jWindow.on('lazyLoadXToncomplete', function(){
$('.tm-owl-slider').each(function(){
$(this).trigger('refresh.owl.carousel');
});
});
jWindow.on('tc_init_epo_plugin', function(evt){
init_epo_plugin(evt);
});
jWindow.on('tcShowLastError', function(){
window.console.log(errorObject);
});
jBody.on('click.tcajax', '.ajax_add_to_cart', function(){
var _pid;
var epos;
var _cpf_product_price;
var form_prefix;
var epoid;
var obj;
var data;
currentAjaxButton=$(this);
if(undefined!==currentAjaxButton.attr('data-product_id')){
epoid=currentAjaxButton.closest('.cart').find('.tm-epo-counter').val();
if(! epoid){
epoid=currentAjaxButton.attr('data-epo-id');
if(! epoid){
return;
}}
if(currentAjaxButton.closest('.tm-has-options').length!==1&&currentAjaxButton.attr('data-epo-id')===undefined){
return;
}
_pid=currentAjaxButton.attr('data-product_id');
obj={};
epos=$('.tc-extra-product-options.tm-product-id-' + _pid + '[data-epo-id="' + epoid + '"]');
if(epos.length > 1){
if(epos.filter('.formepo')){
epos=epos.filter('.formepo');
}else{
epos=epos.first();
}}
if(epos.length===1){
_cpf_product_price=$('.tc-totals-form.tm-product-id-' + _pid + '[data-epo-id="' + epoid + '"]')
.find('.cpf-product-price')
.val();
form_prefix=$('.tc-totals-form.tm-product-id-' + _pid + '[data-epo-id="' + epoid + '"]')
.find('.tc_form_prefix')
.val();
obj=$.extend(obj, {
tcajax: 1,
tcaddtocart: _pid,
cpf_product_price: _cpf_product_price
});
if(form_prefix){
obj.tc_form_prefix=form_prefix;
}}
data=currentAjaxButton.data();
data=$.extend(data, epos.tcSerializeObject(), obj);
currentAjaxButton.removeData();
currentAjaxButton.data(data);
}});
$.ajaxPrefilter(function(options, originalOptions){
var found=false;
var hashes;
var hash;
var i;
var params;
var $thisbutton;
var _data;
var _urldata;
var _pid;
var epos;
var _cpf_product_price;
var form_prefix;
var obj;
var oldData;
var formData;
var can_be_added=false;
var associativeArray={};
if(TMEPOJS.tm_epo_enable_in_shop==='yes'){
hashes=options.url.split('?');
if(hashes&&hashes.length >=1){
hashes=hashes[ 1 ];
if(hashes){
hash=hashes.split('&');
for(i=0; i < hash.length; i +=1){
params=hash[ i ].split('=');
if(params.length >=1){
if(params[ 0 ]&&params[ 1 ]&&params[ 0 ]==='wc-ajax'&&params[ 1 ]==='add_to_cart'){
found=true;
}}
}
if(found){
options.originalsuccess=options.success;
options.success=function(response){
if(response&&response.error&&response.product_url){
if(currentAjaxButton&&currentAjaxButton.length===1){
$thisbutton=currentAjaxButton;
}
$thisbutton=$(".ajax_add_to_cart[data-product_id='" + originalOptions.data.product_id + "']");
$thisbutton.removeClass('added');
$thisbutton.removeClass('loading');
}else{
options.originalsuccess.call(null, response);
}};}}
}}
if(FormData&&originalOptions.data){
_data=originalOptions.data;
if(typeof originalOptions.data==='string'){
_data=$.epoAPI.util.parseParams(originalOptions.data);
}
if(typeof _data[ 0 ]==='object'){
_data.forEach(function(item){
associativeArray[ item.name ]=item.value;
});
_data=associativeArray;
}
_urldata=[];
if(originalOptions.url&&originalOptions.url.indexOf){
_urldata=$.epoAPI.util.parseParams(originalOptions.url.slice(originalOptions.url.indexOf('?') + 1));
}
if('quantity' in _data&&_data.tcaddtocart&&(_data.product_id||_data[ 'add-to-cart' ]||_urldata.product_id||_urldata[ 'add-to-cart' ])){
can_be_added=true;
_pid=_data.tcaddtocart;
}else if(Array.isArray(_data)){
can_be_added=_data.some(function(item){
return item.name==='quantity';
})&&_data.some(function(item){
return item.name==='add-to-cart';
})&&_data.some(function(item){
return item.name==='tcaddtocart';
});
_pid=_data.find(function(item){
return item.name==='tcaddtocart';
});
if(_pid){
_pid=_pid.value;
}else{
_pid=false;
}}
if(can_be_added){
if(currentAjaxButton&&currentAjaxButton.length===1&&currentAjaxButton.closest('.tm-has-options').length===1){
epos=currentAjaxButton.closest('.tm-has-options').find('.tc-extra-product-options.tm-product-id-' + _pid);
}else{
epos=$('.tc-extra-product-options.tm-product-id-' + _pid);
}
if(epos.length > 1){
if(epos.filter('.formepo')){
epos=epos.filter('.formepo');
}else{
epos=epos.first();
}}
if(epos.length===1){
_cpf_product_price=$('.tc-totals-form.tm-product-id-' + _pid)
.find('.cpf-product-price')
.val();
form_prefix=$('.tc-totals-form.tm-product-id-' + _pid)
.find('.tc_form_prefix')
.val();
obj={
tcajax: 1,
tcaddtocart: _pid,
cpf_product_price: _cpf_product_price
};
if(form_prefix){
obj.tc_form_prefix=form_prefix;
}
oldData=$.epoAPI.util.parseParams(options.data, true);
oldData=$.extend(oldData, epos.tcSerializeObject(), obj);
formData=new FormData();
Object.keys(oldData).forEach(function(key){
if(key){
formData.append(key, oldData[ key ]);
}});
epos.find(':file')
.toArray()
.forEach(function(el){
for(i=0; i < $(el)[ 0 ].files.length; i++){
formData.delete($(el).attr('name'));
formData.append($(el).attr('name'), $(el)[ 0 ].files[ i ]);
}});
options.data=formData;
options.contentType=false;
options.cache=false;
options.processData=false;
}}
}});
jDocument.ajaxSuccess(function(event, request, settings){
var qv_container=TMEPOJS.quickview_array||'null';
var fromaddons=TMEPOJS.quickview_container||'null';
var added={};
var selectors;
var container;
var product_id;
var epo_id;
var noProductCheck;
var testContainer;
var parsedUrl;
var time=1;
var detectContainer;
var requestContainer;
parsedUrl=$.epoAPI.util.parseParams(settings.data);
if(parsedUrl.action==='wc_epo_get_associated_product_html'){
return;
}
$('.tm-formepo-normal').remove();
$('.tm-formepo').remove();
$('.tm-cart-link').tmpoplink();
qv_container=$.epoAPI.util.parseJSON(qv_container);
fromaddons=$.epoAPI.util.parseJSON(fromaddons);
for(selectors in fromaddons){
if(Object.prototype.hasOwnProperty.call(fromaddons, selectors)){
added[ fromaddons[ selectors ][ 0 ] ]=$(fromaddons[ selectors ][ 1 ]);
}}
$.extend(qv_container, added);
detectContainer=function(){
var keyfound=false;
Object.keys(qv_container).forEach(function(key){
if($(qv_container[ key ]).length){
keyfound=key;
}});
return keyfound;
};
requestContainer=function(times){
var id=requestAnimationFrame(function(){
setTimeout(function(){
requestContainer(times - 1);
}, 200);
});
var key=detectContainer();
var epoContainer;
if(key||0===times){
cancelAnimationFrame(id);
if(key){
noProductCheck=false;
container=$(qv_container[ key ]);
if(key==='woothemes_quick_view'&&container.is('.fusion-woocommerce-quick-view-container')){
return true;
}
if(key==='fusion_quick_view_load'&&container.find(tcAPI.epoSelector).length===0){
return true;
}
if(key==='woodmart_quick_shop'){
parsedUrl=$.epoAPI.util.parseParams(settings.url);
if(parsedUrl.action==='woodmart_quick_shop'){
testContainer=$($.epoAPI.util.escapeSelector(qv_container[ key ] + '.post-' + parsedUrl.id));
if(testContainer.length){
container=testContainer;
noProductCheck=true;
}}
}
if(key==='woodmart_quick_view'){
parsedUrl=$.epoAPI.util.parseParams(settings.url);
if(parsedUrl.action==='woodmart_quick_view'){
testContainer=$($.epoAPI.util.escapeSelector(qv_container[ key ] + '.post-' + parsedUrl.id));
if(testContainer.length){
container=testContainer;
noProductCheck=true;
}}
}
if(key==='quickview_pro'){
parsedUrl=settings.url.split('/');
if(parsedUrl.length){
testContainer=$($.epoAPI.util.escapeSelector(qv_container[ key ] + ' .post-' + parsedUrl[ parsedUrl.length - 1 ]));
if(testContainer.length){
container=testContainer;
noProductCheck=true;
}}
}
if(key==='exwoofood_booking_info'||key==='wqv_popup_content'||key==='wp_food'||key==='jet_popup_get_content'){
noProductCheck=true;
}
if(key==='woofood'&&settings.data){
parsedUrl=$.epoAPI.util.parseParams(settings.data);
if(parsedUrl.action==='woofood_quickview_ajax'){
testContainer=testContainer=container.find('form').parent();
if(testContainer.length){
container=testContainer;
noProductCheck=true;
}}
}
if(container.find('.product').length===0&&container.is('.product')){
noProductCheck=true;
}
if(( container.find('.product').length > 0||noProductCheck)){
container.removeClass('tc-init');
if(key==='fusion_quick_view_load' ||
key==='jet_popup_get_content' ||
key==='wp_food' ||
key==='woodmart_quick_shop' ||
key==='woodmart_quick_view' ||
key==='lightboxpro' ||
key==='jckqv_quick_view' ||
key==='yith_quick_view' ||
key==='theme_flatsome'
){
variationsFormIsLoaded=true;
}
tmLazyloadContainer=container;
epoContainer=tmLazyloadContainer.find(tcAPI.epoSelector);
if(epoContainer.length===0){
delete qv_container[ key ];
requestContainer(10);
return true;
}
if(key==='fusion_quick_view_load'){
time=1400;
}
setTimeout(function(){
product_id=epoContainer.attr('data-product-id');
epo_id=epoContainer.attr('data-epo-id');
if(key==='woodmart_quick_shop'){
container.addClass('has-options');
}
tcAPI.getElementFromFieldCache=[];
tm_init_epo(tmLazyloadContainer, true, product_id, epo_id);
jWindow.trigger('tmlazy');
jWindow.trigger('tm_epo_loaded_quickview');
if($.jMaskGlobals){
tmLazyloadContainer.find($.jMaskGlobals.maskElements).each(function(){
var t=$(this);
if(t.attr('data-mask')){
t.mask(t.attr('data-mask'));
}});
}}, time);
}}
}};
requestContainer(10);
});
init_epo_plugin();
$('.tm-cart-link').tmpoplink();
jBody.on('updated_checkout wc_fragments_loaded wc_fragments_refreshed wc_fragment_refresh', function(){
$('.tm-cart-link').tmpoplink();
});
jWindow.trigger('tmlazy');
jWindow.trigger('tm_epo_loaded');
});
function associated_table_item(){
$('.tc-associated-table-product td.product-name').each(function(){
var el=$(this);
if(el.find('.product-name').length===0){
el.wrapInner($('<div class="tc-associated-table-product-indent"></div>'));
}});
}
jBody.on('updated_checkout updated_cart_totals', function(){
associated_table_item();
});
associated_table_item();
$(function(){
var ua=navigator.userAgent||navigator.vendor||window.opera;
ua=(ua.indexOf('FBAN') > -1)||(ua.indexOf('FBAV') > -1)||(ua.indexOf('Instagram') > -1);
if(ua){
$('.tmcp-upload').removeAttr('accept');
}
jDocument.on('click', '.quantity .jckqv-qty-spinner, .quantity .ui-spinner-button', function(){
$(this).closest('.quantity').find(tcAPI.qtySelector).trigger('change');
});
$('#wholesale_form').on('submit', function(){
var _product_id=$('form.cart').find(tcAPI.addToCartSelector).val();
var epos=$(tcAPI.epoSelector + ".tm-cart-main[data-product-id='" + _product_id + "']").tcClone();
var epos_hidden=$(".tm-totals-form-main[data-product-id='" + _product_id + "']").tcClone();
var formepo=$("<div class='tm-hidden tm-formepo'></div>");
formepo.append(epos);
formepo.append(epos_hidden);
$(this).append(formepo);
return true;
});
jDocument.on('click', '#add_to_quote', function(e){
var form;
var epo_id;
var epos;
if(TMEPOJS&&TMEPOJS.tm_epo_global_enable_validation==='yes'){
form=$(this).parents('form');
epo_id=parseInt(form.find('.tm-epo-counter').val(), 10);
epos=$(tcAPI.epoSelector + "[data-epo-id='" + epo_id + "']");
if(TMEPOJS.tm_epo_global_enable_validation==='yes'&&$.tc_validator&&form.length > 0&&epos.length > 0&&! form.tc_validate().form()){
e.stopImmediatePropagation();
}}
});
$('.single_add_to_cart_button.paypal_checkout_button').on('click', function(event){
var form=$('.cart');
var validator;
if(form.data('tc_validator')){
validator=form.data('tc_validator');
if(validator.errorList){
event.stopImmediatePropagation();
}}
});
$('.wc-product-table').on('init.wcpt', function(event, table){
table.$table.find(tcAPI.epoSelector).addClass('hidden');
table.$table.find('thead tr').append('<th>&nbsp;</th>');
setTimeout(function(){
table.$table.find('.cart:not(.cart_group)').each(function(){
var epo=$(this).find(tcAPI.epoSelector);
var tr=epo.closest('tr');
$("<td class='wc-product-table-epo'></td>").appendTo(tr).append(epo);
$(window).trigger('tc_manual_init', epo);
epo.removeClass('hidden');
});
}, 500);
});
});
}(window, document, window.jQuery));
(function($){
const removeAttrClass=cfvsw_swatches_settings.remove_attr_class;
const addRemoveWithCommonClass=`${ removeAttrClass } cfvsw-swatches-out-of-stock`;
const addRemoveDisableClass=removeAttrClass + '-disable';
const addRemoveDisableClassCommon=`${ addRemoveDisableClass } cfvsw-swatches-disabled`;
const SW={
init: ()=> {
if(cfvsw_swatches_settings.disable_out_of_stock){
SW.firstTime();
SW.Events();
}},
firstTime: ()=> {
const getVariationTable=$('table.variations').not('.cfvsw-variation-disable-logic'
);
getVariationTable.addClass('cfvsw-variation-disable-logic');
getVariationTable.each(function (){
const table=$(this);
const getForm=table.closest('[data-product_id][data-product_variations]'
);
const getFormData=getForm.data('product_variations');
SW.swatchesOptions(getForm, getFormData);
});
},
chooseOption(){
const option=$(this);
const getForm=option.closest('[data-product_id][data-product_variations]'
);
getForm
.find('.disable-to-select')
.removeClass('disable-to-select');
const td=option.closest('td');
const checkTdSelected=td
.find('.cfvsw-hidden-select select')
.val();
if(''!==checkTdSelected){
td.addClass('disable-to-select');
}
const getFormData=getForm.data('product_variations');
SW.swatchesOptions(getForm, getFormData);
},
getSelectedOptions:(getForm)=> {
const getSelectedSwatches=getForm.find('.cfvsw-hidden-select select'
);
const selected={};
getSelectedSwatches.each(function (){
const select=$(this);
const getValue=select.val();
const getAttrName=select.attr('data-attribute_name');
if(''!==getValue&&''!==getAttrName){
selected[ getAttrName ]=getValue;
}});
return selected;
},
swatchesOptions:(getForm, getFormData)=> {
const getTdAvoidCurrent=getForm
.find('td')
.not('.disable-to-select');
const getAllSelect=getTdAvoidCurrent.find('.cfvsw-swatches-container[swatches-attr]'
);
if(! getAllSelect.length){
return;
}
const getSelectedOptions=SW.getSelectedOptions(getForm);
const findToRemoveClass=getTdAvoidCurrent.find(`.${ addRemoveDisableClass }`
);
if(findToRemoveClass.length){
findToRemoveClass.removeClass(addRemoveDisableClassCommon);
}
getAllSelect.each(function (){
const select=$(this);
const getAttrName=select.attr('swatches-attr');
if(''!==getAttrName){
const findOptions=select.find('.cfvsw-swatches-option');
findOptions.each(function (){
const optValue=$(this);
const currentTermSlug=optValue.attr('data-slug');
if(currentTermSlug&&''!==currentTermSlug){
const hasStock=SW.checkOptionAvail(getAttrName,
currentTermSlug,
getSelectedOptions,
getFormData
);
if(! hasStock){
optValue.addClass(addRemoveDisableClassCommon
);
}}
});
}});
},
checkOptionAvail: (
getAttrName,
currentTermSlug,
getSelectedOptions,
getFormData
)=> {
let hasThisSwatch;
for(let index=0; index < getFormData.length; index++){
const productVariations=getFormData[ index ];
const { attributes, is_in_stock }=productVariations;
const passedInRaw=SW.checkInPreRawData(getSelectedOptions,
attributes,
getAttrName,
currentTermSlug,
is_in_stock
);
if(passedInRaw){
hasThisSwatch=is_in_stock;
break;
}}
return hasThisSwatch;
},
checkInPreRawData: (
getSelectedOptions,
attributes,
getAttrName,
currentTermSlug,
is_in_stock
)=> {
let hasThisSwatch=false;
const copySelected={ ...getSelectedOptions };
const selectedKeys=Object.keys(getSelectedOptions);
const getCurrentIndex=selectedKeys.indexOf(getAttrName);
const currentObj={};
currentObj[ getAttrName ]=currentTermSlug;
if(getCurrentIndex >=0){
selectedKeys.splice(getCurrentIndex, 1);
delete copySelected[ getAttrName ];
}
hasThisSwatch=SW.checkInRawData(attributes,
copySelected,
currentObj,
is_in_stock
);
return hasThisSwatch;
},
checkInRawData:(attribute, selected, currentObj, is_in_stock)=> {
const cloneAttr={ ...attribute };
const selectedCurrent={ ...selected, ...currentObj };
let checkAndAvail=true;
for(const checkIsAvail in selectedCurrent){
const value=selectedCurrent[ checkIsAvail ];
const attrValue=attribute[ checkIsAvail ];
if(''===attrValue){
delete cloneAttr[ checkIsAvail ];
continue;
}
if(value===attrValue){
delete cloneAttr[ checkIsAvail ];
continue;
}
checkAndAvail=false;
}
if(is_in_stock){
return checkAndAvail;
}
for(const cloneKey in cloneAttr){
const cloneValue=cloneAttr[ cloneKey ];
if(''!==cloneValue){
checkAndAvail=false;
}}
return checkAndAvail;
},
Events: ()=> {
$(document).on('click',
'.cfvsw-swatches-container .cfvsw-swatches-option[data-slug]',
SW.chooseOption
);
$(document).on('berocket_ajax_products_infinite_loaded',
function (){
SW.firstTime();
}
);
},
};
$(document).on('click', '.cfvsw-swatches-option', function (){
const swatchesOption=$(this);
if(swatchesOption.hasClass('cfvsw-swatches-disabled') ||
swatchesOption.hasClass('cfvsw-swatches-out-of-stock')
){
return;
}
onClickSwatchesOption(swatchesOption);
addVariationFunctionality();
});
$('body').on('click',
'.cfvsw_ajax_add_to_cart.cfvsw_variation_found',
function(e){
e.preventDefault();
triggerAddToCart($(this));
}
);
function onClickSwatchesOption(swatch){
if(swatch.hasClass('cfvsw-selected-swatch')){
swatch.removeClass('cfvsw-selected-swatch');
resetPrice(swatch);
resetThumbnail(swatch);
resetButtonData(swatch);
}else{
const parent=swatch.parent();
parent.find('.cfvsw-swatches-option').each(function (){
$(this).removeClass('cfvsw-selected-swatch');
});
swatch.addClass('cfvsw-selected-swatch');
}
updateSelectOption(swatch);
if(cfvsw_swatches_settings.html_design!=='inline'){
updateTitle(swatch);
}}
function updateSelectOption(swatch){
const value=swatch.hasClass('cfvsw-selected-swatch')
? swatch.data('slug')
: '';
const select=swatch
.closest('.cfvsw-swatches-container')
.prev()
.find('select');
select.val(value).change();
}
function updateTitle(swatch){
const label=swatch.closest('tr').children('.label');
label.find('.cfvsw-selected-label').remove();
if(! swatch.hasClass('cfvsw-selected-swatch')){
return;
}
label
.children('label')
.append('<span class="cfvsw-selected-label"></span>');
label
.children('label')
.children('.cfvsw-selected-label')
.html(swatch.data('title'));
}
function triggerAddToCart(variant){
if(variant.is('.wc-variation-is-unavailable')){
return window.alert(cfvsw_swatches_settings.unavailable_text);
}
const productId=variant.data('product_id');
let variationId=variant.attr('data-variation_id');
variationId=parseInt(variationId);
if(isNaN(productId) ||
productId===0 ||
isNaN(variationId) ||
variationId===0
){
return true;
}
let variation=variant.attr('data-selected_variant');
variation=JSON.parse(variation);
const data={
action: 'cfvsw_ajax_add_to_cart',
security: cfvsw_swatches_settings.ajax_add_to_cart_nonce,
product_id: productId,
variation_id: variationId,
variation,
};
$(document.body).trigger('adding_to_cart', [ variant, data ]);
variant.removeClass('added').addClass('loading');
$.ajax({
type: 'POST',
url: cfvsw_swatches_settings.ajax_url,
data,
dataType: 'json',
success(response){
if(! response){
return;
}
if(response.error&&response.product_url){
window.location=response.product_url;
return;
}
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash,
variant,
]);
$(document.body).trigger('update_checkout');
variant.removeClass('loading').addClass('added');
},
error(errorThrown){
variant.removeClass('loading');
console.log(errorThrown);
},
});
}
$(document).on('change', '.cfvsw-hidden-select select', function (){
setTimeout(()=> {
updateSwatchesAvailability();
}, 1);
});
$('.reset_variations').on('click', function (){
resetSwatches($(this));
});
$(document).on({
mouseenter(){
const addToTooltip=$(this);
const tooltip=addToTooltip.data('tooltip');
if(''===tooltip ||
'undefined'===typeof tooltip ||
addToTooltip.hasClass('cfvsw-label-option')
){
return;
}
if(addToTooltip.children('.cfvsw-tooltip').length===0){
addToTooltip.prepend(`<div class="cfvsw-tooltip"><span class="cfvsw-tooltip-label">${ tooltip }</span></div>`
);
$('.cfvsw-tooltip').fadeIn(500);
const swatchHeight=addToTooltip
.children('.cfvsw-swatch-inner')
.innerHeight();
$('.cfvsw-tooltip').css({
bottom: swatchHeight,
});
if(cfvsw_swatches_settings.tooltip_image &&
addToTooltip.hasClass('cfvsw-image-option')
){
$('.cfvsw-tooltip').prepend("<span class='cfvsw-tooltip-preview'></span>"
);
const preview=addToTooltip
.children('.cfvsw-swatch-inner')
.css('backgroundImage');
$('.cfvsw-tooltip').css({
bottom: swatchHeight - 30,
padding: '2px',
});
$('.cfvsw-tooltip-preview').css({
backgroundImage: preview,
backgroundSize: 'cover',
});
}}
},
mouseleave(){
$('.cfvsw-tooltip').remove();
},
},
'.cfvsw-swatches-option'
);
$(document).on('ready', function (){
setTimeout(()=> {
setSwatchesSelection();
}, 1);
$('.woocommerce-widget-layered-nav-list').each(function (){
if($(this).find('.cfvsw-swatches-container').length){
$(this).addClass('cfvsw-filters');
}});
});
$('.cfvsw-shop-variations').on('click', function(e){
e.preventDefault();
});
$('.cfvsw-shop-variations .cfvsw-more-link').on('click', function(e){
window.location=e.target.href;
});
function updateSwatchesAvailability(){
$('.cfvsw-hidden-select select').each(function (){
const availableOptions=[];
$(this)
.children('option')
.each(function (){
if(''!==$(this).val()){
availableOptions.push($(this).val());
}});
$(this)
.parent()
.next()
.find('.cfvsw-swatches-option')
.each(function (){
if(-1===$.inArray($(this).attr('data-slug'),
availableOptions
)
){
$(this).addClass(addRemoveWithCommonClass);
}else{
$(this).removeClass(addRemoveWithCommonClass);
}});
});
}
function setSwatchesSelection(){
$('.cfvsw-hidden-select select').each(function (){
const selected=$(this).val();
$(this)
.parent()
.next()
.find(`[data-slug='${ selected }']`)
.trigger('click');
});
}
function resetSwatches(resetButton){
$('.cfvsw-swatches-option').each(function (){
$(this).removeClass('cfvsw-selected-swatch');
});
$('.cfvsw-selected-label').remove();
if(cfvsw_swatches_settings.disable_out_of_stock){
const table=resetButton.closest('table');
const findDisabledAttr=table.find(`.${ addRemoveDisableClass }`
);
const findDisableSelect=table.find('.disable-to-select');
if(findDisableSelect.length){
findDisableSelect.removeClass('disable-to-select');
}
if(findDisabledAttr){
findDisabledAttr.removeClass(addRemoveDisableClassCommon);
}
setTimeout(()=> {
SW.firstTime();
}, 20);
}}
function addVariationFunctionality(){
$('.cfvsw_variations_form:not(.variation-function-added)').each(function (){
const thisForm=$(this);
thisForm.addClass('variation-function-added');
thisForm.wc_variation_form();
thisForm.on('found_variation', function(e, variation){
updateThumbnail(thisForm, variation.image);
if(thisForm.attr('data-cfvsw-catalog')){
return;
}
updatePrice(thisForm, variation);
updatebuttonData(thisForm, variation);
});
}
);
}
$(window).on('load', function (){
addVariationFunctionality();
});
function updateThumbnail(swatch, imageData){
const listItem=swatch.closest('li');
const thumbnail=listItem.find('img:first');
if(0===listItem.find('.cfvsw-original-thumbnail').length){
const originalThumbnail=thumbnail.clone();
thumbnail.after('<span class="cfvsw-original-thumbnail"></span>');
listItem
.find('.cfvsw-original-thumbnail')
.html(originalThumbnail);
}
thumbnail.attr('src', imageData.thumb_src);
thumbnail.attr('srcset', '');
}
function resetThumbnail(swatch){
const listItem=swatch.closest('li');
if(listItem.find('.cfvsw-original-thumbnail').length){
const thumbnail=listItem.find('img:first');
thumbnail.replaceWith(listItem.find('.cfvsw-original-thumbnail').html()
);
listItem.find('.cfvsw-original-thumbnail').remove();
}}
function updatePrice(swatch, variation){
if(0===variation.price_html.length){
return;
}
if(swatch.parents('li').find('.cfvsw-original-price').length){
const price=swatch.parents('li').find('.price');
price.replaceWith(variation.price_html);
}else{
const price=swatch.parents('li').find('.price');
price.after(variation.price_html);
price.removeClass('price').addClass('cfvsw-original-price');
}}
function resetPrice(swatch){
if(swatch.parents('li').find('.cfvsw-original-price').length){
swatch.parents('li').find('.price').remove();
swatch
.parents('li')
.find('.cfvsw-original-price')
.removeClass('cfvsw-original-price')
.addClass('price');
}}
function updatebuttonData(variant, variation){
const select=variant.find('.variations select');
const data={};
const button=variant
.parents('li')
.find('.cfvsw_ajax_add_to_cart');
select.each(function (){
const attributeName =
$(this).data('attribute_name')||$(this).attr('name');
const value=$(this).val()||'';
data[ attributeName ]=value;
});
button.html(button.data('add_to_cart_text'));
button.addClass('cfvsw_variation_found');
button.attr('data-variation_id', variation.variation_id);
button.attr('data-selected_variant', JSON.stringify(data));
}
function resetButtonData(variant){
const button=variant
.parents('li')
.find('.cfvsw_ajax_add_to_cart');
button.html(button.data('select_options_text'));
button.removeClass('cfvsw_variation_found');
button.attr('data-variation_id', '');
button.attr('data-selected_variant', '');
}
SW.init();
document.addEventListener('astraInfinitePaginationLoaded', function (){
SW.firstTime();
addVariationFunctionality();
});
document.addEventListener('cfvswVariationLoad', function (){
SW.firstTime();
addVariationFunctionality();
});
})(jQuery);
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.sbjs=e()}}(function(){return function e(t,r,n){function a(s,o){if(!r[s]){if(!t[s]){var c="function"==typeof require&&require;if(!o&&c)return c(s,!0);if(i)return i(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var p=r[s]={exports:{}};t[s][0].call(p.exports,function(e){var r=t[s][1][e];return a(r||e)},p,p.exports,e,t,r,n)}return r[s].exports}for(var i="function"==typeof require&&require,s=0;s<n.length;s++)a(n[s]);return a}({1:[function(e,t,r){"use strict";var n=e("./init"),a={init:function(e){this.get=n(e),e&&e.callback&&"function"==typeof e.callback&&e.callback(this.get)}};t.exports=a},{"./init":6}],2:[function(e,t,r){"use strict";var n=e("./terms"),a=e("./helpers/utils"),i={containers:{current:"sbjs_current",current_extra:"sbjs_current_add",first:"sbjs_first",first_extra:"sbjs_first_add",session:"sbjs_session",udata:"sbjs_udata",promocode:"sbjs_promo"},service:{migrations:"sbjs_migrations"},delimiter:"|||",aliases:{main:{type:"typ",source:"src",medium:"mdm",campaign:"cmp",content:"cnt",term:"trm",id:"id",platform:"plt",format:"fmt",tactic:"tct"},extra:{fire_date:"fd",entrance_point:"ep",referer:"rf"},session:{pages_seen:"pgs",current_page:"cpg"},udata:{visits:"vst",ip:"uip",agent:"uag"},promo:"code"},pack:{main:function(e){return i.aliases.main.type+"="+e.type+i.delimiter+i.aliases.main.source+"="+e.source+i.delimiter+i.aliases.main.medium+"="+e.medium+i.delimiter+i.aliases.main.campaign+"="+e.campaign+i.delimiter+i.aliases.main.content+"="+e.content+i.delimiter+i.aliases.main.term+"="+e.term+i.delimiter+i.aliases.main.id+"="+e.id+i.delimiter+i.aliases.main.platform+"="+e.platform+i.delimiter+i.aliases.main.format+"="+e.format+i.delimiter+i.aliases.main.tactic+"="+e.tactic},extra:function(e){return i.aliases.extra.fire_date+"="+a.setDate(new Date,e)+i.delimiter+i.aliases.extra.entrance_point+"="+document.location.href+i.delimiter+i.aliases.extra.referer+"="+(document.referrer||n.none)},user:function(e,t){return i.aliases.udata.visits+"="+e+i.delimiter+i.aliases.udata.ip+"="+t+i.delimiter+i.aliases.udata.agent+"="+navigator.userAgent},session:function(e){return i.aliases.session.pages_seen+"="+e+i.delimiter+i.aliases.session.current_page+"="+document.location.href},promo:function(e){return i.aliases.promo+"="+a.setLeadingZeroToInt(a.randomInt(e.min,e.max),e.max.toString().length)}}};t.exports=i},{"./helpers/utils":5,"./terms":9}],3:[function(e,t,r){"use strict";var n=e("../data").delimiter;t.exports={useBase64:!1,setBase64Flag:function(e){this.useBase64=e},encodeData:function(e){return encodeURIComponent(e).replace(/\!/g,"%21").replace(/\~/g,"%7E").replace(/\*/g,"%2A").replace(/\'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")},decodeData:function(e){try{return decodeURIComponent(e).replace(/\%21/g,"!").replace(/\%7E/g,"~").replace(/\%2A/g,"*").replace(/\%27/g,"'").replace(/\%28/g,"(").replace(/\%29/g,")")}catch(t){try{return unescape(e)}catch(r){return""}}},set:function(e,t,r,n,a){var i,s;if(r){var o=new Date;o.setTime(o.getTime()+60*r*1e3),i="; expires="+o.toGMTString()}else i="";s=n&&!a?";domain=."+n:"";var c=this.encodeData(t);this.useBase64&&(c=btoa(c).replace(/=+$/,"")),document.cookie=this.encodeData(e)+"="+c+i+s+"; path=/"},get:function(e){for(var t=this.encodeData(e)+"=",r=document.cookie.split(";"),n=0;n<r.length;n++){for(var a=r[n];" "===a.charAt(0);)a=a.substring(1,a.length);if(0===a.indexOf(t)){var i=a.substring(t.length,a.length);if(/^[A-Za-z0-9+/]+$/.test(i))try{i=atob(i.padEnd(4*Math.ceil(i.length/4),"="))}catch(s){}return this.decodeData(i)}}return null},destroy:function(e,t,r){this.set(e,"",-1,t,r)},parse:function(e){var t=[],r={};if("string"==typeof e)t.push(e);else for(var a in e)e.hasOwnProperty(a)&&t.push(e[a]);for(var i=0;i<t.length;i++){var s;r[this.unsbjs(t[i])]={},s=this.get(t[i])?this.get(t[i]).split(n):[];for(var o=0;o<s.length;o++){var c=s[o].split("="),u=c.splice(0,1);u.push(c.join("=")),r[this.unsbjs(t[i])][u[0]]=this.decodeData(u[1])}}return r},unsbjs:function(e){return e.replace("sbjs_","")}}},{"../data":2}],4:[function(e,t,r){"use strict";t.exports={parse:function(e){for(var t=this.parseOptions,r=t.parser[t.strictMode?"strict":"loose"].exec(e),n={},a=14;a--;)n[t.key[a]]=r[a]||"";return n[t.q.name]={},n[t.key[12]].replace(t.q.parser,function(e,r,a){r&&(n[t.q.name][r]=a)}),n},parseOptions:{strictMode:!1,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}},getParam:function(e){for(var t={},r=(e||window.location.search.substring(1)).split("&"),n=0;n<r.length;n++){var a=r[n].split("=");if("undefined"==typeof t[a[0]])t[a[0]]=a[1];else if("string"==typeof t[a[0]]){var i=[t[a[0]],a[1]];t[a[0]]=i}else t[a[0]].push(a[1])}return t},getHost:function(e){return this.parse(e).host.replace("www.","")}}},{}],5:[function(e,t,r){"use strict";t.exports={escapeRegexp:function(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},setDate:function(e,t){var r=e.getTimezoneOffset()/60,n=e.getHours(),a=t||0===t?t:-r;return e.setHours(n+r+a),e.getFullYear()+"-"+this.setLeadingZeroToInt(e.getMonth()+1,2)+"-"+this.setLeadingZeroToInt(e.getDate(),2)+" "+this.setLeadingZeroToInt(e.getHours(),2)+":"+this.setLeadingZeroToInt(e.getMinutes(),2)+":"+this.setLeadingZeroToInt(e.getSeconds(),2)},setLeadingZeroToInt:function(e,t){for(var r=e+"";r.length<t;)r="0"+r;return r},randomInt:function(e,t){return Math.floor(Math.random()*(t-e+1))+e}}},{}],6:[function(e,t,r){"use strict";var n=e("./data"),a=e("./terms"),i=e("./helpers/cookies"),s=e("./helpers/uri"),o=e("./helpers/utils"),c=e("./params"),u=e("./migrations");t.exports=function(e){var t,r,p,f,m,d,l,g,h,y,_,v,b,x=c.fetch(e),k=s.getParam(),w=x.domain.host,q=x.domain.isolate,I=x.lifetime;function j(e){switch(e){case a.traffic.utm:t=a.traffic.utm,r="undefined"!=typeof k.utm_source?k.utm_source:"undefined"!=typeof k.gclid?"google":"undefined"!=typeof k.yclid?"yandex":a.none,p="undefined"!=typeof k.utm_medium?k.utm_medium:"undefined"!=typeof k.gclid?"cpc":"undefined"!=typeof k.yclid?"cpc":a.none,f="undefined"!=typeof k.utm_campaign?k.utm_campaign:"undefined"!=typeof k[x.campaign_param]?k[x.campaign_param]:"undefined"!=typeof k.gclid?"google_cpc":"undefined"!=typeof k.yclid?"yandex_cpc":a.none,m="undefined"!=typeof k.utm_content?k.utm_content:"undefined"!=typeof k[x.content_param]?k[x.content_param]:a.none,l=k.utm_id||a.none,g=k.utm_source_platform||a.none,h=k.utm_creative_format||a.none,y=k.utm_marketing_tactic||a.none,d="undefined"!=typeof k.utm_term?k.utm_term:"undefined"!=typeof k[x.term_param]?k[x.term_param]:function(){var e=document.referrer;if(k.utm_term)return k.utm_term;if(!(e&&s.parse(e).host&&s.parse(e).host.match(/^(?:.*\.)?yandex\..{2,9}$/i)))return!1;try{return s.getParam(s.parse(document.referrer).query).text}catch(t){return!1}}()||a.none;break;case a.traffic.organic:t=a.traffic.organic,r=r||s.getHost(document.referrer),p=a.referer.organic,f=a.none,m=a.none,d=a.none,l=a.none,g=a.none,h=a.none,y=a.none;break;case a.traffic.referral:t=a.traffic.referral,r=r||s.getHost(document.referrer),p=p||a.referer.referral,f=a.none,m=s.parse(document.referrer).path,d=a.none,l=a.none,g=a.none,h=a.none,y=a.none;break;case a.traffic.typein:t=a.traffic.typein,r=x.typein_attributes.source,p=x.typein_attributes.medium,f=a.none,m=a.none,d=a.none,l=a.none,g=a.none,h=a.none,y=a.none;break;default:t=a.oops,r=a.oops,p=a.oops,f=a.oops,m=a.oops,d=a.oops,l=a.oops,g=a.oops,h=a.oops,y=a.oops}var i={type:t,source:r,medium:p,campaign:f,content:m,term:d,id:l,platform:g,format:h,tactic:y};return n.pack.main(i)}function R(e){var t=document.referrer;switch(e){case a.traffic.organic:return!!t&&H(t)&&function(e){var t=new RegExp("^(?:.*\\.)?"+o.escapeRegexp("yandex")+"\\..{2,9}$"),n=new RegExp(".*"+o.escapeRegexp("text")+"=.*"),a=new RegExp("^(?:www\\.)?"+o.escapeRegexp("google")+"\\..{2,9}$");if(s.parse(e).query&&s.parse(e).host.match(t)&&s.parse(e).query.match(n))return r="yandex",!0;if(s.parse(e).host.match(a))return r="google",!0;if(!s.parse(e).query)return!1;for(var i=0;i<x.organics.length;i++){if(s.parse(e).host.match(new RegExp("^(?:.*\\.)?"+o.escapeRegexp(x.organics[i].host)+"$","i"))&&s.parse(e).query.match(new RegExp(".*"+o.escapeRegexp(x.organics[i].param)+"=.*","i")))return r=x.organics[i].display||x.organics[i].host,!0;if(i+1===x.organics.length)return!1}}(t);case a.traffic.referral:return!!t&&H(t)&&function(e){if(!(x.referrals.length>0))return r=s.getHost(e),!0;for(var t=0;t<x.referrals.length;t++){if(s.parse(e).host.match(new RegExp("^(?:.*\\.)?"+o.escapeRegexp(x.referrals[t].host)+"$","i")))return r=x.referrals[t].display||x.referrals[t].host,p=x.referrals[t].medium||a.referer.referral,!0;if(t+1===x.referrals.length)return r=s.getHost(e),!0}}(t);default:return!1}}function H(e){if(x.domain){if(q)return s.getHost(e)!==s.getHost(w);var t=new RegExp("^(?:.*\\.)?"+o.escapeRegexp(w)+"$","i");return!s.getHost(e).match(t)}return s.getHost(e)!==s.getHost(document.location.href)}function D(){i.set(n.containers.current_extra,n.pack.extra(x.timezone_offset),I,w,q),i.get(n.containers.first_extra)||i.set(n.containers.first_extra,n.pack.extra(x.timezone_offset),I,w,q)}return i.setBase64Flag(x.base64),u.go(I,w,q),i.set(n.containers.current,function(){var e;if("undefined"!=typeof k.utm_source||"undefined"!=typeof k.utm_medium||"undefined"!=typeof k.utm_campaign||"undefined"!=typeof k.utm_content||"undefined"!=typeof k.utm_term||"undefined"!=typeof k.utm_id||"undefined"!=typeof k.utm_source_platform||"undefined"!=typeof k.utm_creative_format||"undefined"!=typeof k.utm_marketing_tactic||"undefined"!=typeof k.gclid||"undefined"!=typeof k.yclid||"undefined"!=typeof k[x.campaign_param]||"undefined"!=typeof k[x.term_param]||"undefined"!=typeof k[x.content_param])D(),e=j(a.traffic.utm);else if(R(a.traffic.organic))D(),e=j(a.traffic.organic);else if(!i.get(n.containers.session)&&R(a.traffic.referral))D(),e=j(a.traffic.referral);else{if(i.get(n.containers.first)||i.get(n.containers.current))return i.get(n.containers.current);D(),e=j(a.traffic.typein)}return e}(),I,w,q),i.get(n.containers.first)||i.set(n.containers.first,i.get(n.containers.current),I,w,q),i.get(n.containers.udata)?(_=parseInt(i.parse(n.containers.udata)[i.unsbjs(n.containers.udata)][n.aliases.udata.visits])||1,_=i.get(n.containers.session)?_:_+1,v=n.pack.user(_,x.user_ip)):(_=1,v=n.pack.user(_,x.user_ip)),i.set(n.containers.udata,v,I,w,q),i.get(n.containers.session)?(b=parseInt(i.parse(n.containers.session)[i.unsbjs(n.containers.session)][n.aliases.session.pages_seen])||1,b+=1):b=1,i.set(n.containers.session,n.pack.session(b),x.session_length,w,q),x.promocode&&!i.get(n.containers.promocode)&&i.set(n.containers.promocode,n.pack.promo(x.promocode),I,w,q),i.parse(n.containers)}},{"./data":2,"./helpers/cookies":3,"./helpers/uri":4,"./helpers/utils":5,"./migrations":7,"./params":8,"./terms":9}],7:[function(e,t,r){"use strict";var n=e("./data"),a=e("./helpers/cookies");t.exports={go:function(e,t,r){var i,s=this.migrations,o={l:e,d:t,i:r};if(a.get(n.containers.first)||a.get(n.service.migrations)){if(!a.get(n.service.migrations))for(i=0;i<s.length;i++)s[i].go(s[i].id,o)}else{var c=[];for(i=0;i<s.length;i++)c.push(s[i].id);var u="";for(i=0;i<c.length;i++)u+=c[i]+"=1",i<c.length-1&&(u+=n.delimiter);a.set(n.service.migrations,u,o.l,o.d,o.i)}},migrations:[{id:"1418474375998",version:"1.0.0-beta",go:function(e,t){var r=e+"=1",i=e+"=0",s=function(e,t,r){return t||r?e:n.delimiter};try{var o=[];for(var c in n.containers)n.containers.hasOwnProperty(c)&&o.push(n.containers[c]);for(var u=0;u<o.length;u++)if(a.get(o[u])){var p=a.get(o[u]).replace(/(\|)?\|(\|)?/g,s);a.destroy(o[u],t.d,t.i),a.destroy(o[u],t.d,!t.i),a.set(o[u],p,t.l,t.d,t.i)}a.get(n.containers.session)&&a.set(n.containers.session,n.pack.session(0),t.l,t.d,t.i),a.set(n.service.migrations,r,t.l,t.d,t.i)}catch(f){a.set(n.service.migrations,i,t.l,t.d,t.i)}}}]}},{"./data":2,"./helpers/cookies":3}],8:[function(e,t,r){"use strict";var n=e("./terms"),a=e("./helpers/uri");t.exports={fetch:function(e){var t=e||{},r={};if(r.lifetime=this.validate.checkFloat(t.lifetime)||6,r.lifetime=parseInt(30*r.lifetime*24*60),r.session_length=this.validate.checkInt(t.session_length)||30,r.timezone_offset=this.validate.checkInt(t.timezone_offset),r.base64=t.base64||!1,r.campaign_param=t.campaign_param||!1,r.term_param=t.term_param||!1,r.content_param=t.content_param||!1,r.user_ip=t.user_ip||n.none,t.promocode?(r.promocode={},r.promocode.min=parseInt(t.promocode.min)||1e5,r.promocode.max=parseInt(t.promocode.max)||999999):r.promocode=!1,t.typein_attributes&&t.typein_attributes.source&&t.typein_attributes.medium?(r.typein_attributes={},r.typein_attributes.source=t.typein_attributes.source,r.typein_attributes.medium=t.typein_attributes.medium):r.typein_attributes={source:"(direct)",medium:"(none)"},t.domain&&this.validate.isString(t.domain)?r.domain={host:t.domain,isolate:!1}:t.domain&&t.domain.host?r.domain=t.domain:r.domain={host:a.getHost(document.location.hostname),isolate:!1},r.referrals=[],t.referrals&&t.referrals.length>0)for(var i=0;i<t.referrals.length;i++)t.referrals[i].host&&r.referrals.push(t.referrals[i]);if(r.organics=[],t.organics&&t.organics.length>0)for(var s=0;s<t.organics.length;s++)t.organics[s].host&&t.organics[s].param&&r.organics.push(t.organics[s]);return r.organics.push({host:"bing.com",param:"q",display:"bing"}),r.organics.push({host:"yahoo.com",param:"p",display:"yahoo"}),r.organics.push({host:"about.com",param:"q",display:"about"}),r.organics.push({host:"aol.com",param:"q",display:"aol"}),r.organics.push({host:"ask.com",param:"q",display:"ask"}),r.organics.push({host:"globososo.com",param:"q",display:"globo"}),r.organics.push({host:"go.mail.ru",param:"q",display:"go.mail.ru"}),r.organics.push({host:"rambler.ru",param:"query",display:"rambler"}),r.organics.push({host:"tut.by",param:"query",display:"tut.by"}),r.referrals.push({host:"t.co",display:"twitter.com"}),r.referrals.push({host:"plus.url.google.com",display:"plus.google.com"}),r},validate:{checkFloat:function(e){return!(!e||!this.isNumeric(parseFloat(e)))&&parseFloat(e)},checkInt:function(e){return!(!e||!this.isNumeric(parseInt(e)))&&parseInt(e)},isNumeric:function(e){return!isNaN(e)},isString:function(e){return"[object String]"===Object.prototype.toString.call(e)}}}},{"./helpers/uri":4,"./terms":9}],9:[function(e,t,r){"use strict";t.exports={traffic:{utm:"utm",organic:"organic",referral:"referral",typein:"typein"},referer:{referral:"referral",organic:"organic",social:"social"},none:"(none)",oops:"(Houston, we have a problem)"}},{}]},{},[1])(1)});
!function(t){"use strict";const e=t.params,n=(document.querySelector.bind(document),(t,e)=>e.split(".").reduce((t,e)=>t&&t[e],t)),i=()=>null,s=t=>null===t||t===undefined?"":t,o="wc/store/checkout";function a(t){document.querySelectorAll("wc-order-attribution-inputs").forEach((t,e)=>{e>0&&t.remove()});for(const e of document.querySelectorAll("wc-order-attribution-inputs"))e.values=t}function r(t){window.wp&&window.wp.data&&window.wp.data.dispatch&&window.wc&&window.wc.wcBlocksData&&window.wp.data.dispatch(window.wc.wcBlocksData.CHECKOUT_STORE_KEY).setExtensionData("woocommerce/order-attribution",t,!0)}function c(){return"undefined"!=typeof sbjs}function d(){if(window.wp&&window.wp.data&&"function"==typeof window.wp.data.subscribe){const e=window.wp.data.subscribe(function(){e(),r(t.getAttributionData())},o)}}t.getAttributionData=function(){const s=e.allowTracking&&c()?n:i,o=c()?sbjs.get:{},a=Object.entries(t.fields).map(([t,e])=>[t,s(o,e)]);return Object.fromEntries(a)},t.setOrderTracking=function(n){if(e.allowTracking=n,n){if(!c())return;sbjs.init({lifetime:Number(e.lifetime),session_length:Number(e.session),base64:Boolean(e.base64),timezone_offset:"0"})}else!function(){const t=window.location.hostname;["sbjs_current","sbjs_current_add","sbjs_first","sbjs_first_add","sbjs_session","sbjs_udata","sbjs_migrations","sbjs_promo"].forEach(e=>{document.cookie=`${e}=; path=/; max-age=-999; domain=.${t};`})}();const i=t.getAttributionData();a(i),r(i)},t.setOrderTracking(e.allowTracking),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",d):d(),window.customElements.define("wc-order-attribution-inputs",class extends HTMLElement{constructor(){if(super(),this._fieldNames=Object.keys(t.fields),this.hasOwnProperty("_values")){let t=this.values;delete this.values,this.values=t||{}}}connectedCallback(){this.innerHTML="";const t=new DocumentFragment;for(const n of this._fieldNames){const i=document.createElement("input");i.type="hidden",i.name=`${e.prefix}${n}`,i.value=s(this.values&&this.values[n]||""),t.appendChild(i)}this.appendChild(t)}set values(t){if(this._values=t,this.isConnected)for(const t of this._fieldNames){const n=this.querySelector(`input[name="${e.prefix}${t}"]`);n?n.value=s(this.values[t]):console.warn(`Field "${t}" not found. `+"Most likely, the '<wc-order-attribution-inputs>' element was manipulated.")}}get values(){return this._values}})}(window.wc_order_attribution);
(function(window, document, $){
'use strict';
var TMEPOJS;
var tcAPI;
$(function(){
TMEPOJS=window.TMEPOJS||null;
tcAPI=$.tcAPI ? $.tcAPI():null;
if(! TMEPOJS||! tcAPI){
return;
}
$('body').on('sober_quickview_opened', function(){
var product_id;
var epo_id;
var tmLazyloadContainer;
tmLazyloadContainer=$('#quick-view-modal');
$.tcepo.tmLazyloadContainer(tmLazyloadContainer);
product_id=tmLazyloadContainer.find(tcAPI.epoSelector).attr('data-product-id');
epo_id=tmLazyloadContainer.find(tcAPI.epoSelector).attr('data-epo-id');
$.tcepo.tm_init_epo(tmLazyloadContainer, true, product_id, epo_id);
$(window).trigger('tmlazy');
$(window).trigger('tm_epo_loaded_quickview');
if($.jMaskGlobals){
tmLazyloadContainer.find($.jMaskGlobals.maskElements).each(function(){
var t=$(this);
if(t.attr('data-mask')){
t.mask(t.attr('data-mask'));
}});
}});
if(window.ctEvents){
window.ctEvents.on('blocksy:frontend:init', function(){
var qv_container=TMEPOJS.quickview_array||'null';
var fromaddons=TMEPOJS.quickview_container||'null';
var added={};
var selectors;
var container;
var product_id;
var epo_id;
var noProductCheck;
var time=1;
var key='blocsky_get_woo_quick_view';
var tmLazyloadContainer;
$('.tm-formepo-normal').remove();
$('.tm-formepo').remove();
qv_container=$.epoAPI.util.parseJSON(qv_container);
fromaddons=$.epoAPI.util.parseJSON(fromaddons);
for(selectors in fromaddons){
if(Object.prototype.hasOwnProperty.call(fromaddons, selectors)){
added[ fromaddons[ selectors ][ 0 ] ]=$(fromaddons[ selectors ][ 1 ]);
}}
$.extend(qv_container, added);
noProductCheck=false;
container=$(qv_container[ key ]);
if(container.find('.product').length===0&&container.is('.product')){
noProductCheck=true;
}
if(container.length&&(container.find('.product').length > 0||noProductCheck)){
container.removeClass('tc-init');
tmLazyloadContainer=container;
$.tcepo.tmLazyloadContainer(tmLazyloadContainer);
setTimeout(function(){
product_id=tmLazyloadContainer.find(tcAPI.epoSelector).attr('data-product-id');
epo_id=tmLazyloadContainer.find(tcAPI.epoSelector).attr('data-epo-id');
if(key==='woodmart_quick_shop'){
container.addClass('has-options');
}
tcAPI.getElementFromFieldCache=[];
$.tcepo.tm_init_epo(tmLazyloadContainer, true, product_id, epo_id);
$(window).trigger('tmlazy');
$(window).trigger('tm_epo_loaded_quickview');
if($.jMaskGlobals){
tmLazyloadContainer.find($.jMaskGlobals.maskElements).each(function(){
var t=$(this);
if(t.attr('data-mask')){
t.mask(t.attr('data-mask'));
}});
}}, time);
}});
}});
}(window, document, window.jQuery));