// Base64 script - helps encoding unicode characters, so it can be sent to the server, without hitting POST max vars limitations
(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory(global):typeof define==="function"&&define.amd?define(factory):factory(global)})(typeof self!=="undefined"?self:typeof window!=="undefined"?window:typeof global!=="undefined"?global:this,function(global){"use strict";global=global||{};var _Base64=global.Base64;var version="2.5.2";var buffer;if(typeof module!=="undefined"&&module.exports){try{buffer=eval("require('buffer').Buffer")}catch(err){buffer=undefined}}var b64chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var b64tab=function(bin){var t={};for(var i=0,l=bin.length;i<l;i++)t[bin.charAt(i)]=i;return t}(b64chars);var fromCharCode=String.fromCharCode;var cb_utob=function(c){if(c.length<2){var cc=c.charCodeAt(0);return cc<128?c:cc<2048?fromCharCode(192|cc>>>6)+fromCharCode(128|cc&63):fromCharCode(224|cc>>>12&15)+fromCharCode(128|cc>>>6&63)+fromCharCode(128|cc&63)}else{var cc=65536+(c.charCodeAt(0)-55296)*1024+(c.charCodeAt(1)-56320);return fromCharCode(240|cc>>>18&7)+fromCharCode(128|cc>>>12&63)+fromCharCode(128|cc>>>6&63)+fromCharCode(128|cc&63)}};var re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;var utob=function(u){return u.replace(re_utob,cb_utob)};var cb_encode=function(ccc){var padlen=[0,2,1][ccc.length%3],ord=ccc.charCodeAt(0)<<16|(ccc.length>1?ccc.charCodeAt(1):0)<<8|(ccc.length>2?ccc.charCodeAt(2):0),chars=[b64chars.charAt(ord>>>18),b64chars.charAt(ord>>>12&63),padlen>=2?"=":b64chars.charAt(ord>>>6&63),padlen>=1?"=":b64chars.charAt(ord&63)];return chars.join("")};var btoa=global.btoa?function(b){return global.btoa(b)}:function(b){return b.replace(/[\s\S]{1,3}/g,cb_encode)};var _encode=function(u){var isUint8Array=Object.prototype.toString.call(u)==="[object Uint8Array]";return isUint8Array?u.toString("base64"):btoa(utob(String(u)))};var encode=function(u,urisafe){return!urisafe?_encode(u):_encode(String(u)).replace(/[+\/]/g,function(m0){return m0=="+"?"-":"_"}).replace(/=/g,"")};var encodeURI=function(u){return encode(u,true)};var re_btou=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;var cb_btou=function(cccc){switch(cccc.length){case 4:var cp=(7&cccc.charCodeAt(0))<<18|(63&cccc.charCodeAt(1))<<12|(63&cccc.charCodeAt(2))<<6|63&cccc.charCodeAt(3),offset=cp-65536;return fromCharCode((offset>>>10)+55296)+fromCharCode((offset&1023)+56320);case 3:return fromCharCode((15&cccc.charCodeAt(0))<<12|(63&cccc.charCodeAt(1))<<6|63&cccc.charCodeAt(2));default:return fromCharCode((31&cccc.charCodeAt(0))<<6|63&cccc.charCodeAt(1))}};var btou=function(b){return b.replace(re_btou,cb_btou)};var cb_decode=function(cccc){var len=cccc.length,padlen=len%4,n=(len>0?b64tab[cccc.charAt(0)]<<18:0)|(len>1?b64tab[cccc.charAt(1)]<<12:0)|(len>2?b64tab[cccc.charAt(2)]<<6:0)|(len>3?b64tab[cccc.charAt(3)]:0),chars=[fromCharCode(n>>>16),fromCharCode(n>>>8&255),fromCharCode(n&255)];chars.length-=[0,0,2,1][padlen];return chars.join("")};var _atob=global.atob?function(a){return global.atob(a)}:function(a){return a.replace(/\S{1,4}/g,cb_decode)};var atob=function(a){return _atob(String(a).replace(/[^A-Za-z0-9\+\/]/g,""))};var _decode=buffer?buffer.from&&Uint8Array&&buffer.from!==Uint8Array.from?function(a){return(a.constructor===buffer.constructor?a:buffer.from(a,"base64")).toString()}:function(a){return(a.constructor===buffer.constructor?a:new buffer(a,"base64")).toString()}:function(a){return btou(_atob(a))};var decode=function(a){return _decode(String(a).replace(/[-_]/g,function(m0){return m0=="-"?"+":"/"}).replace(/[^A-Za-z0-9\+\/]/g,""))};var noConflict=function(){var Base64=global.Base64;global.Base64=_Base64;return Base64};global.Base64={VERSION:version,atob:atob,btoa:btoa,fromBase64:decode,toBase64:encode,utob:utob,encode:encode,encodeURI:encodeURI,btou:btou,decode:decode,noConflict:noConflict,__buffer__:buffer};if(typeof Object.defineProperty==="function"){var noEnum=function(v){return{value:v,enumerable:false,writable:true,configurable:true}};global.Base64.extendString=function(){Object.defineProperty(String.prototype,"fromBase64",noEnum(function(){return decode(this)}));Object.defineProperty(String.prototype,"toBase64",noEnum(function(urisafe){return encode(this,urisafe)}));Object.defineProperty(String.prototype,"toBase64URI",noEnum(function(){return encode(this,true)}))}}if(global["Meteor"]){Base64=global.Base64}if(typeof module!=="undefined"&&module.exports){module.exports.Base64=global.Base64}else if(typeof define==="function"&&define.amd){define([],function(){return global.Base64})}return{Base64:global.Base64}});
// The msDropDown script - may have modifications over the original
// MSDropDown - jquery.dd.js
// author: Marghoob Suleman - http://www.marghoobsuleman.com/
// Date: 10 Nov, 2012
// Version: 3.5.2
// Revision: 27
// web: www.marghoobsuleman.com
/*
// msDropDown is free jQuery Plugin: you can redistribute it and/or modify
// it under the terms of the either the MIT License or the Gnu General Public License (GPL) Version 2
*/
var msBeautify = msBeautify || {};
sccWhenAvailable('jQuery', (function ($) {
	msBeautify = {
		version: {msDropdown:'3.5.2'},
		author: "Marghoob Suleman",
		counter: 20,
		debug: function (v) {
			if (v !== false) {
				$(".ddOutOfVision").css({height: 'auto', position: 'relative'});
			} else {
				$(".ddOutOfVision").css({height: '0px', position: 'absolute'});
			}
		},
		oldDiv: '',
		create: function (id, settings, type) {
			type = type || "dropdown";
			var data;
			switch (type.toLowerCase()) {
				case "dropdown":
				case "select":
				data = $(id).msDropdown(settings).data("dd-scc");
				break;
			}
			return data;
		}
	};
$.msDropDown = {}; //Legacy
$.msDropdown = {}; //camelCaps
$.extend(true, $.msDropDown, msBeautify);
$.extend(true, $.msDropdown, msBeautify);
// make compatibiliy with old and new jquery
if ($.fn.prop === undefined) {$.fn.prop = $.fn.attr;}
if ($.fn.on === undefined) {$.fn.on = $.fn.bind;$.fn.off = $.fn.unbind;}
if (typeof $.expr.createPseudo === 'function') {
	//jQuery 1.8  or greater
	$.expr[':'].Contains = $.expr.createPseudo(function (arg) {return function (elem) { return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; }; });
} else {
	//lower version
	$.expr[':'].Contains = function (a, i, m) {return $(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; };
}
//dropdown class
function dd(element, settings) {
	var settings = $.extend(true,
		{byJson: {data: null, selectedIndex: 0, name: null, size: 0, multiple: false, width: 250},
		mainCSS: 'dd-scc dd-scc-' + element.getAttribute('id').split('_')[element.getAttribute('id').split('_').length -1],
		height: 220, //not using currently
		visibleRows: 7,
		rowHeight: 0,
		showIcon: true,
		zIndex: 9998,
		useSprite: false,
		animStyle: 'slideDown',
		event:'click',
		openDirection: 'auto', //auto || alwaysUp || alwaysDown
		jsonTitle: true,
		style: '',
		disabledOpacity: 0.7,
		disabledOptionEvents: true,
		childWidth:0,
		enableCheckbox:false, //this needs to multiple or it will set element to multiple
		checkboxNameSuffix:'_mscheck',
		append:'',
		prepend:'',
		reverseMode:true, //it will update the msdropdown UI/value if you update the original dropdown - will be usefull if are using knockout.js or playing with original dropdown
		roundedCorner:true,
		enableAutoFilter:true,
		on: {create: null,open: null,close: null,add: null,remove: null,change: null,blur: null,click: null,dblclick: null,mousemove: null,mouseover: null,mouseout: null,focus: null,mousedown: null,mouseup: null}
	}, settings);
	var $this = this; //this class
	var holderId = {postElementHolder: '_msddHolder', postID: '_msdd', postTitleID: '_title',postTitleTextID: '_titleText', postChildID: '_child'};
	var css = {dd:settings.mainCSS, ddTitle: 'ddTitle', arrow: 'ddArrow arrowoff', ddChild: 'ddChild', ddTitleText: 'ddTitleText',disabled: 'disabled', enabled: 'enabled', ddOutOfVision: 'ddOutOfVision', borderTop: 'borderTop', noBorderTop: 'noBorderTop', selected: 'selected', divider: 'divider', optgroup: "optgroup", optgroupTitle: "optgroupTitle", description: "description", label: "ddlabel trn",hover: 'hover',disabledAll: 'disabledAll'};
	var css_i = {li: '_msddli_',borderRadiusTp: 'borderRadiusTp',ddChildMore: 'border shadow',fnone: "fnone"};
	var isList = false, isMultiple=false,isDisabled=false, cacheElement = {}, element, orginial = {}, isOpen=false;
	var DOWN_ARROW = 40, UP_ARROW = 38, LEFT_ARROW=37, RIGHT_ARROW=39, ESCAPE = 27, ENTER = 13, ALPHABETS_START = 47, SHIFT=16, CONTROL = 17, BACKSPACE=8, DELETE=46;
	var shiftHolded=false, controlHolded=false,lastTarget=null,forcedTrigger=false, oldSelected, isCreated = false;
	var doc = document, ua = window.navigator.userAgent, isIE = ua.match(/msie/i);
	settings.reverseMode = settings.reverseMode.toString();
	settings.roundedCorner = settings.roundedCorner.toString();
	var isArray = function(obj) {
		return (Object.prototype.toString.call(obj)=="[object Array]") ? true : false;
	};
	var msieversion = function()
	{
		var msie = ua.indexOf("MSIE");
      if ( msie > 0 ) {      // If Internet Explorer, return version number
      	return parseInt (ua.substring (msie+5, ua.indexOf (".", msie)));
	  } else {                // If another browser, return 0
	  	return 0;
	  };
	};
	var checkDataSetting = function() {
		settings.mainCSS = $("#"+element).data("maincss") || settings.mainCSS;
		settings.visibleRows = $("#"+element).data("visiblerows") || settings.visibleRows;
		if($("#"+element).data("showicon")==false) {settings.showIcon = $("#"+element).data("showicon");};
		settings.useSprite = $("#"+element).data("usesprite") || settings.useSprite;
		settings.animStyle = $("#"+element).data("animstyle") || settings.animStyle;
		settings.event = $("#"+element).data("event") || settings.event;
		settings.openDirection = $("#"+element).data("opendirection") || settings.openDirection;
		settings.jsonTitle = $("#"+element).data("jsontitle") || settings.jsonTitle;
		settings.disabledOpacity = $("#"+element).data("disabledopacity") || settings.disabledOpacity;
		settings.childWidth = $("#"+element).data("childwidth") || settings.childWidth;
		settings.enableCheckbox = $("#"+element).data("enablecheckbox") || settings.enableCheckbox;
		settings.checkboxNameSuffix = $("#"+element).data("checkboxnamesuffix") || settings.checkboxNameSuffix;
		settings.append = $("#"+element).data("append") || settings.append;
		settings.prepend = $("#"+element).data("prepend") || settings.prepend;
		settings.reverseMode = $("#"+element).data("reversemode") || settings.reverseMode;
		settings.roundedCorner = $("#"+element).data("roundedcorner") || settings.roundedCorner;
		settings.enableAutoFilter = $("#"+element).data("enableautofilter") || settings.enableAutoFilter;
		//make string
		settings.reverseMode = settings.reverseMode.toString();
		settings.roundedCorner = settings.roundedCorner.toString();
		settings.enableAutoFilter = settings.enableAutoFilter.toString();
	};
	var getElement = function(ele) {
		if (cacheElement[ele] === undefined) {
			cacheElement[ele] = doc.getElementById(ele);
		}
		return cacheElement[ele];
	};
	var getIndex = function(opt) {
		var childid = getPostID("postChildID");
		return $("#"+childid + " li."+css_i.li).index(opt);
	};
	var createByJson = function() {
		if (settings.byJson.data) {
			var validData = ["description","image","title"];
			try {
				if (!element.id) {
					element.id = "dropdown"+msBeautify.counter;
				};
				settings.byJson.data = eval(settings.byJson.data);
					//change element
					var id = "msdropdown"+(msBeautify.counter++);
					var obj = {};
					obj.id = id;
					obj.name = settings.byJson.name || element.id; //its name
					if (settings.byJson.size>0) {
						obj.size = settings.byJson.size;
					};
					obj.multiple = settings.byJson.multiple;
					var oSelect = createElement("select", obj);
					for(var i=0;i<settings.byJson.data.length;i++) {
						var current = settings.byJson.data[i];
						var opt = new Option(current.text, current.value);
						for(var p in current) {
							if (p.toLowerCase() != 'text') {
								var key = ($.inArray(p.toLowerCase(), validData)!=-1) ? "data-" : "";
								opt.setAttribute(key+p, current[p]);
							};
						};
						oSelect.options[i] = opt;
					};
					getElement(element.id).appendChild(oSelect);
					oSelect.selectedIndex = settings.byJson.selectedIndex;
					$(oSelect).css({width: settings.byJson.width+'px'});
					//now change element for access other things
					element = oSelect;
				} catch(e) {
					throw "There is an error in json data.";
				};
			};
		};
		var init = function() {
		 //set properties
		 createByJson();
		 if (!element.id) {
		 	element.id = "msdrpdd"+(msBeautify.counter++);
		 };
		 element = element.id;
		 $this.element = element;
		 checkDataSetting();
		 isDisabled = getElement(element).disabled;
		 var useCheckbox = settings.enableCheckbox;
		 if(useCheckbox.toString()==="true") {
		 	getElement(element).multiple = true;
		 	settings.enableCheckbox = true;
		 };
		 isList = (getElement(element).size>1 || getElement(element).multiple==true) ? true : false;
		//trace("isList "+isList);
		if (isList) {isMultiple = getElement(element).multiple;};
		mergeAllProp();
		//create layout
		createLayout();
		//set ui prop
		updateProp("uiData", getDataAndUI());
		updateProp("selectedOptions", $("#"+element +" option:selected"));
		var childid = getPostID("postChildID");
		oldSelected = $("#" + childid + " li." + css.selected);
		if(settings.reverseMode==="true") {
			$("#"+element).on("change", function() {
				setValue(this.selectedIndex);
			});
		};
		//add refresh method
		getElement(element).refresh = function(e) {
			$("#"+element).msDropdown().data("dd").refresh();
		};
	};
	/********************************************************************************************/
	var getPostID = function (id) {
		return element+holderId[id];
	};
	var getInternalStyle = function(ele) {
		var s = (ele.style === undefined) ? "" : ele.style.cssText;
		return s;
	};
	var parseOption = function(opt) {
		var imagePath = '', title ='', description='', value=-1, text='', className='', imagecss = '', index;
		if (opt !== undefined) {
			var attrTitle = opt.title || "";
			//data-title
			if (attrTitle!="") {
				var reg = /^\{.*\}$/;
				var isJson = reg.test(attrTitle);
				if (isJson && settings.jsonTitle) {
					var obj =  eval("["+attrTitle+"]");
				};
				title = (isJson && settings.jsonTitle) ? obj[0].title : title;
				description = (isJson && settings.jsonTitle) ? obj[0].description : description;
				imagePath = (isJson && settings.jsonTitle) ? obj[0].image : attrTitle;
				imagecss = (isJson && settings.jsonTitle) ? obj[0].imagecss : imagecss;
				index = opt.index;
			};
			text = opt.text || '';
			value = opt.value || '';
			className = opt.className || "";
			//ignore title attribute if playing with data tags
			title = $(opt).prop("data-title") || $(opt).data("title") || (title || "");
			description = $(opt).prop("data-description") || $(opt).data("description") || (description || "");
			imagePath = $(opt).prop("data-image") || $(opt).data("image") || (imagePath || "");
			imagecss = $(opt).prop("data-imagecss") || $(opt).data("imagecss") || (imagecss || "");
			index = $(opt).index();
		};
		var o = {image: imagePath, title: title, description: description, value: value, text: text, className: className, imagecss:imagecss, index:index};
		return o;
	};
	var createElement = function(nm, attr, html) {
		var tag = doc.createElement(nm);
		if (attr) {
			for(var i in attr) {
				switch(i) {
					case "style":
					tag.style.cssText = attr[i];
					break;
					default:
					tag[i]  = attr[i];
					break;
				};
			};
		};
		if (html) {
			tag.innerHTML = html;
		};
		return tag;
	};
	/********************************************************************************************/
	/*********************** <layout> *************************************/
	var hideOriginal = function() {
		var hidid = getPostID("postElementHolder");
		if ($("#"+hidid).length==0) {
			var obj = {style: 'height: 0px;overflow: hidden;position: absolute;',className: css.ddOutOfVision};
			obj.id = hidid;
			var oDiv = createElement("div", obj);
			$("#"+element).after(oDiv);
			$("#"+element).appendTo($("#"+hidid));
		} else {
			$("#"+hidid).css({height: 0,overflow: 'hidden',position: 'absolute'});
		};
		getElement(element).tabIndex = -1;
	};
	var createWrapper = function () {
		var brdRds = (settings.roundedCorner == "true") ? " borderRadius" : "";
		var obj = {
			className: css.dd + " ddcommon"+brdRds
		};
		var intcss = getInternalStyle(getElement(element));
		var w = $("#" + element).outerWidth();
		obj.style = "wwidth: " + w + "px;";
		if (intcss.length > 0) {
			obj.style = obj.style + "" + intcss;
		};
		obj.id = getPostID("postID");
		obj.tabIndex = getElement(element).tabIndex;
		var oDiv = createElement("div", obj);
		return oDiv;
	};
	var createTitle = function () {
		var selectedOption;
		if(getElement(element).selectedIndex>=0) {
			selectedOption = getElement(element).options[getElement(element).selectedIndex];
		} else {
			selectedOption = {value:'', text:''};
		}
		var spriteClass = "", selectedClass = "";
		//check sprite
		var useSprite = $("#"+element).data("usesprite");
		if(useSprite) { settings.useSprite = useSprite; };
		if (settings.useSprite != false) {
			spriteClass = " " + settings.useSprite;
			selectedClass = " " + selectedOption.className;
		};
		var brdRdsTp = (settings.roundedCorner == "true") ? " "+css_i.borderRadiusTp : "" ;
		var oTitle = createElement("div", {className: css.ddTitle + spriteClass + brdRdsTp});
		//divider
		var oDivider = createElement("span", {className: css.divider});
		//arrow
		var oArrow = createElement("span", {className: css.arrow});
		//title Text
		var titleid = getPostID("postTitleID");
		var oTitleText = createElement("span", {className: css.ddTitleText + selectedClass, id: titleid});
		var parsed = parseOption(selectedOption);
		var arrowPath = parsed.image;
		var sText = parsed.text || "";
		if (arrowPath != "" && settings.showIcon) {
			var oIcon = createElement("img");
			oIcon.src = arrowPath;
			if(parsed.imagecss!="") {
				oIcon.className = parsed.imagecss+" ";
			};
		};
		var oTitleText_in = createElement("span", {className: css.label}, sText);
		oTitle.appendChild(oDivider);
		oTitle.appendChild(oArrow);
		if (oIcon) {
			oTitleText.appendChild(oIcon);
		};
		oTitleText.appendChild(oTitleText_in);
		oTitle.appendChild(oTitleText);
		var oDescription = createElement("span", {className: css.description}, parsed.description);
		oTitleText.appendChild(oDescription);
		return oTitle;
	};
	var createFilterBox = function () {
		var tid = getPostID("postTitleTextID");
		var brdRds = (settings.roundedCorner == "true") ? "borderRadius" : "";
		var sText = createElement("input", {id: tid, type: 'text', value: '', autocomplete: 'off', className: 'text shadow '+brdRds, style: 'display: none'});
		return sText;
	};
	var createChild = function (opt) {
		var obj = {};
		var intcss = getInternalStyle(opt);
		if (intcss.length > 0) {obj.style = intcss; };
		var css2 = (opt.disabled) ? css.disabled : css.enabled;
		css2 = (opt.selected) ? (css2 + " " + css.selected) : css2;
		css2 = css2 + " " + css_i.li;
		obj.className = css2;
		if (settings.useSprite != false) {
			obj.className = css2 + " " + opt.className;
		};
		var li = createElement("li", obj);
		var parsed = parseOption(opt);
		if (parsed.title != "") {
			li.title = parsed.title;
		};
		var arrowPath = parsed.image;
		if (arrowPath != "" && settings.showIcon) {
			var oIcon = createElement("img");
			oIcon.src = arrowPath;
			if(parsed.imagecss!="") {
				oIcon.className = parsed.imagecss+" ";
			};
		};
		if (parsed.description != "") {
			var oDescription = createElement("span", {
				className: css.description
			}, parsed.description);
		};
		var sText = opt.text || "";
		var oTitleText = createElement("span", {
			className: css.label
		}, sText);
		//checkbox
		if(settings.enableCheckbox===true) {
			var chkbox = createElement("input", {
			type: 'checkbox', name:element+settings.checkboxNameSuffix+'[]', value:opt.value||"", className:"checkbox"}); //this can be used for future
			li.appendChild(chkbox);
			if(settings.enableCheckbox===true) {
				chkbox.checked = (opt.selected) ? true : false;
			};
		};
		if (oIcon) {
			li.appendChild(oIcon);
		};
		li.appendChild(oTitleText);
		if (oDescription) {
			li.appendChild(oDescription);
		} else {
			if (oIcon) {
				oIcon.className = oIcon.className+css_i.fnone;
			};
		};
		var oClear = createElement("div", {className: 'clear'});
		li.appendChild(oClear);
		return li;
	};
	var createChildren = function () {
		var childid = getPostID("postChildID");
		var obj = {className: css.ddChild + " ddchild_ " + css_i.ddChildMore, id: childid};
		if (isList == false) {
			obj.style = "z-index: " + settings.zIndex;
		} else {
			obj.style = "z-index:1";
		};
		var childWidth = $("#"+element).data("childwidth") || settings.childWidth;
		if(childWidth) {
			obj.style =  (obj.style || "") + ";width:"+childWidth;
		};
		var oDiv = createElement("div", obj);
		var ul = createElement("ul");
		if (settings.useSprite != false) {
			ul.className = settings.useSprite;
		};
		var allOptions = getElement(element).children;
		for (var i = 0; i < allOptions.length; i++) {
			var current = allOptions[i];
			var li;
			if (current.nodeName.toLowerCase() == "optgroup") {
				//create ul
				li = createElement("li", {className: css.optgroup});
				var span = createElement("span", {className: css.optgroupTitle}, current.label);
				li.appendChild(span);
				var optChildren = current.children;
				var optul = createElement("ul");
				for (var j = 0; j < optChildren.length; j++) {
					var opt_li = createChild(optChildren[j]);
					optul.appendChild(opt_li);
				};
				li.appendChild(optul);
			} else {
				li = createChild(current);
			};
			ul.appendChild(li);
		};
		oDiv.appendChild(ul);
		return oDiv;
	};
	var childHeight = function (val) {
		val = -1;
		var childid = getPostID("postChildID");
		if (val) {
			if (val == -1) { //auto
				$("#"+childid).css({height: "auto", overflow: "auto"});
			} else {
				$("#"+childid).css("height", val+"px");
			};
			return false;
		};
		//else return height
		var iHeight;
		var totalOptions = getElement(element).options.length;
		if (totalOptions > settings.visibleRows || settings.visibleRows) {
			var firstLI = $("#" + childid + " li:first");
			var margin = parseInt(firstLI.css("padding-bottom")) + parseInt(firstLI.css("padding-top"));
			if(settings.rowHeight===0) {
				$("#" + childid).css({visibility:'hidden',display:'block'}); //hack for first child
				settings.rowHeight = Math.ceil(firstLI.height());
				$("#" + childid).css({visibility:'visible'});
				if(!isList || settings.enableCheckbox===true) {
					$("#" + childid).css({display:'none'});
				};
			};
			iHeight = ((settings.rowHeight + margin) * Math.min(settings.visibleRows,totalOptions)) + 3;
		} else if (isList) {
			iHeight = $("#" + element).height(); //get height from original element
		};
		return iHeight;
	};
	var applyChildEvents = function () {
		var childid = getPostID("postChildID");
		$("#" + childid).on("click", function (e) {
			if (isDisabled === true) return false;
			//prevent body click
			e.preventDefault();
			e.stopPropagation();
			if (isList) {
				bind_on_events();
			};
		});
		$("#" + childid + " li." + css.enabled).on("click", function (e) {
			if(e.target.nodeName.toLowerCase() !== "input") {
				close(this);
			};
		});
		$("#" + childid + " li." + css.enabled).on("mousedown", function (e) {
			if (isDisabled === true) return false;
			oldSelected = $("#" + childid + " li." + css.selected);
			lastTarget = this;
			e.preventDefault();
			e.stopPropagation();
			//select current input
			if(settings.enableCheckbox===true) {
				if(e.target.nodeName.toLowerCase() === "input") {
					controlHolded = true;
				};
			};
			if (isList === true) {
				if (isMultiple) {
					if (shiftHolded === true) {
						$(this).addClass(css.selected);
						var selected = $("#" + childid + " li." + css.selected);
						var lastIndex = getIndex(this);
						if (selected.length > 1) {
							var items = $("#" + childid + " li." + css_i.li);
							var ind1 = getIndex(selected[0]);
							var ind2 = getIndex(selected[1]);
							if (lastIndex > ind2) {
								ind1 = (lastIndex);
								ind2 = ind2 + 1;
							};
							for (var i = Math.min(ind1, ind2); i <= Math.max(ind1, ind2); i++) {
								var current = items[i];
								if ($(current).hasClass(css.enabled)) {
									$(current).addClass(css.selected);
								};
							};
						};
					} else if (controlHolded === true) {
						$(this).toggleClass(css.selected); //toggle
						if(settings.enableCheckbox===true) {
							var checkbox = this.childNodes[0];
							checkbox.checked = !checkbox.checked; //toggle
						};
					} else {
						$("#" + childid + " li." + css.selected).removeClass(css.selected);
						$("#" + childid + " input:checkbox").prop("checked", false);
						$(this).addClass(css.selected);
						if(settings.enableCheckbox===true) {
							this.childNodes[0].checked = true;
						};
					};
				} else {
					$("#" + childid + " li." + css.selected).removeClass(css.selected);
					$(this).addClass(css.selected);
				};
				//fire event on mouseup
			} else {
				$("#" + childid + " li." + css.selected).removeClass(css.selected);
				$(this).addClass(css.selected);
			};
		});
		$("#" + childid + " li." + css.enabled).on("mouseenter", function (e) {
			if (isDisabled === true) return false;
			e.preventDefault();
			e.stopPropagation();
			if (lastTarget != null) {
				if (isMultiple) {
					$(this).addClass(css.selected);
					if(settings.enableCheckbox===true) {
						this.childNodes[0].checked = true;
					};
				};
			};
		});
		$("#" + childid + " li." + css.enabled).on("mouseover", function (e) {
			if (isDisabled === true) return false;
			$(this).addClass(css.hover);
		});
		$("#" + childid + " li." + css.enabled).on("mouseout", function (e) {
			if (isDisabled === true) return false;
			$("#" + childid + " li." + css.hover).removeClass(css.hover);
		});
		$("#" + childid + " li." + css.enabled).on("mouseup", function (e) {
			if (isDisabled === true) return false;
			e.preventDefault();
			e.stopPropagation();
			if(settings.enableCheckbox===true) {
				controlHolded = false;
			};
			var selected = $("#" + childid + " li." + css.selected).length;
			forcedTrigger = (oldSelected.length != selected || selected == 0) ? true : false;
			fireAfterItemClicked();
			unbind_on_events(); //remove old one
			bind_on_events();
			lastTarget = null;
		});
		/* options events */
		if (settings.disabledOptionEvents == false) {
			$("#" + childid + " li." + css_i.li).on("click", function (e) {
				if (isDisabled === true) return false;
				fireOptionEventIfExist(this, "click");
			});
			$("#" + childid + " li." + css_i.li).on("mouseenter", function (e) {
				if (isDisabled === true) return false;
				fireOptionEventIfExist(this, "mouseenter");
			});
			$("#" + childid + " li." + css_i.li).on("mouseover", function (e) {
				if (isDisabled === true) return false;
				fireOptionEventIfExist(this, "mouseover");
			});
			$("#" + childid + " li." + css_i.li).on("mouseout", function (e) {
				if (isDisabled === true) return false;
				fireOptionEventIfExist(this, "mouseout");
			});
			$("#" + childid + " li." + css_i.li).on("mousedown", function (e) {
				if (isDisabled === true) return false;
				fireOptionEventIfExist(this, "mousedown");
			});
			$("#" + childid + " li." + css_i.li).on("mouseup", function (e) {
				if (isDisabled === true) return false;
				fireOptionEventIfExist(this, "mouseup");
			});
		};
	};
	var removeChildEvents = function () {
		var childid = getPostID("postChildID");
		$("#" + childid).off("click");
		$("#" + childid + " li." + css.enabled).off("mouseenter");
		$("#" + childid + " li." + css.enabled).off("click");
		$("#" + childid + " li." + css.enabled).off("mouseover");
		$("#" + childid + " li." + css.enabled).off("mouseout");
		$("#" + childid + " li." + css.enabled).off("mousedown");
		$("#" + childid + " li." + css.enabled).off("mouseup");
	};
	var triggerBypassingHandler = function (id, evt_n, handler) {
		$("#" + id).off(evt_n, handler);
		$("#" + id).trigger(evt_n);
		$("#" + id).on(evt_n, handler);
	};
	var applyEvents = function () {
		var id = getPostID("postID");
		var tid = getPostID("postTitleTextID");
		var childid = getPostID("postChildID");
		$("#" + id).on(settings.event, function (e) {
			if (isDisabled === true) return false;
			fireEventIfExist(settings.event);
			//prevent body click
			e.preventDefault();
			e.stopPropagation();
			open(e);
		});
		$("#" + id).on("keydown", function (e) {
			var k = e.which;
			if (!isOpen && (k == ENTER || k == UP_ARROW || k == DOWN_ARROW ||
				k == LEFT_ARROW || k == RIGHT_ARROW ||
				(k >= ALPHABETS_START && !isList))) {
				open(e);
			if (k >= ALPHABETS_START) {
				showFilterBox();
			} else {
				e.preventDefault();
				e.stopImmediatePropagation();
			};
		};
	});
		$("#" + id).on("focus", wrapperFocusHandler);
		$("#" + id).on("blur", wrapperBlurHandler);
		$("#" + tid).on("blur", function (e) {
			//return focus to the wrapper without triggering the handler
			triggerBypassingHandler(id, "focus", wrapperFocusHandler);
		});
		applyChildEvents();
		$("#" + id).on("dblclick", on_dblclick);
		$("#" + id).on("mousemove", on_mousemove);
		$("#" + id).on("mouseenter", on_mouseover);
		$("#" + id).on("mouseleave", on_mouseout);
		$("#" + id).on("mousedown", on_mousedown);
		$("#" + id).on("mouseup", on_mouseup);
	};
	var wrapperFocusHandler = function (e) {
		fireEventIfExist("focus");
	};
	var wrapperBlurHandler = function (e) {
		fireEventIfExist("blur");
	};
	//after create
	var fixedForList = function () {
		var id = getPostID("postID");
		var childid = getPostID("postChildID");
		if (isList === true && settings.enableCheckbox===false) {
			$("#" + id + " ." + css.ddTitle).hide();
			$("#" + childid).css({display: 'block', position: 'relative'});
			//open();
		} else {
			if(settings.enableCheckbox===false) {
				isMultiple = false; //set multiple off if this is not a list
			};
			$("#" + id + " ." + css.ddTitle).show();
			$("#" + childid).css({display: 'none', position: 'absolute'});
			//set value
			var first = $("#" + childid + " li." + css.selected)[0];
			$("#" + childid + " li." + css.selected).removeClass(css.selected);
			var index = getIndex($(first).addClass(css.selected));
			setValue(index);
		};
		childHeight(childHeight()); //get and set height
	};
	var fixedForDisabled = function () {
		var id = getPostID("postID");
		var opc = (isDisabled == true) ? settings.disabledOpacity : 1;
		if (isDisabled === true) {
			$("#" + id).addClass(css.disabledAll);
		} else {
			$("#" + id).removeClass(css.disabledAll);
		};
	};
	var fixedSomeUI = function () {
		//auto filter
		var tid = getPostID("postTitleTextID");
		if(settings.enableAutoFilter=="true") {
			$("#" + tid).on("keyup", applyFilters);
		};
		//if is list
		fixedForList();
		fixedForDisabled();
	};
	var createLayout = function () {
		var oDiv = createWrapper();
		var oTitle = createTitle();
		oDiv.appendChild(oTitle);
		//auto filter box
		var oFilterBox = createFilterBox();
		oDiv.appendChild(oFilterBox);
		var oChildren = createChildren();
		oDiv.appendChild(oChildren);
		$("#" + element).after(oDiv);
		hideOriginal(); //hideOriginal
		fixedSomeUI();
		applyEvents();
		var childid = getPostID("postChildID");
		//append
		if(settings.append!='') {
			$("#" + childid).append(settings.append);
		};
		//prepend
		if(settings.prepend!='') {
			$("#" + childid).prepend(settings.prepend);
		};
		if (typeof settings.on.create == "function") {
			settings.on.create.apply($this, arguments);
		};
	};
	var selectUI_LI = function(indexes) {
		var childid = getPostID("postChildID");
		$("#" + childid + " li." + css_i.li).removeClass(css.selected);
		if(settings.enableCheckbox===true) {
			$("#" + childid + " li." + css_i.li + " input.checkbox").prop("checked", false);
		};
		if(isArray(indexes)===true) {
			for(var i=0;i<indexes.length;i++) {
				updateNow(indexes[i]);
			};
		} else {
			updateNow(indexes);
		};
		function updateNow(index) {
			$($("#" + childid + " li." + css_i.li)[index]).addClass(css.selected);
			if(settings.enableCheckbox===true) {
				$($("#" + childid + " li." + css_i.li)[index]).find("input.checkbox").prop("checked", "checked");
			};
		};
	};
	var selectMutipleOptions = function (bySelected, useIndexes) {
		var childid = getPostID("postChildID");
		var selected = bySelected || $("#" + childid + " li." + css.selected); //bySelected or by argument
		for (var i = 0; i < selected.length; i++) {
			var ind = (useIndexes===true) ? selected[i]  : getIndex(selected[i]);
			getElement(element).options[ind].selected = "selected";
		};
		setValue(selected);
	};
	var fireAfterItemClicked = function () {
		var childid = getPostID("postChildID");
		var selected = $("#" + childid + " li." + css.selected);
		if (isMultiple && (shiftHolded || controlHolded) || forcedTrigger) {
			getElement(element).selectedIndex = -1; //reset old
		};
		var index;
		if (selected.length == 0) {
			index = -1;
		} else if (selected.length > 1) {
			//selected multiple
			selectMutipleOptions(selected);
		} else {
			//if one selected
			index = getIndex($("#" + childid + " li." + css.selected));
		};
		if ((getElement(element).selectedIndex != index || forcedTrigger) && selected.length<=1) {
			forcedTrigger = false;
			var evt = has_handler("change");
			getElement(element).selectedIndex = index;
			setValue(index);
			//local
			if (typeof settings.on.change == "function") {
				var d = getDataAndUI();
				settings.on.change(d.data, d.ui);
			};
			$("#" + element).trigger("change");
		};
	};
	var setValue = function (index, byvalue) {
		if (index !== undefined) {
			var selectedIndex, value, selectedText;
			if (index == -1) {
				selectedIndex = -1;
				value = "";
				selectedText = "";
				updateTitleUI(-1);
			} else {
				//by index or byvalue
				if (typeof index != "object") {
					var opt = getElement(element).options[index];
					getElement(element).selectedIndex = index;
					selectedIndex = index;
					value = parseOption(opt);
					selectedText = (index >= 0) ? getElement(element).options[index].text : "";
					updateTitleUI(undefined, value);
					value = value.value; //for bottom
				} else {
					//this is multiple or by option
					selectedIndex = (byvalue && byvalue.index) || getElement(element).selectedIndex;
					value = (byvalue && byvalue.value) || getElement(element).value;
					selectedText = (byvalue && byvalue.text) || getElement(element).options[getElement(element).selectedIndex].text || "";
					updateTitleUI(selectedIndex);
					//check if this is multiple checkbox
				};
			};
			updateProp("selectedIndex", selectedIndex);
			updateProp("value", value);
			updateProp("selectedText", selectedText);
			updateProp("children", getElement(element).children);
			updateProp("uiData", getDataAndUI());
			updateProp("selectedOptions", $("#" + element + " option:selected"));
		}
	};
	var has_handler = function (name) {
		//True if a handler has been added in the html.
		var evt = {byElement: false, byJQuery: false, hasEvent: false};
		var obj = $("#" + element);
		try {
			if (obj.prop("on" + name) !== null) {
				evt.hasEvent = true;
				evt.byElement = true;
			};
		} catch(e) {
		}
		// True if a handler has been added using jQuery.
		var evs;
		if (typeof $._data == "function") { //1.8
			evs = $._data(obj[0], "events");
		} else {
			evs = obj.data("events");
		};
		if (evs && evs[name]) {
			evt.hasEvent = true;
			evt.byJQuery = true;
		};
		return evt;
	};
	var bind_on_events = function () {
		unbind_on_events();
		$("body").on("click", close);
		//bind more events
		$(document).on("keydown", on_keydown);
		$(document).on("keyup", on_keyup);
		//focus will work on this
	};
	var unbind_on_events = function () {
		$("body").off("click", close);
		//bind more events
		$(document).off("keydown", on_keydown);
		$(document).off("keyup", on_keyup);
	};
	var applyFilters = function (e) {
		if(e.keyCode < ALPHABETS_START && e.keyCode!=BACKSPACE && e.keyCode!=DELETE) {
			return false;
		};
		var childid = getPostID("postChildID");
		var tid = getPostID("postTitleTextID");
		var sText = getElement(tid).value;
		if (sText.length == 0) {
			$("#" + childid + " li:hidden").show(); //show if hidden
			childHeight(childHeight());
		} else {
			$("#" + childid + " li").hide();
			var items = $("#" + childid + " li:Contains('" + sText + "')").show();
			if ($("#" + childid + " li:visible").length <= settings.visibleRows) {
				childHeight(-1); //set autoheight
			};
			if (items.length > 0 && !isList || !isMultiple) {
				$("#" + childid + " ." + css.selected).removeClass(css.selected);
				$(items[0]).addClass(css.selected);
			};
		};
		if (!isList) {
			adjustOpen();
		};
	};
	var showFilterBox = function () {
		if(settings.enableAutoFilter=="true") {
			var id = getPostID("postID");
			var tid = getPostID("postTitleTextID");
			if ($("#" + tid + ":hidden").length > 0 && controlHolded == false) {
				$("#" + tid + ":hidden").show().val("");
				//blur the wrapper without triggering the handler
				triggerBypassingHandler(id, "blur", wrapperBlurHandler);
				getElement(tid).focus();
			};
		};
	};
	var hideFilterBox = function () {
		var tid = getPostID("postTitleTextID");
		if ($("#" + tid + ":visible").length > 0) {
			$("#" + tid + ":visible").hide();
			getElement(tid).blur();
		};
	};
	var on_keydown = function (evt) {
		var tid = getPostID("postTitleTextID");
		var childid = getPostID("postChildID");
		switch (evt.keyCode) {
			case DOWN_ARROW:
			case RIGHT_ARROW:
			evt.preventDefault();
			evt.stopPropagation();
				//hideFilterBox();
				next();
				break;
				case UP_ARROW:
				case LEFT_ARROW:
				evt.preventDefault();
				evt.stopPropagation();
				//hideFilterBox();
				previous();
				break;
				case ESCAPE:
				case ENTER:
				evt.preventDefault();
				evt.stopPropagation();
				close();
				var selected = $("#" + childid + " li." + css.selected).length;
				forcedTrigger = (oldSelected.length != selected || selected == 0) ? true : false;
				fireAfterItemClicked();
				unbind_on_events(); //remove old one
				lastTarget = null;
				break;
				case SHIFT:
				shiftHolded = true;
				break;
				case CONTROL:
				controlHolded = true;
				break;
				default:
				if (evt.keyCode >= ALPHABETS_START && isList === false) {
					showFilterBox();
				};
				break;
			};
			if (isDisabled === true) return false;
			fireEventIfExist("keydown");
		};
		var on_keyup = function (evt) {
			switch (evt.keyCode) {
				case SHIFT:
				shiftHolded = false;
				break;
				case CONTROL:
				controlHolded = false;
				break;
			};
			if (isDisabled === true) return false;
			fireEventIfExist("keyup");
		};
		var on_dblclick = function (evt) {
			if (isDisabled === true) return false;
			fireEventIfExist("dblclick");
		};
		var on_mousemove = function (evt) {
			if (isDisabled === true) return false;
			fireEventIfExist("mousemove");
		};
		var on_mouseover = function (evt) {
			if (isDisabled === true) return false;
			evt.preventDefault();
			fireEventIfExist("mouseover");
		};
		var on_mouseout = function (evt) {
			if (isDisabled === true) return false;
			evt.preventDefault();
			fireEventIfExist("mouseout");
		};
		var on_mousedown = function (evt) {
			if (isDisabled === true) return false;
			fireEventIfExist("mousedown");
		};
		var on_mouseup = function (evt) {
			if (isDisabled === true) return false;
			fireEventIfExist("mouseup");
		};
		var option_has_handler = function (opt, name) {
		//True if a handler has been added in the html.
		var evt = {byElement: false, byJQuery: false, hasEvent: false};
		if ($(opt).prop("on" + name) != undefined) {
			evt.hasEvent = true;
			evt.byElement = true;
		};
		// True if a handler has been added using jQuery.
		var evs = $(opt).data("events");
		if (evs && evs[name]) {
			evt.hasEvent = true;
			evt.byJQuery = true;
		};
		return evt;
	};
	var fireOptionEventIfExist = function (li, evt_n) {
		if (settings.disabledOptionEvents == false) {
			var opt = getElement(element).options[getIndex(li)];
			//check if original has some
			if (option_has_handler(opt, evt_n).hasEvent === true) {
				if (option_has_handler(opt, evt_n).byElement === true) {
					opt["on" + evt_n]();
				};
				if (option_has_handler(opt, evt_n).byJQuery === true) {
					switch (evt_n) {
						case "keydown":
						case "keyup":
							//key down/up will check later
							break;
							default:
							$(opt).trigger(evt_n);
							break;
						};
					};
					return false;
				};
			};
		};
		var fireEventIfExist = function (evt_n) {
		//local
		if (typeof settings.on[evt_n] == "function") {
			settings.on[evt_n].apply(this, arguments);
		};
		//check if original has some
		if (has_handler(evt_n).hasEvent === true) {
			if (has_handler(evt_n).byElement === true) {
				getElement(element)["on" + evt_n]();
			} else if (has_handler(evt_n).byJQuery === true) {
				switch (evt_n) {
					case "keydown":
					case "keyup":
						//key down/up will check later
						break;
						default:
						$("#" + element).triggerHandler(evt_n);
						break;
					};
				};
				return false;
			};
		};
		/******************************* navigation **********************************************/
		var scrollToIfNeeded = function (opt) {
			var childid = getPostID("postChildID");
		//if scroll is needed
		opt = (opt !== undefined) ? opt : $("#" + childid + " li." + css.selected);
		if (opt.length > 0) {
			var pos = parseInt(($(opt).position().top));
			var ch = parseInt($("#" + childid).height());
			if (pos > ch) {
				var top = pos + $("#" + childid).scrollTop() - (ch/2);
				$("#" + childid).animate({scrollTop:top}, 500);
			};
		};
	};
	var next = function () {
		var childid = getPostID("postChildID");
		var items = $("#" + childid + " li:visible." + css_i.li);
		var selected = $("#" + childid + " li:visible." + css.selected);
		selected = (selected.length==0) ? items[0] : selected;
		var index = $("#" + childid + " li:visible." + css_i.li).index(selected);
		if ((index < items.length - 1)) {
			index = getNext(index);
			if (index < items.length) { //check again - hack for last disabled
				if (!shiftHolded || !isList || !isMultiple) {
					$("#" + childid + " ." + css.selected).removeClass(css.selected);
				};
				$(items[index]).addClass(css.selected);
				updateTitleUI(index);
				if (isList == true) {
					fireAfterItemClicked();
				};
				scrollToIfNeeded($(items[index]));
			};
			if (!isList) {
				adjustOpen();
			};
		};
		function getNext(ind) {
			ind = ind + 1;
			if (ind > items.length) {
				return ind;
			};
			if ($(items[ind]).hasClass(css.enabled) === true) {
				return ind;
			};
			return ind = getNext(ind);
		};
	};
	var previous = function () {
		var childid = getPostID("postChildID");
		var selected = $("#" + childid + " li:visible." + css.selected);
		var items = $("#" + childid + " li:visible." + css_i.li);
		var index = $("#" + childid + " li:visible." + css_i.li).index(selected[0]);
		if (index >= 0) {
			index = getPrev(index);
			if (index >= 0) { //check again - hack for disabled
				if (!shiftHolded || !isList || !isMultiple) {
					$("#" + childid + " ." + css.selected).removeClass(css.selected);
				};
				$(items[index]).addClass(css.selected);
				updateTitleUI(index);
				if (isList == true) {
					fireAfterItemClicked();
				};
				if (parseInt(($(items[index]).position().top + $(items[index]).height())) <= 0) {
					var top = ($("#" + childid).scrollTop() - $("#" + childid).height()) - $(items[index]).height();
					$("#" + childid).animate({scrollTop: top}, 500);
				};
			};
			if (!isList) {
				adjustOpen();
			};
		};
		function getPrev(ind) {
			ind = ind - 1;
			if (ind < 0) {
				return ind;
			};
			if ($(items[ind]).hasClass(css.enabled) === true) {
				return ind;
			};
			return ind = getPrev(ind);
		};
	};
	var adjustOpen = function () {
		var id = getPostID("postID");
		var childid = getPostID("postChildID");
		var pos = $("#" + id).offset();
		var mH = $("#" + id).height();
		var wH = $(window).height();
		var st = $(window).scrollTop();
		var cH = $("#" + childid).height();
		var top = $("#" + id).height(); //this close so its title height
		var direction = settings.openDirection.toLowerCase();
		if (((wH + st) < Math.floor(cH + mH + pos.top) || direction == 'alwaysup') && direction != 'alwaysdown') {
			top = cH;
			$("#" + childid).css({top: "-" + top + "px", display: 'block', zIndex: settings.zIndex});
			if($("#" + id).find('.arrowoff:first, .ddUpArrow:first') && $("#" + id).find('.arrowoff:first, .ddUpArrow:first').length > 0){
				$($("#" + id).find('.ddUpArrow:first, .arrowoff:first')[0]).removeClass('ddUpArrow').addClass('ddArrow')
			}
			if(settings.roundedCorner == "true") {
				$("#" + id).removeClass("borderRadius borderRadiusTp").addClass("borderRadiusBtm");
			};
			var top = $("#" + childid).offset().top;
			if (top < -10) {
				$("#" + childid).css({top: (parseInt($("#" + childid).css("top")) - top + 20 + st) + "px", zIndex: settings.zIndex});
				if(settings.roundedCorner == "true") {
					$("#" + id).removeClass("borderRadiusBtm borderRadiusTp").addClass("borderRadius");
				};
			};
		} else {
			$("#" + childid).css({top: top + "px", zIndex: settings.zIndex});
			if(settings.roundedCorner == "true") {
				$("#" + id).removeClass("borderRadius borderRadiusBtm").addClass("borderRadiusTp");
				if($("#" + id).find('.ddArrow:first, .arrowoff:first') && $("#" + id).find('.ddArrow:first, .arrowoff:first').length > 0){
					$($("#" + id).find('.ddArrow:first, .arrowoff:first')[0]).removeClass('ddArrow').addClass('ddUpArrow')
				}
			};
		};
		//hack for ie zindex
		//i hate ie :D
		if(isIE) {
			if(msieversion()<=7) {
				$('div.ddcommon').css("zIndex", settings.zIndex-10);
				$("#" + id).css("zIndex", settings.zIndex+5);
			};
		};
	};
	var open = function (e) {
		if (isDisabled === true) return false;
		var id = getPostID("postID");
		var childid = getPostID("postChildID");
		if (!isOpen) {
			isOpen = true;
			if (msBeautify.oldDiv != '') {
				$("#" + msBeautify.oldDiv).css({display: "none"}); //hide all
			};
			msBeautify.oldDiv = childid;
			$("#" + childid + " li:hidden").show(); //show if hidden
			adjustOpen();
			var animStyle = settings.animStyle;
			if(animStyle=="" || animStyle=="none") {
				$("#" + childid).css({display:"block"});
				scrollToIfNeeded();
				if (typeof settings.on.open == "function") {
					var d = getDataAndUI();
					settings.on.open(d.data, d.ui);
				};
			} else {
				$("#" + childid)[animStyle]("fast", function () {
					scrollToIfNeeded();
					if (typeof settings.on.open == "function") {
						var d = getDataAndUI();
						settings.on.open(d.data, d.ui);
					};
				});
			};
			bind_on_events();
		} else {
			if(settings.event!=='mouseover') {
				close();
			};
		};
	};
	var close = function (e) {
		isOpen = false;
		var id = getPostID("postID");
		var childid = getPostID("postChildID");
		if (isList === false || settings.enableCheckbox===true) {
			$("#" + childid).css({display: "none"});
			if(settings.roundedCorner == "true") {
				$("#" + id).removeClass("borderRadiusTp borderRadiusBtm").addClass("borderRadius");
				if($("#" + id).find('.arrowoff:first, .ddUpArrow:first') && $("#" + id).find('.arrowoff:first, .ddUpArrow:first').length > 0){
					$($("#" + id).find('.ddUpArrow:first, .arrowoff:first')[0]).removeClass('ddUpArrow').addClass('ddArrow')
				}
			};
		};
		unbind_on_events();
		if (typeof settings.on.close == "function") {
			var d = getDataAndUI();
			settings.on.close(d.data, d.ui);
		};
		//rest some old stuff
		hideFilterBox();
		childHeight(childHeight()); //its needed after filter applied
		$("#" + childid).css({zIndex:1});
		//update the title in case the user clicked outside
		updateTitleUI(getElement(element).selectedIndex);
	};
	/*********************** </layout> *************************************/
	var mergeAllProp = function () {
		try {
			orginial = $.extend(true, {}, getElement(element));
			for (var i in orginial) {
				if (typeof orginial[i] != "function") {
					$this[i] = orginial[i]; //properties
				};
			};
		} catch(e) {
			//silent
		};
		$this.selectedText = (getElement(element).selectedIndex >= 0) ? getElement(element).options[getElement(element).selectedIndex].text : "";
		$this.version = msBeautify.version.msDropdown;
		$this.author = msBeautify.author;
	};
	var getDataAndUIByOption = function (opt) {
		if (opt != null && typeof opt != "undefined") {
			var childid = getPostID("postChildID");
			var data = parseOption(opt);
			var ui = $("#" + childid + " li." + css_i.li + ":eq(" + (opt.index) + ")");
			return {data: data, ui: ui, option: opt, index: opt.index};
		};
		return null;
	};
	var getDataAndUI = function () {
		var childid = getPostID("postChildID");
		var ele = getElement(element);
		var data, ui, option, index;
		if (ele.selectedIndex == -1) {
			data = null;
			ui = null;
			option = null;
			index = -1;
		} else {
			ui = $("#" + childid + " li." + css.selected);
			if (ui.length > 1) {
				var d = [], op = [], ind = [];
				for (var i = 0; i < ui.length; i++) {
					var pd = getIndex(ui[i]);
					d.push(pd);
					op.push(ele.options[pd]);
				};
				data = d;
				option = op;
				index = d;
			} else {
				option = ele.options[ele.selectedIndex];
				data = parseOption(option);
				index = ele.selectedIndex;
			};
		};
		return {data: data, ui: ui, index: index, option: option};
	};
	var updateTitleUI = function (index, byvalue) {
		var titleid = getPostID("postTitleID");
		var value = {};
		if (index == -1) {
			value.text = "&nbsp;";
			value.className = "";
			value.description = "";
			value.image = "";
		} else if (typeof index != "undefined") {
			var opt = getElement(element).options[index];
			value = parseOption(opt);
		} else {
			value = byvalue;
		};
		//update title and current
		if ( $("#" + titleid).children().length > 0 ) {
			var label = css.label
			if(label.indexOf('trn') != -1){
				label = label.replace('trn',',.trn')
			}
			var count = 0
			$("#" + titleid).find("." + label).each(function(index, ob){
				if(count == 0){
					$(ob).text(value.text);
				}
				count++
			})
		}else{
			$("#" + titleid).html('<span class="ddlabel trn" data-trn-key="' + value.text + '">'+ value.text +'</span><span class="description trn"> </span>');
		}
		getElement(titleid).className = css.ddTitleText + " " + value.className;
		//update desction
		if (value.description != "" && value.description != " ") {
			var descriptionExists = false
			$("#" + titleid).find("." + css.description).each(function(index, ob){
				descriptionExists = true
				$(ob).text(value.description);
				$(ob).show();
			})
			if(!descriptionExists){
				if ( $("#" + titleid).children().length > 0 ) {
					var label = css.label
					if(label.indexOf('trn') != -1){
						label = label.replace('trn',',.trn')
					}
					$( "span" ).insertAfter( $("#" + titleid).find("." + label + ':first') );
				}else{
					$("#" + titleid).html('')
					$("#" + titleid).append('<span class="ddlabel trn" data-trn-key="' + value.text + '">'+ value.text +'</span>')
					$("#" + titleid).append('<span class="description trn">'+ value.description +'</span>')
				}
			}
		} else {
			//$("#" + titleid).find("." + css.description).html("").hide();
		};
		//update icon
		var img = $("#" + titleid).find("img");
		if (img.length > 0) {
			$(img).remove();
		};
		if (value.image != "" && settings.showIcon) {
			img = createElement("img", {src: value.image});
			$("#" + titleid).prepend(img);
			if(value.imagecss!="") {
				img.className = value.imagecss+" ";
			};
			if (value.description == "") {
				img.className = img.className+css_i.fnone;
			};
		};
	};
	var updateProp = function (p, v) {
		$this[p] = v;
	};
	var updateUI = function (a, opt, i) { //action, index, opt
		var childid = getPostID("postChildID");
		var wasSelected = false;
		switch (a) {
			case "add":
			var li = createChild(opt || getElement(element).options[i]);
			var index;
			if (arguments.length == 3) {
				index = i;
			} else {
				index = $("#" + childid + " li." + css_i.li).length - 1;
			};
			if (index < 0 || !index) {
				$("#" + childid + " ul").append(li);
			} else {
				var at = $("#" + childid + " li." + css_i.li)[index];
				$(at).before(li);
			};
			removeChildEvents();
			applyChildEvents();
			if (settings.on.add != null) {
				settings.on.add.apply(this, arguments);
			};
			break;
			case "remove":
			wasSelected = $($("#" + childid + " li." + css_i.li)[i]).hasClass(css.selected);
			$("#" + childid + " li." + css_i.li + ":eq(" + i + ")").remove();
			var items = $("#" + childid + " li." + css.enabled);
			if (wasSelected == true) {
				if (items.length > 0) {
					$(items[0]).addClass(css.selected);
					var ind = $("#" + childid + " li." + css_i.li).index(items[0]);
					setValue(ind);
				};
			};
			if (items.length == 0) {
				setValue(-1);
			};
			if ($("#" + childid + " li." + css_i.li).length < settings.visibleRows && !isList) {
					childHeight(-1); //set autoheight
				};
				if (settings.on.remove != null) {
					settings.on.remove.apply(this, arguments);
				};
				break;
			};
		};
		/************************** public methods/events **********************/
		this.act = function () {
			var action = arguments[0];
			Array.prototype.shift.call(arguments);
			switch (action) {
				case "add":
				$this.add.apply(this, arguments);
				break;
				case "remove":
				$this.remove.apply(this, arguments);
				break;
				default:
				try {
					getElement(element)[action].apply(getElement(element), arguments);
				} catch (e) {
					//there is some error.
				};
				break;
			};
		};
		this.add = function () {
			var text, value, title, image, description;
			var obj = arguments[0];
			if (typeof obj == "string") {
				text = obj;
				value = text;
				opt = new Option(text, value);
			} else {
				text = obj.text || '';
				value = obj.value || text;
				title = obj.title || '';
				image = obj.image || '';
				description = obj.description || '';
			//image:imagePath, title:title, description:description, value:opt.value, text:opt.text, className:opt.className||""
			opt = new Option(text, value);
			$(opt).data("description", description);
			$(opt).data("image", image);
			$(opt).data("title", title);
		};
		arguments[0] = opt; //this option
		getElement(element).add.apply(getElement(element), arguments);
		updateProp("children", getElement(element)["children"]);
		updateProp("length", getElement(element).length);
		updateUI("add", opt, arguments[1]);
	};
	this.remove = function (i) {
		getElement(element).remove(i);
		updateProp("children", getElement(element)["children"]);
		updateProp("length", getElement(element).length);
		updateUI("remove", undefined, i);
	};
	this.set = function (prop, val) {
		if (typeof prop == "undefined" || typeof val == "undefined") return false;
		prop = prop.toString();
		try {
			updateProp(prop, val);
		} catch (e) {/*this is ready only */};
		switch (prop) {
			case "size":
			getElement(element)[prop] = val;
			if (val == 0) {
					getElement(element).multiple = false; //if size is zero multiple should be false
				};
				isList = (getElement(element).size > 1 || getElement(element).multiple == true) ? true : false;
				fixedForList();
				break;
				case "multiple":
				getElement(element)[prop] = val;
				isList = (getElement(element).size > 1 || getElement(element).multiple == true) ? true : false;
				isMultiple = getElement(element).multiple;
				fixedForList();
				updateProp(prop, val);
				break;
				case "disabled":
				getElement(element)[prop] = val;
				isDisabled = val;
				fixedForDisabled();
				break;
				case "selectedIndex":
				case "value":
				if(prop=="selectedIndex" && isArray(val)===true) {
					$("#"+element +" option").prop("selected", false);
					selectMutipleOptions(val, true);
					selectUI_LI(val); //setValue is being called from selectMutipleOptions
				} else {
					getElement(element)[prop] = val;
					selectUI_LI(getElement(element).selectedIndex);
					setValue(getElement(element).selectedIndex);
				};
				break;
				case "length":
				var childid = getPostID("postChildID");
				if (val < getElement(element).length) {
					getElement(element)[prop] = val;
					if (val == 0) {
						$("#" + childid + " li." + css_i.li).remove();
						setValue(-1);
					} else {
						$("#" + childid + " li." + css_i.li + ":gt(" + (val - 1) + ")").remove();
						if ($("#" + childid + " li." + css.selected).length == 0) {
							$("#" + childid + " li." + css.enabled + ":eq(0)").addClass(css.selected);
						};
					};
					updateProp(prop, val);
					updateProp("children", getElement(element)["children"]);
				};
				break;
				case "id":
				//please i need this. so preventing to change it. will work on this later
				break;
				default:
				//check if this is not a readonly properties
				try {
					getElement(element)[prop] = val;
					updateProp(prop, val);
				} catch (e) {
					//silent
				};
				break;
			};
		};
		this.get = function (prop) {
		return $this[prop] || getElement(element)[prop]; //return if local else from original
	};
	this.visible = function (val) {
		var id = getPostID("postID");
		if (val === true) {
			$("#" + id).show();
		} else if (val === false) {
			$("#" + id).hide();
		} else {
			return ($("#" + id).css("display")=="none") ? false : true;
		};
	};
	this.debug = function (v) {
		msBeautify.debug(v);
	};
	this.close = function () {
		close();
	};
	this.open = function () {
		open();
	};
	this.showRows = function (r) {
		if (typeof r == "undefined" || r == 0) {
			return false;
		};
		settings.visibleRows = r;
		childHeight(childHeight());
	};
	this.visibleRows = this.showRows;
	this.on = function (type, fn) {
		$("#" + element).on(type, fn);
	};
	this.off = function (type, fn) {
		$("#" + element).off(type, fn);
	};
	this.addMyEvent = this.on;
	this.getData = function () {
		return getDataAndUI()
	};
	this.namedItem = function () {
		var opt = getElement(element).namedItem.apply(getElement(element), arguments);
		return getDataAndUIByOption(opt);
	};
	this.item = function () {
		var opt = getElement(element).item.apply(getElement(element), arguments);
		return getDataAndUIByOption(opt);
	};
	//v 3.2
	this.setIndexByValue = function(val) {
		this.set("value", val);
	};
	this.destroy = function () {
		var hidid = getPostID("postElementHolder");
		var id = getPostID("postID");
		$("#" + id + ", #" + id + " *").off();
		getElement(element).tabIndex = getElement(id).tabIndex;
		$("#" + id).remove();
		$("#" + element).parent().replaceWith($("#" + element));
		$("#" + element).data("dd", null);
	};
	this.refresh = function() {
		setValue(getElement(element).selectedIndex);
	};
	//Create msDropDown
	init();
};
//bind in jquery
$.fn.extend({
	msDropDown: function(settings)
	{
		return this.each(function()
		{
			if (!$(this).data('dd')){
				var mydropdown = new dd(this, settings);
				$(this).data('dd', mydropdown);
			};
		});
	}
});
$.fn.msDropdown = $.fn.msDropDown; //make a copy
}));
/**
 * @file jquery.translate.js
 * @brief jQuery plugin to translate text in the client side.
 * @author Manuel Fernandes
 * @site
 * @version 0.9
 * @license MIT license <http://www.opensource.org/licenses/MIT>
 *
 * translate.js is a jQuery plugin to translate text in the client side.
 *
 */
 sccWhenAvailable('jQuery', (function($){
 	$.fn.translate = function(options) {
    var that = this; //a reference to ourselves
    var settings = {
    	css: "trn",
      lang: "en"/*,
      t: {
        "translate": {
          pt: "tradução",
          br: "tradução"
        }
    }*/
};
settings = $.extend(settings, options || {});
    if (settings.css.lastIndexOf(".", 0) !== 0)   //doesn't start with '.'
    	settings.css = "." + settings.css;
    var t = settings.t;
    this.lang = function(l) {
    	if (l) {
    		settings.lang = l;
        this.translate(settings);  //translate everything
    }
    return settings.lang;
};
this.get = function(index) {
	var res = index;
     // console.log(JSON.stringify(t))
     try {
     	res = t[index][settings.lang];
     }
     catch (err) {
        //not found, return index
        return index;
    }
    if (res)
    	return res;
    else
    	return index;
};
this.g = this.get;
    // old main
    this.find(settings.css).each(function(i) {
    	var $this = $(this);
    	var trn_key = $this.attr("data-trn-key");
    	if (!trn_key && !($this.hasClass('ddlabel'))) {
    		trn_key = $this.html();
      $this.attr("data-trn-key", trn_key);   //store key for next time
  }
  $this.hasClass('ddlabel') || $this.hasClass('description') ? $this.attr("data-trn-key", $this.html()).html(that.get($this.html())) : $this.html(that.get(trn_key));
  if($this.is( "option" )){
  	$this.text(that.get(trn_key));
  }
  if($this.is('span') && $this.hasClass('ddTitleText')){
  	var data_tr = $this.attr("data-trn-key")
  	if(data_tr.includes('span')){
  		$this.attr("data-trn-key",data_tr.split('>')[1].split('<')[0])
  		if($this.find('.ddlabel')[0]){
  			jQuery($this.find('.ddlabel')[0]).text(that.get($this.attr("data-trn-key")));
  		}
  	}
  }else if($this.is('span')){
  	var data_tr = $this.attr("data-trn-key")
  	if(!data_tr){
  		data_tr = that.get($this.text())
  	}else{
  		data_tr = that.get(data_tr)
  	}
  	$this.html(data_tr)
  }
  if($this.attr('placeholder') && $this.attr('placeholder').length && $this.attr('placeholder').length > 0){
  	$this.attr('placeholder', that.get($this.attr('placeholder')))
  }
  if($this.attr('data-checked') && $this.attr('data-unchecked')) {
  	$this.attr('data-checked', that.get($this.attr('data-checked')))
  	$this.attr('data-unchecked', that.get($this.attr('data-unchecked')))
  }
});
	// end od old main
	return this;
};
}));
// The bootstrap slider script. Has customization for the slider handle and price pubble
"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/*! =========================================================
 * bootstrap-slider.js
 *
 * Maintainers:
 *		Kyle Kemp
 *			- Twitter: @seiyria
 *			- Github:  seiyria
 *		Rohit Kalkur
 *			- Twitter: @Rovolutionary
 *			- Github:  rovolution
 *
 * =========================================================
 *
 * bootstrap-slider is released under the MIT License
 * Copyright (c) 2017 Kyle Kemp, Rohit Kalkur, and contributors
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * ========================================================= */
/**
 * Bridget makes jQuery widgets
 * v1.0.1
 * MIT license
 */
 var windowIsDefined = (typeof window === "undefined" ? "undefined" : _typeof(window)) === "object";
 (function (factory) {
 	if (typeof define === "function" && define.amd) {
 		define(["jquery"], factory);
 	} else if ((typeof module === "undefined" ? "undefined" : _typeof(module)) === "object" && module.exports) {
 		var jQuery;
 		try {
 			jQuery = require("jquery");
 		} catch (err) {
 			jQuery = null;
 		}
 		module.exports = factory(jQuery);
 	} else if (window) {
 		window.Slider = factory(window.jQuery);
 	}
 })(function ($) {
	// Constants
	var NAMESPACE_MAIN = 'slider';
	var NAMESPACE_ALTERNATE = 'bootstrapSlider';
	// Polyfill console methods
	if (windowIsDefined && !window.console) {
		window.console = {};
	}
	if (windowIsDefined && !window.console.log) {
		window.console.log = function () {};
	}
	if (windowIsDefined && !window.console.warn) {
		window.console.warn = function () {};
	}
	// Reference to Slider constructor
	var Slider;
	(function ($) {
		'use strict';
		// -------------------------- utils -------------------------- //
		var slice = Array.prototype.slice;
		function noop() {}
		// -------------------------- definition -------------------------- //
		function defineBridget($) {
			// bail if no jQuery
			if (!$) {
				return;
			}
			// -------------------------- addOptionMethod -------------------------- //
			/**
    * adds option method -> $().plugin('option', {...})
    * @param {Function} PluginClass - constructor class
    */
    function addOptionMethod(PluginClass) {
				// don't overwrite original option method
				if (PluginClass.prototype.option) {
					return;
				}
				// option setter
				PluginClass.prototype.option = function (opts) {
					// bail out if not an object
					if (!$.isPlainObject(opts)) {
						return;
					}
					this.options = $.extend(true, this.options, opts);
				};
			}
			// -------------------------- plugin bridge -------------------------- //
			// helper function for logging errors
			// $.error breaks jQuery chaining
			var logError = typeof console === 'undefined' ? noop : function (message) {
				console.error(message);
			};
			/**
    * jQuery plugin bridge, access methods like $elem.plugin('method')
    * @param {String} namespace - plugin name
    * @param {Function} PluginClass - constructor class
    */
    function bridge(namespace, PluginClass) {
				// add to jQuery fn namespace
				$.fn[namespace] = function (options) {
					if (typeof options === 'string') {
						// call plugin method when first argument is a string
						// get arguments for method
						var args = slice.call(arguments, 1);
						for (var i = 0, len = this.length; i < len; i++) {
							var elem = this[i];
							var instance = $.data(elem, namespace);
							if (!instance) {
								logError("cannot call methods on " + namespace + " prior to initialization; " + "attempted to call '" + options + "'");
								continue;
							}
							if (!$.isFunction(instance[options]) || options.charAt(0) === '_') {
								logError("no such method '" + options + "' for " + namespace + " instance");
								continue;
							}
							// trigger method with arguments
							var returnValue = instance[options].apply(instance, args);
							// break look and return first value if provided
							if (returnValue !== undefined && returnValue !== instance) {
								return returnValue;
							}
						}
						// return this if no return value
						return this;
					} else {
						var objects = this.map(function () {
							var instance = $.data(this, namespace);
							if (instance) {
								// apply options & init
								instance.option(options);
								instance._init();
							} else {
								// initialize new instance
								instance = new PluginClass(this, options);
								$.data(this, namespace, instance);
							}
							return $(this);
						});
						if (!objects || objects.length > 1) {
							return objects;
						} else {
							return objects[0];
						}
					}
				};
			}
			// -------------------------- bridget -------------------------- //
			/**
    * converts a Prototypical class into a proper jQuery plugin
    *   the class must have a ._init method
    * @param {String} namespace - plugin name, used in $().pluginName
    * @param {Function} PluginClass - constructor class
    */
    $.bridget = function (namespace, PluginClass) {
    	addOptionMethod(PluginClass);
    	bridge(namespace, PluginClass);
    };
    return $.bridget;
}
		// get jquery from browser global
		defineBridget($);
	})($);
	/*************************************************
 			BOOTSTRAP-SLIDER SOURCE CODE
 			**************************************************/
 			(function ($) {
 				var ErrorMsgs = {
 					formatInvalidInputErrorMsg: function formatInvalidInputErrorMsg(input) {
 						return "Invalid input value '" + input + "' passed in";
 					},
 					callingContextNotSliderInstance: "Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method"
 				};
 				var SliderScale = {
 					linear: {
 						toValue: function toValue(percentage) {
 							var rawValue = percentage / 100 * (this.options.max - this.options.min);
 							var shouldAdjustWithBase = true;
 							if (this.options.ticks_positions.length > 0) {
 								var minv,
 								maxv,
 								minp,
 								maxp = 0;
 								for (var i = 1; i < this.options.ticks_positions.length; i++) {
 									if (percentage <= this.options.ticks_positions[i]) {
 										minv = this.options.ticks[i - 1];
 										minp = this.options.ticks_positions[i - 1];
 										maxv = this.options.ticks[i];
 										maxp = this.options.ticks_positions[i];
 										break;
 									}
 								}
 								var partialPercentage = (percentage - minp) / (maxp - minp);
 								rawValue = minv + partialPercentage * (maxv - minv);
 								shouldAdjustWithBase = false;
 							}
 							var adjustment = shouldAdjustWithBase ? this.options.min : 0;
 							var value = adjustment + Math.round(rawValue / this.options.step) * this.options.step;
 							if (value < this.options.min) {
 								return this.options.min;
 							} else if (value > this.options.max) {
 								return this.options.max;
 							} else {
 								return value;
 							}
 						},
 						toPercentage: function toPercentage(value) {
 							if (this.options.max === this.options.min) {
 								return 0;
 							}
 							if (this.options.ticks_positions.length > 0) {
 								var minv,
 								maxv,
 								minp,
 								maxp = 0;
 								for (var i = 0; i < this.options.ticks.length; i++) {
 									if (value <= this.options.ticks[i]) {
 										minv = i > 0 ? this.options.ticks[i - 1] : 0;
 										minp = i > 0 ? this.options.ticks_positions[i - 1] : 0;
 										maxv = this.options.ticks[i];
 										maxp = this.options.ticks_positions[i];
 										break;
 									}
 								}
 								if (i > 0) {
 									var partialPercentage = (value - minv) / (maxv - minv);
 									return minp + partialPercentage * (maxp - minp);
 								}
 							}
 							return 100 * (value - this.options.min) / (this.options.max - this.options.min);
 						}
 					},
 					logarithmic: {
 						/* Based on http://stackoverflow.com/questions/846221/logarithmic-slider */
 						toValue: function toValue(percentage) {
 							var min = this.options.min === 0 ? 0 : Math.log(this.options.min);
 							var max = Math.log(this.options.max);
 							var value = Math.exp(min + (max - min) * percentage / 100);
 							if (Math.round(value) === this.options.max) {
 								return this.options.max;
 							}
 							value = this.options.min + Math.round((value - this.options.min) / this.options.step) * this.options.step;
					/* Rounding to the nearest step could exceed the min or
					* max, so clip to those values. */
					if (value < this.options.min) {
						return this.options.min;
					} else if (value > this.options.max) {
						return this.options.max;
					} else {
						return value;
					}
				},
				toPercentage: function toPercentage(value) {
					if (this.options.max === this.options.min) {
						return 0;
					} else {
						var max = Math.log(this.options.max);
						var min = this.options.min === 0 ? 0 : Math.log(this.options.min);
						var v = value === 0 ? 0 : Math.log(value);
						return 100 * (v - min) / (max - min);
					}
				}
			}
		};
		/*************************************************
  						CONSTRUCTOR
  						**************************************************/
  						Slider = function Slider(element, options) {
  							createNewSlider.call(this, element, options);
  							return this;
  						};
  						var calculator_id = -1
  						function createNewSlider(element, options) {
			/*
   	The internal state object is used to store data about the current 'state' of slider.
   	This includes values such as the `value`, `enabled`, etc...
   	*/
   	this._state = {
   		value: null,
   		enabled: null,
   		offset: null,
   		size: null,
   		percentage: null,
   		inDrag: false,
   		over: false
   	};
			// The objects used to store the reference to the tick methods if ticks_tooltip is on
			this.ticksCallbackMap = {};
			this.handleCallbackMap = {};
			if (typeof element === "string") {
				this.element = document.querySelector(element);
			} else if (element instanceof HTMLElement) {
				this.element = element;
			}
			/*************************************************
   					Process Options
   					**************************************************/
   					options = options ? options : {};
   					var optionTypes = Object.keys(this.defaultOptions);
   					for (var i = 0; i < optionTypes.length; i++) {
   						var optName = optionTypes[i];
				// First check if an option was passed in via the constructor
				var val = options[optName];
				// If no data attrib, then check data atrributes
				val = typeof val !== 'undefined' ? val : getDataAttrib(this.element, optName);
				// Finally, if nothing was specified, use the defaults
				val = val !== null ? val : this.defaultOptions[optName];
				// Set all options on the instance of the Slider
				if (!this.options) {
					this.options = {};
				}
				this.options[optName] = val;
			}
			// Check options.rtl
			if (this.options.rtl === 'auto') {
				this.options.rtl = window.getComputedStyle(this.element).direction === 'rtl';
			}
			/*
   	Validate `tooltip_position` against 'orientation`
   	- if `tooltip_position` is incompatible with orientation, swith it to a default compatible with specified `orientation`
   		-- default for "vertical" -> "right", "left" if rtl
   		-- default for "horizontal" -> "top"
   		*/
   		if (this.options.orientation === "vertical" && (this.options.tooltip_position === "top" || this.options.tooltip_position === "bottom")) {
   			if (this.options.rtl) {
   				this.options.tooltip_position = "left";
   			} else {
   				this.options.tooltip_position = "right";
   			}
   		} else if (this.options.orientation === "horizontal" && (this.options.tooltip_position === "left" || this.options.tooltip_position === "right")) {
   			this.options.tooltip_position = "top";
   		}
   		function getDataAttrib(element, optName) {
   			var dataName = "data-slider-" + optName.replace(/_/g, '-');
   			var dataValString = element.getAttribute(dataName);
   			if(optName === 'id') {
   				calculator_id = dataValString.split('-')[1]
   			}
   			try {
   				return JSON.parse(dataValString);
   			} catch (err) {
   				return dataValString;
   			}
   		}
			/*************************************************
   					Create Markup
   					**************************************************/
   					var origWidth = this.element.style.width;
   					var updateSlider = false;
   					var parent = this.element.parentNode;
   					var sliderTrackSelection;
   					var sliderTrackLow, sliderTrackHigh;
   					var sliderMinHandle;
   					var sliderMaxHandle;
   					if (this.sliderElem) {
   						updateSlider = true;
   					} else {
   						/* Create elements needed for slider */
   						this.sliderElem = document.createElement("div");
   						this.sliderElem.className = "slider";
   						/* Create slider track elements */
   						var sliderTrack = document.createElement("div");
   						sliderTrack.className = "slider-track";
   						sliderTrackLow = document.createElement("div");
   						sliderTrackLow.className = "slider-track-low";
				//getDataAttrib(this.sliderElemen, 'id')
				sliderTrackSelection = document.createElement("div");
				sliderTrackSelection.className = "slider-selection slider-selection-" + calculator_id;
				sliderTrackHigh = document.createElement("div");
				sliderTrackHigh.className = "slider-track-high";
				sliderMinHandle = document.createElement("div");
				sliderMinHandle.className = "slider-handle slider-handle_" + this.options.handlebackground + " min-slider-handle";
				sliderMinHandle.setAttribute('role', 'slider');
				sliderMinHandle.setAttribute('aria-valuemin', this.options.min);
				sliderMinHandle.setAttribute('aria-valuemax', this.options.max);
				sliderMaxHandle = document.createElement("div");
				sliderMaxHandle.className = "slider-handle max-slider-handle";
				sliderMaxHandle.setAttribute('role', 'slider');
				sliderMaxHandle.setAttribute('aria-valuemin', this.options.min);
				sliderMaxHandle.setAttribute('aria-valuemax', this.options.max);
				sliderTrack.appendChild(sliderTrackLow);
				sliderTrack.appendChild(sliderTrackSelection);
				sliderTrack.appendChild(sliderTrackHigh);
				/* Create highlight range elements */
				this.rangeHighlightElements = [];
				var rangeHighlightsOpts = this.options.rangeHighlights;
				if (Array.isArray(rangeHighlightsOpts) && rangeHighlightsOpts.length > 0) {
					for (var j = 0; j < rangeHighlightsOpts.length; j++) {
						var rangeHighlightElement = document.createElement("div");
						var customClassString = rangeHighlightsOpts[j].class || "";
						rangeHighlightElement.className = "slider-rangeHighlight slider-selection slider-selection-" + calculator_id + ' ' +customClassString;
						this.rangeHighlightElements.push(rangeHighlightElement);
						sliderTrack.appendChild(rangeHighlightElement);
					}
				}
				/* Add aria-labelledby to handle's */
				var isLabelledbyArray = Array.isArray(this.options.labelledby);
				if (isLabelledbyArray && this.options.labelledby[0]) {
					sliderMinHandle.setAttribute('aria-labelledby', this.options.labelledby[0]);
				}
				if (isLabelledbyArray && this.options.labelledby[1]) {
					sliderMaxHandle.setAttribute('aria-labelledby', this.options.labelledby[1]);
				}
				if (!isLabelledbyArray && this.options.labelledby) {
					sliderMinHandle.setAttribute('aria-labelledby', this.options.labelledby);
					sliderMaxHandle.setAttribute('aria-labelledby', this.options.labelledby);
				}
				/* Create ticks */
				this.ticks = [];
				if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) {
					this.ticksContainer = document.createElement('div');
					this.ticksContainer.className = 'slider-tick-container';
					for (i = 0; i < this.options.ticks.length; i++) {
						var tick = document.createElement('div');
						tick.className = 'slider-tick';
						if (this.options.ticks_tooltip) {
							var tickListenerReference = this._addTickListener();
							var enterCallback = tickListenerReference.addMouseEnter(this, tick, i);
							var leaveCallback = tickListenerReference.addMouseLeave(this, tick);
							this.ticksCallbackMap[i] = {
								mouseEnter: enterCallback,
								mouseLeave: leaveCallback
							};
						}
						this.ticks.push(tick);
						this.ticksContainer.appendChild(tick);
					}
					sliderTrackSelection.className += " tick-slider-selection";
				}
				this.tickLabels = [];
				if (Array.isArray(this.options.ticks_labels) && this.options.ticks_labels.length > 0) {
					this.tickLabelContainer = document.createElement('div');
					this.tickLabelContainer.className = 'slider-tick-label-container';
					for (i = 0; i < this.options.ticks_labels.length; i++) {
						var label = document.createElement('div');
						var noTickPositionsSpecified = this.options.ticks_positions.length === 0;
						var tickLabelsIndex = this.options.reversed && noTickPositionsSpecified ? this.options.ticks_labels.length - (i + 1) : i;
						label.className = 'slider-tick-label';
						label.innerHTML = this.options.ticks_labels[tickLabelsIndex];
						this.tickLabels.push(label);
						this.tickLabelContainer.appendChild(label);
					}
				}
				var createAndAppendTooltipSubElements = function createAndAppendTooltipSubElements(tooltipElem) {
					var arrow = document.createElement("div");
					arrow.className = "tooltip-arrow";
					var inner = document.createElement("div");
					inner.className = "tooltip-inner scc_inner_slider_t1";
					var baloon = document.createElement("div");
					baloon.className = "scc-slider-speech-bubble";
					baloon.innerHTML = "unset";
 					// baloon.setAttribute("style", "");
 					tooltipElem.appendChild(arrow);
 					tooltipElem.appendChild(inner);
 					tooltipElem.appendChild(baloon);
 				};
 				/* Create tooltip elements */
 				var sliderTooltip = document.createElement("div");
 				sliderTooltip.className = "tooltip tooltip-main";
 				sliderTooltip.setAttribute('role', 'presentation');
 				createAndAppendTooltipSubElements(sliderTooltip);
 				var sliderTooltipMin = document.createElement("div");
 				sliderTooltipMin.className = "tooltip tooltip-min";
 				sliderTooltipMin.setAttribute('role', 'presentation');
 				createAndAppendTooltipSubElements(sliderTooltipMin);
 				var sliderTooltipMax = document.createElement("div");
 				sliderTooltipMax.className = "tooltip tooltip-max";
 				sliderTooltipMax.setAttribute('role', 'presentation');
 				createAndAppendTooltipSubElements(sliderTooltipMax);
 				/* Append components to sliderElem */
 				this.sliderElem.appendChild(sliderTrack);
 				this.sliderElem.appendChild(sliderTooltip);
 				this.sliderElem.appendChild(sliderTooltipMin);
 				this.sliderElem.appendChild(sliderTooltipMax);
 				if (this.tickLabelContainer) {
 					this.sliderElem.appendChild(this.tickLabelContainer);
 				}
 				if (this.ticksContainer) {
 					this.sliderElem.appendChild(this.ticksContainer);
 				}
 				this.sliderElem.appendChild(sliderMinHandle);
 				this.sliderElem.appendChild(sliderMaxHandle);
 				/* Append slider element to parent container, right before the original <input> element */
 				parent.insertBefore(this.sliderElem, this.element);
 				/* Hide original <input> element */
 				this.element.style.display = "none !important";
 			}
 			/* If JQuery exists, cache JQ references */
 			if ($) {
 				this.$element = $(this.element);
 				this.$sliderElem = $(this.sliderElem);
 			}
			/*************************************************
   						Setup
   						**************************************************/
   						this.eventToCallbackMap = {};
   						this.sliderElem.id = this.options.id;
   						this.touchCapable = 'ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch;
   						this.touchX = 0;
   						this.touchY = 0;
   						this.tooltip = this.sliderElem.querySelector('.tooltip-main');
   						this.baloon = this.sliderElem.querySelector('.scc-slider-speech-bubble');
   						this.tooltipInner = this.tooltip.querySelector('.tooltip-inner');
   						this.tooltip_min = this.sliderElem.querySelector('.tooltip-min');
   						this.tooltipInner_min = this.tooltip_min.querySelector('.tooltip-inner');
   						this.tooltip_max = this.sliderElem.querySelector('.tooltip-max');
   						this.tooltipInner_max = this.tooltip_max.querySelector('.tooltip-inner');
   						if (SliderScale[this.options.scale]) {
   							this.options.scale = SliderScale[this.options.scale];
   						}
   						if (updateSlider === true) {
				// Reset classes
				this._removeClass(this.sliderElem, 'slider-horizontal');
				this._removeClass(this.sliderElem, 'slider-vertical');
				this._removeClass(this.sliderElem, 'slider-rtl');
				this._removeClass(this.tooltip, 'hide');
				this._removeClass(this.tooltip_min, 'hide');
				this._removeClass(this.tooltip_max, 'hide');
				// Undo existing inline styles for track
				["left", "right", "top", "width", "height"].forEach(function (prop) {
					this._removeProperty(this.trackLow, prop);
					this._removeProperty(this.trackSelection, prop);
					this._removeProperty(this.trackHigh, prop);
				}, this);
				// Undo inline styles on handles
				[this.handle1, this.handle2].forEach(function (handle) {
					this._removeProperty(handle, 'left');
					this._removeProperty(handle, 'right');
					this._removeProperty(handle, 'top');
				}, this);
				// Undo inline styles and classes on tooltips
				[this.tooltip, this.tooltip_min, this.tooltip_max].forEach(function (tooltip) {
					this._removeProperty(tooltip, 'left');
					this._removeProperty(tooltip, 'right');
					this._removeProperty(tooltip, 'top');
					this._removeClass(tooltip, 'right');
					this._removeClass(tooltip, 'left');
					this._removeClass(tooltip, 'top');
				}, this);
			}
			if (this.options.orientation === 'vertical') {
				this._addClass(this.sliderElem, 'slider-vertical');
				this.stylePos = 'top';
				this.mousePos = 'pageY';
				this.sizePos = 'offsetHeight';
			} else {
				this._addClass(this.sliderElem, 'slider-horizontal');
				this.sliderElem.style.width = origWidth;
				this.options.orientation = 'horizontal';
				if (this.options.rtl) {
					this.stylePos = 'right';
				} else {
					this.stylePos = 'left';
				}
				this.mousePos = 'clientX';
				this.sizePos = 'offsetWidth';
			}
			// specific rtl class
			if (this.options.rtl) {
				this._addClass(this.sliderElem, 'slider-rtl');
			}
			this._setTooltipPosition();
			/* In case ticks are specified, overwrite the min and max bounds */
			if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) {
				this.options.max = Math.max.apply(Math, this.options.ticks);
				this.options.min = Math.min.apply(Math, this.options.ticks);
			}
			if (Array.isArray(this.options.value)) {
				this.options.range = true;
				this._state.value = this.options.value;
			} else if (this.options.range) {
				// User wants a range, but value is not an array
				this._state.value = [this.options.value, this.options.max];
			} else {
				this._state.value = this.options.value;
			}
			this.trackLow = sliderTrackLow || this.trackLow;
			this.trackSelection = sliderTrackSelection || this.trackSelection;
			this.trackHigh = sliderTrackHigh || this.trackHigh;
			if (this.options.selection === 'none') {
				this._addClass(this.trackLow, 'hide');
				this._addClass(this.trackSelection, 'hide');
				this._addClass(this.trackHigh, 'hide');
			} else if (this.options.selection === 'after' || this.options.selection === 'before') {
				this._removeClass(this.trackLow, 'hide');
				this._removeClass(this.trackSelection, 'hide');
				this._removeClass(this.trackHigh, 'hide');
			}
			this.handle1 = sliderMinHandle || this.handle1;
			this.handle2 = sliderMaxHandle || this.handle2;
			if (updateSlider === true) {
				// Reset classes
				this._removeClass(this.handle1, 'round triangle');
				this._removeClass(this.handle2, 'round triangle hide');
				for (i = 0; i < this.ticks.length; i++) {
					this._removeClass(this.ticks[i], 'round triangle hide');
				}
			}
			var availableHandleModifiers = ['round', 'triangle', 'custom'];
			var isValidHandleType = availableHandleModifiers.indexOf(this.options.handle) !== -1;
			if (isValidHandleType) {
				this._addClass(this.handle1, this.options.handle);
				this._addClass(this.handle2, this.options.handle);
				for (i = 0; i < this.ticks.length; i++) {
					this._addClass(this.ticks[i], this.options.handle);
				}
			}
			this._state.offset = this._offset(this.sliderElem);
			this._state.size = this.sliderElem[this.sizePos];
			this.setValue(this._state.value);
			/******************************************
   				Bind Event Listeners
   				******************************************/
			// Bind keyboard handlers
			this.handle1Keydown = this._keydown.bind(this, 0);
			this.handle1.addEventListener("keydown", this.handle1Keydown, false);
			this.handle2Keydown = this._keydown.bind(this, 1);
			this.handle2.addEventListener("keydown", this.handle2Keydown, false);
			this.mousedown = this._mousedown.bind(this);
			this.touchstart = this._touchstart.bind(this);
			this.touchmove = this._touchmove.bind(this);
			if (this.touchCapable) {
				// Test for passive event support
				var supportsPassive = false;
				try {
					var opts = Object.defineProperty({}, 'passive', {
						get: function get() {
							supportsPassive = true;
						}
					});
					window.addEventListener("test", null, opts);
				} catch (e) {}
				// Use our detect's results. passive applied if supported, capture will be false either way.
				var eventOptions = supportsPassive ? { passive: true } : false;
				// Bind touch handlers
				this.sliderElem.addEventListener("touchstart", this.touchstart, eventOptions);
				this.sliderElem.addEventListener("touchmove", this.touchmove, eventOptions);
			}
			this.sliderElem.addEventListener("mousedown", this.mousedown, false);
			// Bind window handlers
			this.resize = this._resize.bind(this);
			window.addEventListener("resize", this.resize, false);
			// Bind tooltip-related handlers
			if (this.options.tooltip === 'hide') {
				this._addClass(this.tooltip, 'hide');
				this._addClass(this.tooltip_min, 'hide');
				this._addClass(this.tooltip_max, 'hide');
			} else if (this.options.tooltip === 'always') {
				this._showTooltip();
				this._alwaysShowTooltip = true;
			} else {
				this.showTooltip = this._showTooltip.bind(this);
				this.hideTooltip = this._hideTooltip.bind(this);
				if (this.options.ticks_tooltip) {
					var callbackHandle = this._addTickListener();
					//create handle1 listeners and store references in map
					var mouseEnter = callbackHandle.addMouseEnter(this, this.handle1);
					var mouseLeave = callbackHandle.addMouseLeave(this, this.handle1);
					this.handleCallbackMap.handle1 = {
						mouseEnter: mouseEnter,
						mouseLeave: mouseLeave
					};
					//create handle2 listeners and store references in map
					mouseEnter = callbackHandle.addMouseEnter(this, this.handle2);
					mouseLeave = callbackHandle.addMouseLeave(this, this.handle2);
					this.handleCallbackMap.handle2 = {
						mouseEnter: mouseEnter,
						mouseLeave: mouseLeave
					};
				} else {
					this.sliderElem.addEventListener("mouseenter", this.showTooltip, false);
					this.sliderElem.addEventListener("mouseleave", this.hideTooltip, false);
				}
				this.handle1.addEventListener("focus", this.showTooltip, false);
				this.handle1.addEventListener("blur", this.hideTooltip, false);
				this.handle2.addEventListener("focus", this.showTooltip, false);
				this.handle2.addEventListener("blur", this.hideTooltip, false);
			}
			if (this.options.enabled) {
				this.enable();
			} else {
				this.disable();
			}
		}
		/*************************************************
  				INSTANCE PROPERTIES/METHODS
  	- Any methods bound to the prototype are considered
  part of the plugin's `public` interface
  **************************************************/
  Slider.prototype = {
			_init: function _init() {}, // NOTE: Must exist to support bridget
			constructor: Slider,
			defaultOptions: {
				id: "",
				min: 0,
				max: 10,
				step: 1,
				precision: 0,
				orientation: 'horizontal',
				value: 5,
				range: false,
				selection: 'before',
				tooltip: 'show',
				tooltip_split: false,
				handle: 'round',
				reversed: false,
				rtl: 'auto',
				enabled: true,
				tooltipstep: 0,
				handlebackground: '',
				multiplier: 1,
				formatter: function formatter(val) {
					if (Array.isArray(val)) {
						return val[0] + " : " + val[1];
					} else {
						return val;
					}
				},
				natural_arrow_keys: false,
				ticks: [],
				ticks_positions: [],
				ticks_labels: [],
				ticks_snap_bounds: 0,
				ticks_tooltip: false,
				scale: 'linear',
				focus: false,
				tooltip_position: null,
				labelledby: null,
				rangeHighlights: []
			},
			getElement: function getElement() {
				return this.sliderElem;
			},
			getValue: function getValue() {
				if (this.options.range) {
					return this._state.value;
				} else {
					return this._state.value[0];
				}
			},
			setValue: function setValue(val, triggerSlideEvent, triggerChangeEvent) {
				if (!val) {
					val = 0;
				}
				var oldValue = this.getValue();
				this._state.value = this._validateInputValue(val);
				var applyPrecision = this._applyPrecision.bind(this);
				if (this.options.range) {
					this._state.value[0] = applyPrecision(this._state.value[0]);
					this._state.value[1] = applyPrecision(this._state.value[1]);
					this._state.value[0] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[0]));
					this._state.value[1] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[1]));
				} else {
					this._state.value = applyPrecision(this._state.value);
					this._state.value = [Math.max(this.options.min, Math.min(this.options.max, this._state.value))];
					this._addClass(this.handle2, 'hide');
					if (this.options.selection === 'after') {
						this._state.value[1] = this.options.max;
					} else {
						this._state.value[1] = this.options.min;
					}
				}
				if (this.options.max > this.options.min) {
					this._state.percentage = [this._toPercentage(this._state.value[0]), this._toPercentage(this._state.value[1]), this.options.step * 100 / (this.options.max - this.options.min)];
				} else {
					this._state.percentage = [0, 0, 100];
				}
				this._layout();
				var newValue = this.options.range ? this._state.value : this._state.value[0];
				this._setDataVal(newValue);
				if (triggerSlideEvent === true) {
					this._trigger('slide', newValue);
				}
				if (oldValue !== newValue && triggerChangeEvent === true) {
					this._trigger('change', {
						oldValue: oldValue,
						newValue: newValue
					});
				}
				return this;
			},
			destroy: function destroy() {
				// Remove event handlers on slider elements
				this._removeSliderEventHandlers();
				// Remove the slider from the DOM
				this.sliderElem.parentNode.removeChild(this.sliderElem);
				/* Show original <input> element */
				this.element.style.display = "";
				// Clear out custom event bindings
				this._cleanUpEventCallbacksMap();
				// Remove data values
				this.element.removeAttribute("data");
				// Remove JQuery handlers/data
				if ($) {
					this._unbindJQueryEventHandlers();
					this.$element.removeData('slider');
				}
			},
			disable: function disable() {
				this._state.enabled = false;
				this.handle1.removeAttribute("tabindex");
				this.handle2.removeAttribute("tabindex");
				this._addClass(this.sliderElem, 'slider-disabled');
				this._trigger('slideDisabled');
				return this;
			},
			enable: function enable() {
				this._state.enabled = true;
				this.handle1.setAttribute("tabindex", 0);
				this.handle2.setAttribute("tabindex", 0);
				this._removeClass(this.sliderElem, 'slider-disabled');
				this._trigger('slideEnabled');
				return this;
			},
			toggle: function toggle() {
				if (this._state.enabled) {
					this.disable();
				} else {
					this.enable();
				}
				return this;
			},
			isEnabled: function isEnabled() {
				return this._state.enabled;
			},
			on: function on(evt, callback) {
				this._bindNonQueryEventHandler(evt, callback);
				return this;
			},
			off: function off(evt, callback) {
				if ($) {
					this.$element.off(evt, callback);
					this.$sliderElem.off(evt, callback);
				} else {
					this._unbindNonQueryEventHandler(evt, callback);
				}
			},
			getAttribute: function getAttribute(attribute) {
				if (attribute) {
					return this.options[attribute];
				} else {
					return this.options;
				}
			},
			setAttribute: function setAttribute(attribute, value) {
				this.options[attribute] = value;
				return this;
			},
			refresh: function refresh() {
				this._removeSliderEventHandlers();
				createNewSlider.call(this, this.element, this.options);
				if ($) {
					// Bind new instance of slider to the element
					$.data(this.element, 'slider', this);
				}
				return this;
			},
			relayout: function relayout() {
				this._resize();
				this._layout();
				return this;
			},
			/******************************+
   				HELPERS
   	- Any method that is not part of the public interface.
   - Place it underneath this comment block and write its signature like so:
   		_fnName : function() {...}
   		********************************/
   		_removeSliderEventHandlers: function _removeSliderEventHandlers() {
				// Remove keydown event listeners
				this.handle1.removeEventListener("keydown", this.handle1Keydown, false);
				this.handle2.removeEventListener("keydown", this.handle2Keydown, false);
				//remove the listeners from the ticks and handles if they had their own listeners
				if (this.options.ticks_tooltip) {
					var ticks = this.ticksContainer.getElementsByClassName('slider-tick');
					for (var i = 0; i < ticks.length; i++) {
						ticks[i].removeEventListener('mouseenter', this.ticksCallbackMap[i].mouseEnter, false);
						ticks[i].removeEventListener('mouseleave', this.ticksCallbackMap[i].mouseLeave, false);
					}
					this.handle1.removeEventListener('mouseenter', this.handleCallbackMap.handle1.mouseEnter, false);
					this.handle2.removeEventListener('mouseenter', this.handleCallbackMap.handle2.mouseEnter, false);
					this.handle1.removeEventListener('mouseleave', this.handleCallbackMap.handle1.mouseLeave, false);
					this.handle2.removeEventListener('mouseleave', this.handleCallbackMap.handle2.mouseLeave, false);
				}
				this.handleCallbackMap = null;
				this.ticksCallbackMap = null;
				if (this.showTooltip) {
					this.handle1.removeEventListener("focus", this.showTooltip, false);
					this.handle2.removeEventListener("focus", this.showTooltip, false);
				}
				if (this.hideTooltip) {
					this.handle1.removeEventListener("blur", this.hideTooltip, false);
					this.handle2.removeEventListener("blur", this.hideTooltip, false);
				}
				// Remove event listeners from sliderElem
				if (this.showTooltip) {
					this.sliderElem.removeEventListener("mouseenter", this.showTooltip, false);
				}
				if (this.hideTooltip) {
					this.sliderElem.removeEventListener("mouseleave", this.hideTooltip, false);
				}
				this.sliderElem.removeEventListener("touchstart", this.touchstart, false);
				this.sliderElem.removeEventListener("touchmove", this.touchmove, false);
				this.sliderElem.removeEventListener("mousedown", this.mousedown, false);
				// Remove window event listener
				window.removeEventListener("resize", this.resize, false);
			},
			_bindNonQueryEventHandler: function _bindNonQueryEventHandler(evt, callback) {
				if (this.eventToCallbackMap[evt] === undefined) {
					this.eventToCallbackMap[evt] = [];
				}
				this.eventToCallbackMap[evt].push(callback);
			},
			_unbindNonQueryEventHandler: function _unbindNonQueryEventHandler(evt, callback) {
				var callbacks = this.eventToCallbackMap[evt];
				if (callbacks !== undefined) {
					for (var i = 0; i < callbacks.length; i++) {
						if (callbacks[i] === callback) {
							callbacks.splice(i, 1);
							break;
						}
					}
				}
			},
			_cleanUpEventCallbacksMap: function _cleanUpEventCallbacksMap() {
				var eventNames = Object.keys(this.eventToCallbackMap);
				for (var i = 0; i < eventNames.length; i++) {
					var eventName = eventNames[i];
					delete this.eventToCallbackMap[eventName];
				}
			},
			_showTooltip: function _showTooltip() {
				if (this.options.tooltip_split === false) {
					this._addClass(this.tooltip, 'in');
					this.tooltip_min.style.display = 'none';
					this.tooltip_max.style.display = 'none';
				} else {
					this._addClass(this.tooltip_min, 'in');
					this._addClass(this.tooltip_max, 'in');
					this.tooltip.style.display = 'none';
				}
				this._state.over = true;
			},
			_hideTooltip: function _hideTooltip() {
				if (this._state.inDrag === false && this.alwaysShowTooltip !== true) {
					this._removeClass(this.tooltip, 'in');
					this._removeClass(this.tooltip_min, 'in');
					this._removeClass(this.tooltip_max, 'in');
				}
				this._state.over = false;
			},
			_setToolTipOnMouseOver: function _setToolTipOnMouseOver(tempState) {
				var formattedTooltipVal = this.options.formatter(!tempState ? this._state.value[0] : tempState.value[0]);
				var positionPercentages = !tempState ? getPositionPercentages(this._state, this.options.reversed) : getPositionPercentages(tempState, this.options.reversed);
				this._setText(this.tooltipInner, formattedTooltipVal);
				this.tooltip.style[this.stylePos] = positionPercentages[0] + "%";
				function getPositionPercentages(state, reversed) {
					if (reversed) {
						return [100 - state.percentage[0], this.options.range ? 100 - state.percentage[1] : state.percentage[1]];
					}
					return [state.percentage[0], state.percentage[1]];
				}
			},
			_addTickListener: function _addTickListener() {
				return {
					addMouseEnter: function addMouseEnter(reference, tick, index) {
						var enter = function enter() {
							var tempState = reference._state;
							var idString = index >= 0 ? index : this.attributes['aria-valuenow'].value;
							var hoverIndex = parseInt(idString, 10);
							tempState.value[0] = hoverIndex;
							tempState.percentage[0] = reference.options.ticks_positions[hoverIndex];
							reference._setToolTipOnMouseOver(tempState);
							reference._showTooltip();
						};
						tick.addEventListener("mouseenter", enter, false);
						return enter;
					},
					addMouseLeave: function addMouseLeave(reference, tick) {
						var leave = function leave() {
							reference._hideTooltip();
						};
						tick.addEventListener("mouseleave", leave, false);
						return leave;
					}
				};
			},
			_layout: function _layout() {
				var positionPercentages;
				if (this.options.reversed) {
					positionPercentages = [100 - this._state.percentage[0], this.options.range ? 100 - this._state.percentage[1] : this._state.percentage[1]];
				} else {
					positionPercentages = [this._state.percentage[0], this._state.percentage[1]];
				}
				if(positionPercentages[0] === 100){
					positionPercentages[0] = 97
				}
				this.handle1.style[this.stylePos] = positionPercentages[0] + "%";
				this.handle1.setAttribute('aria-valuenow', this._state.value[0]);
				if (isNaN(this.options.formatter(this._state.value[0]))) {
					this.handle1.setAttribute('aria-valuetext', this.options.formatter(this._state.value[0]));
				}
				this.handle2.style[this.stylePos] = positionPercentages[1] + "%";
				this.handle2.setAttribute('aria-valuenow', this._state.value[1]);
				if (isNaN(this.options.formatter(this._state.value[1]))) {
					this.handle2.setAttribute('aria-valuetext', this.options.formatter(this._state.value[1]));
				}
				/* Position highlight range elements */
				if (this.rangeHighlightElements.length > 0 && Array.isArray(this.options.rangeHighlights) && this.options.rangeHighlights.length > 0) {
					for (var _i = 0; _i < this.options.rangeHighlights.length; _i++) {
						var startPercent = this._toPercentage(this.options.rangeHighlights[_i].start);
						var endPercent = this._toPercentage(this.options.rangeHighlights[_i].end);
						if (this.options.reversed) {
							var sp = 100 - endPercent;
							endPercent = 100 - startPercent;
							startPercent = sp;
						}
						var currentRange = this._createHighlightRange(startPercent, endPercent);
						if (currentRange) {
							if (this.options.orientation === 'vertical') {
								this.rangeHighlightElements[_i].style.top = currentRange.start + "%";
								this.rangeHighlightElements[_i].style.height = currentRange.size + "%";
							} else {
								if (this.options.rtl) {
									this.rangeHighlightElements[_i].style.right = currentRange.start + "%";
								} else {
									this.rangeHighlightElements[_i].style.left = currentRange.start + "%";
								}
								this.rangeHighlightElements[_i].style.width = currentRange.size + "%";
							}
						} else {
							this.rangeHighlightElements[_i].style.display = "none";
						}
					}
				}
				/* Position ticks and labels */
				if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) {
					var styleSize = this.options.orientation === 'vertical' ? 'height' : 'width';
					var styleMargin;
					if (this.options.orientation === 'vertical') {
						styleMargin = 'marginTop';
					} else {
						if (this.options.rtl) {
							styleMargin = 'marginRight';
						} else {
							styleMargin = 'marginLeft';
						}
					}
					var labelSize = this._state.size / (this.options.ticks.length - 1);
					if (this.tickLabelContainer) {
						var extraMargin = 0;
						if (this.options.ticks_positions.length === 0) {
							if (this.options.orientation !== 'vertical') {
								this.tickLabelContainer.style[styleMargin] = -labelSize / 2 + "px";
							}
							extraMargin = this.tickLabelContainer.offsetHeight;
						} else {
							/* Chidren are position absolute, calculate height by finding the max offsetHeight of a child */
							for (i = 0; i < this.tickLabelContainer.childNodes.length; i++) {
								if (this.tickLabelContainer.childNodes[i].offsetHeight > extraMargin) {
									extraMargin = this.tickLabelContainer.childNodes[i].offsetHeight;
								}
							}
						}
						if (this.options.orientation === 'horizontal') {
							this.sliderElem.style.marginBottom = extraMargin + "px";
						}
					}
					for (var i = 0; i < this.options.ticks.length; i++) {
						var percentage = this.options.ticks_positions[i] || this._toPercentage(this.options.ticks[i]);
						if (this.options.reversed) {
							percentage = 100 - percentage;
						}
						this.ticks[i].style[this.stylePos] = percentage + "%";
						/* Set class labels to denote whether ticks are in the selection */
						this._removeClass(this.ticks[i], 'in-selection');
						if (!this.options.range) {
							if (this.options.selection === 'after' && percentage >= positionPercentages[0]) {
								this._addClass(this.ticks[i], 'in-selection');
							} else if (this.options.selection === 'before' && percentage <= positionPercentages[0]) {
								this._addClass(this.ticks[i], 'in-selection');
							}
						} else if (percentage >= positionPercentages[0] && percentage <= positionPercentages[1]) {
							this._addClass(this.ticks[i], 'in-selection');
						}
						if (this.tickLabels[i]) {
							this.tickLabels[i].style[styleSize] = labelSize + "px";
							if (this.options.orientation !== 'vertical' && this.options.ticks_positions[i] !== undefined) {
								this.tickLabels[i].style.position = 'absolute';
								this.tickLabels[i].style[this.stylePos] = percentage + "%";
								this.tickLabels[i].style[styleMargin] = -labelSize / 2 + 'px';
							} else if (this.options.orientation === 'vertical') {
								if (this.options.rtl) {
									this.tickLabels[i].style['marginRight'] = this.sliderElem.offsetWidth + "px";
								} else {
									this.tickLabels[i].style['marginLeft'] = this.sliderElem.offsetWidth + "px";
								}
								this.tickLabelContainer.style[styleMargin] = this.sliderElem.offsetWidth / 2 * -1 + 'px';
							}
						}
					}
				}
				var formattedTooltipVal;
				if (this.options.range) {
					formattedTooltipVal = this.options.formatter(this._state.value);
					this._setText(this.tooltipInner, formattedTooltipVal);
					this.tooltip.style[this.stylePos] = (positionPercentages[1] + positionPercentages[0]) / 2 + "%";
					var innerTooltipMinText = this.options.formatter(this._state.value[0]);
					this._setText(this.tooltipInner_min, innerTooltipMinText);
					var innerTooltipMaxText = this.options.formatter(this._state.value[1]);
					this._setText(this.tooltipInner_max, innerTooltipMaxText);
					this.tooltip_min.style[this.stylePos] = positionPercentages[0] + "%";
					this.tooltip_max.style[this.stylePos] = positionPercentages[1] + "%";
				} else {
                                        //console.log('---> boeing ---> ' + JSON.stringify(this.options.tooltipstep));
                                        if (this.options.tooltipstep)
                                        {
                                            //alert(this.options.multiplier);
                                            formattedTooltipVal = this.options.formatter(  parseFloat(this._state.value[0] / this.options.multiplier) );
                                        }
                                        else
                                        {
                                        	formattedTooltipVal = this.options.formatter(this._state.value[0]);
                                        }
                                        this._setText(this.tooltipInner, priceCommaStyler(formattedTooltipVal));
                                        var handleValueLength = String(priceCommaStyler(formattedTooltipVal)).length;
                                        if (handleValueLength > 4) {
                                        	this._setHandleSizing(handleValueLength - 4);
                                        } else {
                                        	this.handle1.style.width = '40px';
                                        	this.handle1.style.height = '40px';
                                        	this.handle1.style.top = '-5px';
                                        	this.tooltipInner.style.marginRight = '-22px';
                                        }
                                        this.tooltip.style[this.stylePos] = positionPercentages[0] + "%";
                                        this.baloon.style[this.stylePos] = positionPercentages[0] > 50 ? positionPercentages[0]/2 + "%" : positionPercentages[0] + "%";
                                    }
                                    if (this.options.orientation === 'vertical') {
                                    	this.trackLow.style.top = '0';
                                    	this.trackLow.style.height = Math.min(positionPercentages[0], positionPercentages[1]) + '%';
                                    	this.trackSelection.style.top = Math.min(positionPercentages[0], positionPercentages[1]) + '%';
                                    	this.trackSelection.style.height = Math.abs(positionPercentages[0] - positionPercentages[1]) + '%';
                                    	this.trackHigh.style.bottom = '0';
                                    	this.trackHigh.style.height = 100 - Math.min(positionPercentages[0], positionPercentages[1]) - Math.abs(positionPercentages[0] - positionPercentages[1]) + '%';
                                    } else {
                                    	if (this.stylePos === 'right') {
                                    		this.trackLow.style.right = '0';
                                    	} else {
                                    		this.trackLow.style.left = '0';
                                    	}
                                    	this.trackLow.style.width = Math.min(positionPercentages[0], positionPercentages[1]) + '%';
                                    	if (this.stylePos === 'right') {
                                    		this.trackSelection.style.right = Math.min(positionPercentages[0], positionPercentages[1]) + '%';
                                    	} else {
                                    		this.trackSelection.style.left = Math.min(positionPercentages[0], positionPercentages[1]) + '%';
                                    	}
                                    	this.trackSelection.style.width = (Math.abs(positionPercentages[0] - positionPercentages[1]) + 1) + '%';
                                    	if (this.stylePos === 'right') {
                                    		this.trackHigh.style.left = '0';
                                    	} else {
                                    		this.trackHigh.style.right = '0';
                                    	}
                                    	this.trackHigh.style.width = (100 - Math.min(positionPercentages[0], positionPercentages[1]) - Math.abs(positionPercentages[0] - positionPercentages[1]) - 1) + '%';
                                    	var offset_min = this.tooltip_min.getBoundingClientRect();
                                    	var offset_max = this.tooltip_max.getBoundingClientRect();
                                    	if (this.options.tooltip_position === 'bottom') {
                                    		if (offset_min.right > offset_max.left) {
                                    			this._removeClass(this.tooltip_max, 'bottom');
                                    			this._addClass(this.tooltip_max, 'top');
                                    			this.tooltip_max.style.top = '';
                                    			this.tooltip_max.style.bottom = 22 + 'px';
                                    		} else {
                                    			this._removeClass(this.tooltip_max, 'top');
                                    			this._addClass(this.tooltip_max, 'bottom');
                                    			this.tooltip_max.style.top = this.tooltip_min.style.top;
                                    			this.tooltip_max.style.bottom = '';
                                    		}
                                    	} else {
                                    		if (offset_min.right > offset_max.left) {
                                    			this._removeClass(this.tooltip_max, 'top');
                                    			this._addClass(this.tooltip_max, 'bottom');
                                    			this.tooltip_max.style.top = 18 + 'px';
                                    		} else {
                                    			this._removeClass(this.tooltip_max, 'bottom');
                                    			this._addClass(this.tooltip_max, 'top');
                                    			this.tooltip_max.style.top = this.tooltip_min.style.top;
                                    		}
                                    	}
                                    }
                                },
                                _createHighlightRange: function _createHighlightRange(start, end) {
                                	if (this._isHighlightRange(start, end)) {
                                		if (start > end) {
                                			return { 'start': end, 'size': start - end };
                                		}
                                		return { 'start': start, 'size': end - start };
                                	}
                                	return null;
                                },
                                _isHighlightRange: function _isHighlightRange(start, end) {
                                	if (0 <= start && start <= 100 && 0 <= end && end <= 100) {
                                		return true;
                                	} else {
                                		return false;
                                	}
                                },
                                _resize: function _resize(ev) {
                                	/*jshint unused:false*/
                                	this._state.offset = this._offset(this.sliderElem);
                                	this._state.size = this.sliderElem[this.sizePos];
                                	this._layout();
                                },
                                _removeProperty: function _removeProperty(element, prop) {
                                	if (element.style.removeProperty) {
                                		element.style.removeProperty(prop);
                                	} else {
                                		element.style.removeAttribute(prop);
                                	}
                                },
                                _mousedown: function _mousedown(ev) {
                                	if (!this._state.enabled) {
                                		return false;
                                	}
                                	if (ev.preventDefault) {
                                		ev.preventDefault();
                                	}
                                	this._state.offset = this._offset(this.sliderElem);
                                	this._state.size = this.sliderElem[this.sizePos];
                                	var percentage = this._getPercentage(ev);
                                	if (this.options.range) {
                                		var diff1 = Math.abs(this._state.percentage[0] - percentage);
                                		var diff2 = Math.abs(this._state.percentage[1] - percentage);
                                		this._state.dragged = diff1 < diff2 ? 0 : 1;
                                		this._adjustPercentageForRangeSliders(percentage);
                                	} else {
                                		this._state.dragged = 0;
                                	}
                                	this._state.percentage[this._state.dragged] = percentage;
                                	this._layout();
                                	if (this.touchCapable) {
                                		document.removeEventListener("touchmove", this.mousemove, false);
                                		document.removeEventListener("touchend", this.mouseup, false);
                                	}
                                	if (this.mousemove) {
                                		document.removeEventListener("mousemove", this.mousemove, false);
                                	}
                                	if (this.mouseup) {
                                		document.removeEventListener("mouseup", this.mouseup, false);
                                	}
                                	this.mousemove = this._mousemove.bind(this);
                                	this.mouseup = this._mouseup.bind(this);
                                	if (this.touchCapable) {
					// Touch: Bind touch events:
					document.addEventListener("touchmove", this.mousemove, false);
					document.addEventListener("touchend", this.mouseup, false);
				}
				// Bind mouse events:
				document.addEventListener("mousemove", this.mousemove, false);
				document.addEventListener("mouseup", this.mouseup, false);
				this._state.inDrag = true;
				var newValue = this._calculateValue();
				this._trigger('slideStart', newValue);
				this._setDataVal(newValue);
				this.setValue(newValue, false, true);
				ev.returnValue = false;
				if (this.options.focus) {
					this._triggerFocusOnHandle(this._state.dragged);
				}
				return true;
			},
			_touchstart: function _touchstart(ev) {
				if (ev.changedTouches === undefined) {
					this._mousedown(ev);
					return;
				}
				var touch = ev.changedTouches[0];
				this.touchX = touch.pageX;
				this.touchY = touch.pageY;
			},
			_triggerFocusOnHandle: function _triggerFocusOnHandle(handleIdx) {
				if (handleIdx === 0) {
					this.handle1.focus();
				}
				if (handleIdx === 1) {
					this.handle2.focus();
				}
			},
			_keydown: function _keydown(handleIdx, ev) {
				if (!this._state.enabled) {
					return false;
				}
				var dir;
				switch (ev.keyCode) {
					case 37: // left
					case 40:
						// down
						dir = -1;
						break;
					case 39: // right
					case 38:
						// up
						dir = 1;
						break;
					}
					if (!dir) {
						return;
					}
				// use natural arrow keys instead of from min to max
				if (this.options.natural_arrow_keys) {
					var ifVerticalAndNotReversed = this.options.orientation === 'vertical' && !this.options.reversed;
					var ifHorizontalAndReversed = this.options.orientation === 'horizontal' && this.options.reversed; // @todo control with rtl
					if (ifVerticalAndNotReversed || ifHorizontalAndReversed) {
						dir = -dir;
					}
				}
				var val = this._state.value[handleIdx] + dir * this.options.step;
				var percentage = val / this.options.max * 100;
				this._state.keyCtrl = handleIdx;
				if (this.options.range) {
					this._adjustPercentageForRangeSliders(percentage);
					var val1 = !this._state.keyCtrl ? val : this._state.value[0];
					var val2 = this._state.keyCtrl ? val : this._state.value[1];
					val = [val1, val2];
				}
				this._trigger('slideStart', val);
				this._setDataVal(val);
				this.setValue(val, true, true);
				this._setDataVal(val);
				this._trigger('slideStop', val);
				this._layout();
				this._pauseEvent(ev);
				delete this._state.keyCtrl;
				return false;
			},
			_pauseEvent: function _pauseEvent(ev) {
				if (ev.stopPropagation) {
					ev.stopPropagation();
				}
				if (ev.preventDefault) {
					ev.preventDefault();
				}
				ev.cancelBubble = true;
				ev.returnValue = false;
			},
			_mousemove: function _mousemove(ev) {
				if (!this._state.enabled) {
					return false;
				}
				var percentage = this._getPercentage(ev);
				this._adjustPercentageForRangeSliders(percentage);
				this._state.percentage[this._state.dragged] = percentage;
				this._layout();
				var val = this._calculateValue(true);
				this.setValue(val, true, true);
				return false;
			},
			_touchmove: function _touchmove(ev) {
				if (ev.changedTouches === undefined) {
					return;
				}
				var touch = ev.changedTouches[0];
				var xDiff = touch.pageX - this.touchX;
				var yDiff = touch.pageY - this.touchY;
				if (!this._state.inDrag) {
					// Vertical Slider
					if (this.options.orientation === 'vertical' && xDiff <= 5 && xDiff >= -5 && (yDiff >= 15 || yDiff <= -15)) {
						this._mousedown(ev);
					}
					// Horizontal slider.
					else if (yDiff <= 5 && yDiff >= -5 && (xDiff >= 15 || xDiff <= -15)) {
						this._mousedown(ev);
					}
				}
			},
			_adjustPercentageForRangeSliders: function _adjustPercentageForRangeSliders(percentage) {
				if (this.options.range) {
					var precision = this._getNumDigitsAfterDecimalPlace(percentage);
					precision = precision ? precision - 1 : 0;
					var percentageWithAdjustedPrecision = this._applyToFixedAndParseFloat(percentage, precision);
					if (this._state.dragged === 0 && this._applyToFixedAndParseFloat(this._state.percentage[1], precision) < percentageWithAdjustedPrecision) {
						this._state.percentage[0] = this._state.percentage[1];
						this._state.dragged = 1;
					} else if (this._state.dragged === 1 && this._applyToFixedAndParseFloat(this._state.percentage[0], precision) > percentageWithAdjustedPrecision) {
						this._state.percentage[1] = this._state.percentage[0];
						this._state.dragged = 0;
					} else if (this._state.keyCtrl === 0 && this._state.value[1] / this.options.max * 100 < percentage) {
						this._state.percentage[0] = this._state.percentage[1];
						this._state.keyCtrl = 1;
						this.handle2.focus();
					} else if (this._state.keyCtrl === 1 && this._state.value[0] / this.options.max * 100 > percentage) {
						this._state.percentage[1] = this._state.percentage[0];
						this._state.keyCtrl = 0;
						this.handle1.focus();
					}
				}
			},
			_mouseup: function _mouseup() {
				if (!this._state.enabled) {
					return false;
				}
				if (this.touchCapable) {
					// Touch: Unbind touch event handlers:
					document.removeEventListener("touchmove", this.mousemove, false);
					document.removeEventListener("touchend", this.mouseup, false);
				}
				// Unbind mouse event handlers:
				document.removeEventListener("mousemove", this.mousemove, false);
				document.removeEventListener("mouseup", this.mouseup, false);
				this._state.inDrag = false;
				if (this._state.over === false) {
					this._hideTooltip();
				}
				var val = this._calculateValue(true);
				this._layout();
				this._setDataVal(val);
				this._trigger('slideStop', val);
				return false;
			},
			_calculateValue: function _calculateValue(snapToClosestTick) {
				var val;
				if (this.options.range) {
					val = [this.options.min, this.options.max];
					if (this._state.percentage[0] !== 0) {
						val[0] = this._toValue(this._state.percentage[0]);
						val[0] = this._applyPrecision(val[0]);
					}
					if (this._state.percentage[1] !== 100) {
						val[1] = this._toValue(this._state.percentage[1]);
						val[1] = this._applyPrecision(val[1]);
					}
				} else {
					val = this._toValue(this._state.percentage[0]);
					val = parseFloat(val);
					val = this._applyPrecision(val);
				}
				if (snapToClosestTick) {
					var min = [val, Infinity];
					for (var i = 0; i < this.options.ticks.length; i++) {
						var diff = Math.abs(this.options.ticks[i] - val);
						if (diff <= min[1]) {
							min = [this.options.ticks[i], diff];
						}
					}
					if (min[1] <= this.options.ticks_snap_bounds) {
						return min[0];
					}
				}
				return val;
			},
			_applyPrecision: function _applyPrecision(val) {
				var precision = this.options.precision || this._getNumDigitsAfterDecimalPlace(this.options.step);
				return this._applyToFixedAndParseFloat(val, precision);
			},
			_getNumDigitsAfterDecimalPlace: function _getNumDigitsAfterDecimalPlace(num) {
				var match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
				if (!match) {
					return 0;
				}
				return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));
			},
			_applyToFixedAndParseFloat: function _applyToFixedAndParseFloat(num, toFixedInput) {
				var truncatedNum = num.toFixed(toFixedInput);
				return parseFloat(truncatedNum);
			},
			/*
   	Credits to Mike Samuel for the following method!
   	Source: http://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number
   	*/
   	_getPercentage: function _getPercentage(ev) {
   		if (this.touchCapable && (ev.type === 'touchstart' || ev.type === 'touchmove')) {
   			ev = ev.touches[0];
   		}
   		var eventPosition = ev[this.mousePos];
   		var sliderOffset = this._state.offset[this.stylePos];
   		var distanceToSlide = eventPosition - sliderOffset;
   		if (this.stylePos === 'right') {
   			distanceToSlide = -distanceToSlide;
   		}
				// Calculate what percent of the length the slider handle has slid
				var percentage = distanceToSlide / this._state.size * 100;
				percentage = Math.round(percentage / this._state.percentage[2]) * this._state.percentage[2];
				if (this.options.reversed) {
					percentage = 100 - percentage;
				}
				// Make sure the percent is within the bounds of the slider.
				// 0% corresponds to the 'min' value of the slide
				// 100% corresponds to the 'max' value of the slide
				return Math.max(0, Math.min(100, percentage));
			},
			_validateInputValue: function _validateInputValue(val) {
				if (!isNaN(+val)) {
					return +val;
				} else if (Array.isArray(val)) {
					this._validateArray(val);
					return val;
				} else {
					throw new Error(ErrorMsgs.formatInvalidInputErrorMsg(val));
				}
			},
			_validateArray: function _validateArray(val) {
				for (var i = 0; i < val.length; i++) {
					var input = val[i];
					if (typeof input !== 'number') {
						throw new Error(ErrorMsgs.formatInvalidInputErrorMsg(input));
					}
				}
			},
			_setDataVal: function _setDataVal(val) {
				this.element.setAttribute('data-value', val);
				this.element.setAttribute('value', val);
				this.element.value = val;
			},
			_trigger: function _trigger(evt, val) {
				val = val || val === 0 ? val : undefined;
				var callbackFnArray = this.eventToCallbackMap[evt];
				if (callbackFnArray && callbackFnArray.length) {
					for (var i = 0; i < callbackFnArray.length; i++) {
						var callbackFn = callbackFnArray[i];
						callbackFn(val);
					}
				}
				/* If JQuery exists, trigger JQuery events */
				if ($) {
					this._triggerJQueryEvent(evt, val);
				}
			},
			_triggerJQueryEvent: function _triggerJQueryEvent(evt, val) {
				var eventData = {
					type: evt,
					value: val
				};
				this.$element.trigger(eventData);
				this.$sliderElem.trigger(eventData);
			},
			_unbindJQueryEventHandlers: function _unbindJQueryEventHandlers() {
				this.$element.off();
				this.$sliderElem.off();
			},
			_setText: function _setText(element, text) {
				if (typeof element.textContent !== "undefined") {
					element.textContent = text;
				} else if (typeof element.innerText !== "undefined") {
					element.innerText = text;
				}
			},
			_setHandleSizing: function _setHandleSizing(charExtraLength) {
				let heightWeight = 40 + (charExtraLength * 5) + 'px';
				this.handle1.style.width = heightWeight;
				this.handle1.style.height = heightWeight;
				this.handle1.style.top = `${-5-(charExtraLength *2)}px`;
				this.tooltipInner.style.marginRight = `${-22-(charExtraLength *5)}px`;
			},
			_removeClass: function _removeClass(element, classString) {
				var classes = classString.split(" ");
				var newClasses = element.className;
				for (var i = 0; i < classes.length; i++) {
					var classTag = classes[i];
					var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
					newClasses = newClasses.replace(regex, " ");
				}
				element.className = newClasses.trim();
			},
			_addClass: function _addClass(element, classString) {
				var classes = classString.split(" ");
				var newClasses = element.className;
				for (var i = 0; i < classes.length; i++) {
					var classTag = classes[i];
					var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
					var ifClassExists = regex.test(newClasses);
					if (!ifClassExists) {
						newClasses += " " + classTag;
					}
				}
				element.className = newClasses.trim();
			},
			_offsetLeft: function _offsetLeft(obj) {
				return obj.getBoundingClientRect().left;
			},
			_offsetRight: function _offsetRight(obj) {
				return obj.getBoundingClientRect().right;
			},
			_offsetTop: function _offsetTop(obj) {
				var offsetTop = obj.offsetTop;
				while ((obj = obj.offsetParent) && !isNaN(obj.offsetTop)) {
					offsetTop += obj.offsetTop;
					if (obj.tagName !== 'BODY') {
						offsetTop -= obj.scrollTop;
					}
				}
				return offsetTop;
			},
			_offset: function _offset(obj) {
				return {
					left: this._offsetLeft(obj),
					right: this._offsetRight(obj),
					top: this._offsetTop(obj)
				};
			},
			_css: function _css(elementRef, styleName, value) {
				if ($) {
					$.style(elementRef, styleName, value);
				} else {
					var style = styleName.replace(/^-ms-/, "ms-").replace(/-([\da-z])/gi, function (all, letter) {
						return letter.toUpperCase();
					});
					elementRef.style[style] = value;
				}
			},
			_toValue: function _toValue(percentage) {
				return this.options.scale.toValue.apply(this, [percentage]);
			},
			_toPercentage: function _toPercentage(value) {
				return this.options.scale.toPercentage.apply(this, [value]);
			},
			_setTooltipPosition: function _setTooltipPosition() {
				var tooltips = [this.tooltip, this.tooltip_min, this.tooltip_max];
				if (this.options.orientation === 'vertical') {
					var tooltipPos;
					if (this.options.tooltip_position) {
						tooltipPos = this.options.tooltip_position;
					} else {
						if (this.options.rtl) {
							tooltipPos = 'left';
						} else {
							tooltipPos = 'right';
						}
					}
					var oppositeSide = tooltipPos === 'left' ? 'right' : 'left';
					tooltips.forEach(function (tooltip) {
						this._addClass(tooltip, tooltipPos);
						tooltip.style[oppositeSide] = '100%';
					}.bind(this));
				} else if (this.options.tooltip_position === 'bottom') {
					tooltips.forEach(function (tooltip) {
						this._addClass(tooltip, 'bottom');
						tooltip.style.top = 22 + 'px';
					}.bind(this));
				} else {
					tooltips.forEach(function (tooltip) {
						this._addClass(tooltip, 'top');
						tooltip.style.top = -this.tooltip.outerHeight - 14 + 'px';
					}.bind(this));
				}
			}
		};
		/*********************************
  		Attach to global namespace
  		*********************************/
  		if ($ && $.fn) {
  			var autoRegisterNamespace = void 0;
  			if (!$.fn.slider) {
  				$.bridget(NAMESPACE_MAIN, Slider);
  				autoRegisterNamespace = NAMESPACE_MAIN;
  			} else {
  				if (windowIsDefined) {
  					window.console.warn("bootstrap-slider.js - WARNING: $.fn.slider namespace is already bound. Use the $.fn.bootstrapSlider namespace instead.");
  				}
  				autoRegisterNamespace = NAMESPACE_ALTERNATE;
  			}
  			$.bridget(NAMESPACE_ALTERNATE, Slider);
			// Auto-Register data-provide="slider" Elements
			$(function () {
				$("input[data-provide=slider]")[autoRegisterNamespace]();
			});
		}
	})($);
	return Slider;
});
// beginning of the code responsible for majority of Stylish Cost Calculator's operation
var conditionMap = [];
if(/MSIE \d|Trident.*rv:/.test(navigator.userAgent)){
	console.log('detecting internet explorer modified')
	document.write('<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.5/bluebird.min.js"><\/script>');
}

// elements are assigned uniqueID if they already has one, the function returns the existing one.
function generateUID(element) {
  // I generate the UID from two parts here
  // to ensure the random number provide enough bits.
  if (!jQuery(element).data('uniqueId')) {
  	var firstPart = (Math.random() * 46656) | 0;
  	var secondPart = (Math.random() * 46656) | 0;
  	firstPart = ("000" + firstPart.toString(36)).slice(-3);
  	secondPart = ("000" + secondPart.toString(36)).slice(-3);
  	jQuery(element).data('uniqueId', (firstPart + secondPart));
  	return firstPart + secondPart;
  };
  if (jQuery(element).data('uniqueId').length) {
  	return jQuery(element).data('uniqueId');
  }
  return 0;
}
// the logicOperators object contains the short form of logic operators as the key and their full names as value
var logicOperators = {
	'eq' : 'Equal To',
	'ne' : 'Not Equal To',
	'any' : 'Any',
	'less' : 'Less Than',
	'gt' : 'Greater Than',
	'true' : 'Truthy',
	'false' : 'Falsey'
}
// an object to hold the condition definitions, it is manipuilated in the editing area, and saved as a parameter
var conditionObject = {};
// Helps delete the value of conditional logic dropdowns in the editing page, if the value of dropdown cahnges, we delete the key helps the logChanges function
function sccStoreConditionDropdwnValue(element) {
	element = jQuery(element);
	element.data('prevVal', element.val());
}
// handles delete button of condition definition
function removeConditionDefinition(element) {
	var parentElementId = jQuery(element).closest('.content').data('uniqueId');
	var definition = jQuery(element).closest('.conditional-selection').find('.condition-stage-a').val();
	console.log();
	delete conditionObject[parentElementId][0][definition];
	jQuery(element).closest('.conditional-selection').prev().find('.btn').prop('disabled', false);
	jQuery(element).closest('.conditional-selection').remove();
}
// function to return condition operators depending on the element type, set to trigger when first dropdown in condition definition is changed
function logChanges(e) {
	var previousValue = jQuery(e).data('prevVal');
  // detetes if dropdown value is changed
  if (previousValue) {
  	var parentElementId = jQuery(e).closest('.content').data('uniqueId');
  	try {
  		delete conditionObject[parentElementId][0][previousValue];
  	} catch (error) {
  	}
  };
  // gets all elements data objects
  var elemnts = new Conditions().getDataObjectWithSchema();
  var elementsWithSlider = elemnts.filter(e => e.type !== 'slider');
  var sliderData = elemnts.filter(e => e.type == 'slider').map(e => e.value.map(e => ({uniqueId: e.uniqueId, type: 'slider'}))).flat();
  sliderData.forEach(e => elementsWithSlider.push(e));
  var names = _.where(elementsWithSlider, {uniqueId: jQuery(e).val()});
  var options = [];
  try {
  	switch (names[0].type) {
  		case 'selectoption':
  		options = ['eq','ne', 'any'];
  		valueType = 'choices';
  		break;
  		case 'number_option':
  		options = ['eq','ne', 'gt', 'less'];
  		valueType = 'numeric';
  		break;
  		case 'slider':
  		options = ['eq','ne', 'gt', 'less'];
  		valueType = 'numeric';
  		break;
  		default:
  		options = ['eq', 'ne', 'gt', 'less', 'true', 'false'];
  		valueType = 'default';
  		break;
  	}
  } catch (error) {
	// if an exception start outputting data for checkboxes
	jQuery(e).parent().find('.condition-stage-b').remove();
	jQuery(e).parent().find('.condition-stage-c').remove();
	selectTag = `<select class="condition-stage-b" onChange="javascript:pushConditionSpec(this, event)" style="width:33%;float:left;height:41px;">
	<option value="unset">Please select an option</option>
	<option value="true">Checked</option>
	<option value="false">Unchecked</option>
	</select>`;
	var tag = jQuery(e).after(selectTag);
	if (!tag.parent().find('button').length) tag.parent().find('.condition-stage-b').after("<button onclick=\"javascript:addNewCondition(this, event);\" class='btn'>Add</button><button onClick=\"javascript:removeConditionDefinition(this)\" class=\"btn btn-danger\" style=\"display: inline-block;\">x</button");
	return;
}
  // console.log(options);
  selectTag = `<select class="condition-stage-b" data-option-type=${valueType} onchange="javascript:logChangesB(this, event)" style="width:20%;float:left;height:41px;">`;
  optionString = options.map((e) => {return `<option value="${e}">${logicOperators[e]}</option>`}).join('');
  selectTag += optionString + '</select>';
  jQuery(e).parent().find('.condition-stage-b').remove();
  jQuery(e).after(selectTag);
  jQuery(e).parent().find('.condition-stage-b').trigger('change');
}
// function to populate the third dropdown
function logChangesB(e,i) {
	var isTypeAny = jQuery(e).val() == 'any';
	switch (jQuery(e).data('optionType')) {
		case 'numeric':
		selectTag = '<input class="condition-stage-c" type="number" onChange="javascript:pushConditionSpec(this, event)" style="width:27%;float:left;height:41px;"></input>';
		jQuery(e).parent().find('.condition-stage-c').remove();
		var stageC = jQuery(e).after(selectTag).next();
		stageC.trigger('change');
		if (!jQuery(e).parent().find('button').length) jQuery(e).parent().find('.condition-stage-c').after("<button onclick=\"javascript:addNewCondition(this, event);\" class='btn'>Add</button><button onClick=\"javascript:removeConditionDefinition(this)\" class=\"btn btn-danger\" style=\"display: inline-block;\">x</button");
		break;
		default:
		var elemnts = new Conditions().getDataObjectWithSchema();
		var names = _.where(elemnts, {uniqueId: jQuery(e).prev().val()});
		var selectTag = `<select class="condition-stage-c" onChange="javascript:pushConditionSpec(this, event)" style="width:27%;float:left;height:41px; ${isTypeAny ? 'display: none;' : 'display: block;'};">`;
		var optionString = names[0].value.map(e => {return `<option value="${parseInt(e.No) + 1}">${e.name}</option>`});
		selectTag += '<option value="unset">Please select an option</option>' + optionString + '</select>';
		jQuery(e).parent().find('.condition-stage-c').remove();
		var stageC = jQuery(e).after(selectTag).next();
		stageC.trigger('change');
		if (!jQuery(e).parent().find('button').length) jQuery(e).parent().find('.condition-stage-c').after("<button onclick=\"javascript:addNewCondition(this, event);\" class='btn'>Add</button><button onClick=\"javascript:removeConditionDefinition(this)\" class=\"btn btn-danger\" style=\"display: inline-block;\">x</button");
		break;
	}
}
// new condition add button function
function addNewCondition(element, event) {
	conditionSelectElement = new Conditions(element).dropdown(element);
	jQuery(element).closest('.conditional-selection').after(conditionSelectElement) && jQuery(element).prop('disabled', true);
}
// constructs condition object
function pushConditionSpec(element) {
  // jQuery(element).closest('sdfdsf');
  parentElementId = jQuery(element).closest('.content').data('uniqueId');
  try {
  	conditionObject[parentElementId];
  	conditionObject[parentElementId][0];
  } catch (error) {
  	conditionObject[parentElementId] = [];
  	conditionObject[parentElementId][0] = {};
  }
  // jQuery(element).closest('.conditional-selection-steps');
  stageAValue = jQuery(element).closest('.conditional-selection-steps').find('.condition-stage-a').val();
  try {
  	conditionObject[parentElementId][0][stageAValue];
  	conditionObject[parentElementId][0][stageAValue].op = jQuery(element).closest('.conditional-selection-steps').find('.condition-stage-b').val();
  	conditionObject[parentElementId][0][stageAValue].val = jQuery(element).closest('.conditional-selection-steps').find('.condition-stage-c').val() || 'unset';
  } catch (error) {
  	conditionObject[parentElementId][0][stageAValue] = {
  		op : jQuery(element).closest('.conditional-selection-steps').find('.condition-stage-b').val(),
  		val: jQuery(element).closest('.conditional-selection-steps').find('.condition-stage-c').val() || 'unset'
  	};
  }
  jQuery(element).closest('.conditional-selection-steps').find('.condition-stage-a');
}
// The Conditions class fetches data about all the elements to apply conditional logic on them, used in the editing area
class Conditions {
  /* conditions constructor function gets the source element, helps filter out the elements
   so same subsection doesn't show up on the dropdown
   */
   constructor(origin) {
   	this.origin = origin;
   	try {
   		this.originElementUid = generateUID(jQuery(this.origin).closest('.content'));
   	} catch (error) {
      // todo
      this.originElementUid = false;
  }
    // return this.getDataObject();
}
  // returns the dropdown options in the stages of condition definition, although named dropdown, it manages checkboxes and number input element types conditions too
  dropdown(isFromAddButton = null) {
  	var arrayC = '<option style="font-size: 10px" value="unset">Select an element</option>';
  	var optItems = 0;
    // Iterate over object and add options to select
    function getFilteredDropdownItems(ctx) {
    	var originUuid = jQuery(isFromAddButton).closest('.content').data('uniqueId');
    	var y = Object.keys(conditionObject[originUuid][0]);
    	var elements = ctx.getDataObjectWithSchema();
    	for (var x=0; x<= y.length; x++) {
    		elements = elements.filter(n => {
    			return n.uniqueId != y[x];
    		});
    	}
    	return elements;
    }
	/* if it is triggered from an add button it filters the currently defined condition and excludes the existing ones
	selectoptions are for dropdowns, switchoptions are for checkboxes and radio elements,
	numberoption is for number/quantity input fields */
	jQuery.each(isFromAddButton ? getFilteredDropdownItems(this) : this.getDataObjectWithSchema(), function(index, value){
		switch (value.type) {
			case 'selectoption':
			arrayC += `<option value="${value.uniqueId}">${value.value[0].title}</option>`;
			optItems += 1;
			break;
			case 'switchoption':
			if (isFromAddButton) {
				var originUuid = jQuery(isFromAddButton).closest('.content').data('uniqueId');
				var y = Object.keys(conditionObject[originUuid][0]);
				var process = (arg) => qq => {
					if(!arg.y.some(e => e == qq.uniqueId)) return `<option value="${qq.uniqueId}">${qq.name}</option>`;
				}
				arrayC += value.value.map(process({originUuid, y}));
				optItems += 1;
				return;
			}
			arrayC += value.value.map(e => {
				return `<option value="${e.uniqueId}">${e.name}</option>`
			});
			optItems += 1;
			break;
			case 'number_option':
			arrayC += `<option value="${value.uniqueId}">${value.value[0].title}</option>`;
			optItems += 1;
			break;
			case 'slider':
			arrayC += [...new Set(value.value.map(e => e.uniqueId))].map(e => value.value.filter(ee => ee.uniqueId == e)[0]).map(e => {
				return `<option value="${e.uniqueId}">${e.title}</option>`
			});
			optItems += 1;
			break;
			default:
			break;
		}
	});
	// quits if no more options are there
	if(optItems < 1) {
		return;
	}
	// filtering for add button populated options
	if (isFromAddButton) {
		return `<div class="col-xs-12 col-md-12 conditional-selection" style="padding: 0px; margin-bottom: 5px;">
		<div><div class="col-xs-1 col-md-1" style="padding:0px;height:40px;background: #DCF1FD;"><span class="scc_label" style="text-align:right;padding-right:10px;margin-top:5px;">And</span></div></div>
		<div class="col-xs-11 col-md-11" style="padding:0px;"><div class="conditional-selection-steps scc-col-xs-12 scc-col-md-12" style="padding:0px;">
		<select class="condition-stage-a" onFocus="javascript:sccStoreConditionDropdwnValue(this)" onChange="javascript:logChanges(this, event)" style="width:27%;float:left;height:41px;">
		${arrayC}
		</select>
		</div></div>
		</div>`;
	}
  // if not from add button click, all of the options are sent
  return `<div class="col-xs-12 col-md-12 conditional-selection" style="padding: 0px; margin-bottom: 5px;">
  <div><div class="col-xs-1 col-md-1" style="padding:0px;height:40px;background: #DCF1FD;"><span class="scc_label" style="text-align:right;padding-right:10px;margin-top:5px;">Show if</span></div></div>
  <div class="col-xs-11 col-md-11" style="padding:0px;"><div class="conditional-selection-steps scc-col-xs-12 scc-col-md-12" style="padding:0px;">
  <select class="condition-stage-a" onFocus="javascript:sccStoreConditionDropdwnValue(this)" onChange="javascript:logChanges(this, event)" style="width:27%;float:left;height:41px;">
  ${arrayC}
  </select>
  </div></div>
  </div>`;
}
// helps logging the element passed through the Conditions class
log() {
	console.log(this.origin);
}
  // Returns all of the sections, elements, basically everything about the currently compiled data in the editing area
  getDataObject() {
  	var SectionName = [];
  	var a = 0;
  	jQuery('#allinputstoadd .addedFieldsStyle').each(function() {
  		var sliderChecked = 0;
  		var elementOption = jQuery(this).find('.boardOption').length;
  		if (elementOption != 0) {
  			var elementNo = 0;
			var emptyValuesError =false //this variable wasnt initialized
  			var allfieldOptions2 = [];
  			jQuery(this).find('.boardOption').each(function(){
  				var allfieldOptions = [];
  				var is = 0;
  				jQuery(this).find('.BodyOption').each(function() {
  					jQuery(this).find('.content').each(function() {
  						var fieldType = jQuery(this).attr('value');
  						var count = 0;
  						var allfieldOptions1 = [];
  						switch (fieldType) {
  							case "buttonoption":
  							var fieldButtonServiceName = jQuery(this).find('.inputbuttonservice_title').val();
  							var s_length = jQuery(this).find('.buttonoption_3').length;
  							jQuery(this).find('.buttonoption_3').each(function() {
  								buttonError = validateSwitch(jQuery(this).parent().parent(), jQuery(this).find('.buttoninputoption').val(), jQuery(this).find('.buttoninputoption_2').val());
  								if (buttonError === true) {
  									return;
  								}
  								allfieldOptions1[count] = new ElementArray(count, fieldButtonServiceName, jQuery(this).find('.buttoninputoption').val(), jQuery(this).find('.buttoninputoption_2').val(), 0, jQuery(this).find('.scc_woo_commerce_product_id') ? jQuery(this).find('.scc_woo_commerce_product_id').val() : '', false, jQuery(this).find('.buttoninputoption').val());
  								count++;
  							});
  							allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length, null, generateUID(this));
  							is++;
  							break;
  							case "switchoption":
  							var s_length = jQuery(this).find('.switchoption_3').length;
  							var s_type = jQuery(this).find('.fieldFormat').val();
  							jQuery(this).find('.switchoption_3').each(function() {
                        // switchError = validateSwitch(jQuery(this).parent().parent(), jQuery(this).find('.switchinputoption').val(), jQuery(this).find('.switchinputoption_2').val());
                        // if (switchError === true) {
                        //   emptyValuesError = switchError
                        //   return;
                        // }
                        if(jQuery(this).parent().parent().find('.scc_title_column_dskp_chkbx').val() != ''){
                        	var scc_title_column_dskp_chkbx = jQuery(this).parent().parent().find('.scc_title_column_dskp_chkbx').val();
                        }
                        if(jQuery(this).parent().parent().find('.scc_title_column_mobl_chkbx').val() != ''){
                        	var scc_title_column_mobl_chkbx = jQuery(this).parent().parent().find('.scc_title_column_mobl_chkbx').val();
                        }
                        var scc_woo_commerce_product_id_switchoption = 0;
                        if(jQuery(this).find('.scc_woo_commerce_product_id').val() != '' && jQuery(this).find('.scc_woo_commerce_product_id').val() != null){
                        	scc_woo_commerce_product_id_switchoption = jQuery(this).find('.scc_woo_commerce_product_id').val()
                        }
                        if(scc_woo_commerce_product_id_switchoption == 0) {
                         /*
                          wooCommerceElementsError.push({
                                name: jQuery(this).find('.switchinputoption').val(),
                                type: 'Checkbox / Toggle / Simple Button'
                              })
                              */
                          }
                          var isPriceHintEnabled = jQuery(this).find('.styled-accordion:eq(0) input.scc-scc_accordion_section').is(':checked');
                          allfieldOptions1[count] = new ElementArray(count, 0, jQuery(this).find('.switchinputoption').val(), jQuery(this).find('.switchinputoption_2').val(), s_type,'',scc_title_column_dskp_chkbx, scc_title_column_mobl_chkbx, scc_woo_commerce_product_id_switchoption, jQuery(this).find('.col-xs-2.col-md-2.tooltipadmin-left[data-selected="true"]').length ? true : false, isPriceHintEnabled, jQuery(this).find('.switchinputoption'),'', generateUID(this));
                          count++;
                      });
  							allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length, null, generateUID(this));
  							is++;
  							break;
  							case "selectoption":
                  var fieldDropServiceName = jQuery(this).find('.inputoption_title').val(); //inputoption_title
                  if(jQuery(this).find('.scc_mandatory_dropdown').prop('checked')){
                    var dropdownServiceMandatory = 'yes'; //mandatory dropdown
                }else{
                    var dropdownServiceMandatory = 'no'; //mandatory dropdown
                }
                if(jQuery(this).find('.selopt3').parent().parent().find('.scc_title_column_dskp').val() != ''){
                	var scc_title_column_dskp = jQuery(this).find('.selopt3').parent().parent().find('.scc_title_column_dskp').val();
                }
                if(jQuery(this).find('.selopt3').parent().parent().find('.scc_title_column_mobl').val() != ''){
                	var scc_title_column_mobl = jQuery(this).find('.selopt3').parent().parent().find('.scc_title_column_mobl').val();
                }
                var s_length = jQuery(this).find('.selopt3').length;
                  var $thisDropDown = this; //inside the each loop, this will have a different value
                  jQuery(this).find('.selopt3').each(function() {
                    // dropdownError = validateDropDown(fieldDropServiceName, $thisDropDown, jQuery(this).find('.inputoption').val(), jQuery(this).find('.inputoption_2').val(),dropdownServiceMandatory);
                    // if (dropdownError === true) {
                    //   emptyValuesError = dropdownError
                    //   return;
                    // }
                    if(!jQuery(this).find('.scc_woo_commerce_product_id') || jQuery(this).find('.scc_woo_commerce_product_id').val() == 0 ||  jQuery(this).find('.scc_woo_commerce_product_id').val() == null) {
                      /*
                      wooCommerceElementsError.push({
                            name: fieldDropServiceName + ' | Option: '+ jQuery(this).find('.inputoption').val(),
                            type: 'Dropdown'
                          })
                          */
                      }
                      allfieldOptions1[count] = new ElementArray(count, fieldDropServiceName, jQuery(this).find('.inputoption').val(), jQuery(this).find('.inputoption_2').val(), jQuery(this).find('.inputoption_desc').val(),dropdownServiceMandatory,scc_title_column_dskp,scc_title_column_mobl, jQuery(this).find('.scc_woo_commerce_product_id') ? jQuery(this).find('.scc_woo_commerce_product_id').val() : '', jQuery(this).find('.col-xs-2.col-md-2.tooltipadmin-left[data-selected="true"]').length ? true : false, false, jQuery(this).find('.inputoption'));
                      count++;
                  });
                  allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length, null, generateUID(this));
                  is++;
                  break;
                  case "comment_option":
                  var fieldCommentName = jQuery(this).find('.inputoption_title').val(); //inputoption_title
                  if(jQuery(this).find('.scc_mandatory_comment').prop('checked')){
                  var commentMandatory = 'yes'; //mandatory dropdown
              }else{
                  var commentMandatory = 'no'; //mandatory dropdown
              }
              var s_length = jQuery(this).find('.selopt5').length;
                  var $thisDropDown = this; //inside the each loop, this will have a different value
                  var commentError = validateComment(fieldCommentName, $thisDropDown);
                  if (commentError === true) {
                  	emptyValuesError = commentError
                  	return;
                  }
                  jQuery(this).find('.selopt5').each(function() {
                  	if(jQuery(this).parent().prev().find('.scc_title_column_dskp_cmntbx').val() != ''){
                  		var scc_title_column_dskp_cmntbx = jQuery(this).parent().prev().find('.scc_title_column_dskp_cmntbx').val();
                  	}
                  	if(jQuery(this).parent().prev().find('.scc_title_column_mobl_cmntbx').val() != ''){
                  		var scc_title_column_mobl_cmntbx = jQuery(this).parent().prev().find('.scc_title_column_mobl_cmntbx').val();
                  	}
                  	allfieldOptions1[count] = new ElementArray(count, fieldCommentName, jQuery(this).find('.inputoption').val(), jQuery(this).find('.inputoption_2').val(), jQuery(this).find('.inputoption_desc').val(),commentMandatory,scc_title_column_dskp_cmntbx, scc_title_column_mobl_cmntbx,  jQuery(this).find('.scc_woo_commerce_product_id') ? jQuery(this).find('.scc_woo_commerce_product_id').val() : '', {eleemnt: jQuery(this).find('.inputoption')});
                  	count++;
                  });
                  allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length, null, generateUID(this));
                  is++;
                  break;
                  case "number_option":
                      var fieldNumberName = jQuery(this).find('.inputoption_title').val(); //inputoption_title
                      if(jQuery(this).find('.scc_mandatory_number').prop('checked')){
                        var numberMandatory = 'yes'; //mandatory dropdown
                    }else{
                        var numberMandatory = 'no'; //mandatory dropdown
                    }
                    var s_length = jQuery(this).find('.selopt3').length;
                      var $thisDropDown = this; //inside the each loop, this will have a different value
                      commentError = validateQuantityBox(fieldNumberName, $thisDropDown, jQuery(this).find('.inputoption_2').val());
                      if (commentError === true) {
                      	emptyValuesError = commentError
                      	return;
                      }
                      jQuery(this).find('.selopt3').each(function() {
                      	if(jQuery(this).parent().parent().prev().find('.scc_title_column_dskp_numbx').val() != ''){
                      		var scc_title_column_dskp_numbx = jQuery(this).parent().parent().prev().find('.scc_title_column_dskp_numbx').val();
                      	}
                      	if(jQuery(this).parent().parent().prev().find('.scc_title_column_mobl_numbx').val() != ''){
                      		var scc_title_column_mobl_numbx = jQuery(this).parent().parent().prev().find('.scc_title_column_mobl_numbx').val();
                      	}
                      	var scc_woo_commerce_product_id_number_box = 0;
                      	if(jQuery(this).parent().find('.scc_woo_commerce_product_id').val() != '' && jQuery(this).parent().find('.scc_woo_commerce_product_id').val() != null){
                      		scc_woo_commerce_product_id_number_box = jQuery(this).parent().find('.scc_woo_commerce_product_id').val()
                      	}
                      	if(jQuery(this).parent().parent().prev().find('.scc_title_column_mobl_numbx').val() != ''){
                      	}
                      	if(scc_woo_commerce_product_id_number_box == 0 ) {
                            /*
                            wooCommerceElementsError.push({
                                    name: fieldNumberName,
                                    type: 'Number Box'
                                  })
                                  */
                              }
                              allfieldOptions1[count] = new ElementArray(count, fieldNumberName, jQuery(this).find('.inputoption').val(), jQuery(this).find('.inputoption_2').val(), jQuery(this).find('.inputoption_desc').val(),numberMandatory,scc_title_column_dskp_numbx,scc_title_column_mobl_numbx, scc_woo_commerce_product_id_number_box, {eleemnt: jQuery(this).find('.inputoption')});
                              count++;
                          });
                      allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length, null, generateUID(this));
                      is++;
                      break;
                      default:
                  }
              });
});
if(jQuery(this).find('.scc_custom_math_checkbox').is(':checked') && jQuery(this).find('.scc_custom_math').is(':visible')) {
                //No, title, name, value1, value2,mandatory,column_dskp,column_mobl, scc_woo_commerce_product_id, opt_default) {
                	var allfieldOptionsCustomMath=[];
                	var scc_custom_math_display_front_end = false;
                	if(jQuery(this).find('.scc_custom_math_display_front_end').is(':checked')){
                		scc_custom_math_display_front_end = true;
                	}
                	var scc_custom_math_display_detailed_list = false
                	if(jQuery(this).find('.scc_custom_math_display_detailed_list').is(':checked')){
                		scc_custom_math_display_detailed_list = true
                	}
                	var custom_math_name = jQuery(this).find('.scc_custom_math_name').val()
                	var custom_math_type = jQuery(this).find('.scc_custom_math_type option:selected:last').val()
                	var custom_math_value = jQuery(this).find('.scc_custom_math_value').val()
                  var $thisDropDown = this; //inside the each loop, this will have a different value
                  // customMathError = validateCustomMath(custom_math_name, $thisDropDown, custom_math_value);
                  // if (customMathError === true) {
                  //   emptyValuesError = customMathError
                  //   return;
                  // }
                  allfieldOptionsCustomMath.push(new ElementArray(0, custom_math_name, custom_math_type, 0, custom_math_value,"",scc_custom_math_display_front_end,scc_custom_math_display_detailed_list, ""))
                //count++;
                allfieldOptions[is] = new InputOptions (is,"'scc_custom_math'",allfieldOptionsCustomMath,1, null, generateUID(jQuery(this).find('.content.scc_custom_math')));
                is++;
            }
            if (jQuery(this).find('.inputoption_slidchk').is(':checked')) {
            	sliderChecked = 1; var allfieldOptions3=[];
            	var fieldServiceName = jQuery(this).find('.sliderinputoption_T').val();
            	var s_length = jQuery(this).find('.price_table tbody tr').length;
            	var ktable=0;
                  // sliderError = validateSlider(this, fieldServiceName)
                  // if(sliderError === true) {
                  //   emptyValuesError = sliderError
                  //   return
                  // }
                  var uniqueID = jQuery(this).find('.selslideropt_4.content').data('uniqueId');
                  if(jQuery(this).find('.scc_title_column_dskp_slider').val() != ''){
                  	var scc_title_column_dskp_slider = jQuery(this).find('.scc_title_column_dskp_slider').val();
                  }
                  if(jQuery(this).find('.scc_title_column_mobl_slider').val() != ''){
                  	var scc_title_column_mobl_slider = jQuery(this).find('.scc_title_column_mobl_slider').val();
                  }
                  var scc_woo_commerce_product_id_slider = 0;
                  if (jQuery(this).find('.scc_woo_commerce_product_id option:selected:last').val() != ''){
                  	var scc_woo_commerce_product_id_slider = jQuery(this).find('.scc_woo_commerce_product_id option:selected:last').val()
                  }
                  jQuery(this).find('.price_table tbody tr').each(function() {
                  	allfieldOptions3[ktable] = new ElementArray(ktable, fieldServiceName, jQuery(this).find('.sliderinputoption').val(), jQuery(this).find('.sliderinputoption_2').val(), jQuery(this).find('.sliderinputoption_5').val(),'',scc_title_column_dskp_slider,scc_title_column_mobl_slider,  scc_woo_commerce_product_id_slider, null, null, null, null, uniqueID);
                  	ktable++;
                  });
                  var step = jQuery(this).find('.slidoption_3').val();
                  var defaultValue = jQuery(this).find('.slidoption_4').val();
                  var showPriceHint = jQuery(this).find('.slidoption_5').prop('checked');
                  var isSlidingScale = jQuery(this).find('.slider-discount-type').val() == 'sliding-scale';
                  generateUID(jQuery(this).find('.selslideropt_4.content'));
                  allfieldOptions2[elementNo] = new SubOptions(elementNo,allfieldOptions, allfieldOptions3, step, defaultValue, showPriceHint, isSlidingScale, uniqueID);
              }
              else {
              	sliderChecked = 0;
              	allfieldOptions3 = [];
              	allfieldOptions2[elementNo] = new SubOptions(elementNo, allfieldOptions, allfieldOptions3, 0, 0, 0);
              }
              elementNo++;
          });
}
else {
	var allfieldOptions2 = [];
}
      /* OLD SectionOptions without Title Column and WITH accordion, OLD Save
        SectionName[a] = new sliderOptions(jQuery(this).find('.sectiontitle').val(), jQuery(this).find('.sectionDescription').val().replace(/(\r\n|\n|\r)/gm,'<br />') + (jQuery(this).find('.scc_accordion_section').prop("checked") ? '///accordion:yes///' : ''),a,allfieldOptions2);
        */
     // new SectionOptions
     var title_column_desktop = jQuery(this).find('.title_column_desktop') && jQuery(this).find('.title_column_desktop').val() ? jQuery(this).find('.title_column_desktop').val() : 4
     var title_column_mobile = jQuery(this).find('.title_column_mobile') && jQuery(this).find('.title_column_mobile').val() ? jQuery(this).find('.title_column_mobile').val() : 10
     SectionName[a] = new sectionOptions( jQuery(this).find('.sectiontitle').val(), jQuery(this).find('.sectionDescription').val().replace(/(\r\n|\n|\r)/gm,'<br />'),jQuery(this).find('.scc_accordion_section:eq(0)').prop("checked"), title_column_desktop, title_column_mobile, a,allfieldOptions2, );
     a++;
 });
return SectionName;
}
  // not useful now, but it was once used when I was developing the feature
  getDataObjectFlattened(dropdownTitleElement) {
  	var data = this.getDataObject();
    // return _.map(data, ((e,i) => {return e.value})).flat().map(item => {return item.Nooptions}).flat().map((e,i) => {return e.value}).flat().filter((n) => {return n.title != dropdownTitleElement.find('input').val()});
    // return _.map(
    //   data, ((bc, index) => {
    //     return _.map(bc.value, (e,i) => {return _.map(bc.value[i].Nooptions, function(num, index){ num.value.map((e) => {e.parentId = i; e.subParent = index}); return num.value; }).flat()}).flat().filter((n) => {return n.title != dropdownTitleElement.find('input').val()})
    //   })
    // )
    return data.map((bc,i) => {return _.map(bc.value, (ee,ii) => {return _.map(bc.value[ii].Nooptions, function(num, index){ num.value.map((e) => {e.parentId = ii;e.secId = i; e.subParent = index}); return num.value; })})}).flat().flat().flat().filter((n) => {return n.title != dropdownTitleElement.find('input').val()})
}
  // returns a formatted values for use with dropdowns of confitional logic definition
  getDataObjectWithSchema() {
  	var data = this.getDataObject();
  	var allElements = data.map((bc,i) => {return _.map(bc.value, (ee,ii) => {return ee})}).flat().map(eee => eee.Nooptions).flat().filter(n => n.uniqueId != this.originElementUid);
	var sliders = data.map((bc,i) => {return _.map(bc.value, (ee,ii) => {return ee})}).flat().map(eee => {return eee.minmax}).flat();
	var sliderElements = new InputOptions (0,'slider',sliders,sliders.length, null, null);
    return [sliderElements, ...allElements];
}
}
// helps the floating total price bar keep showing as it should
function autoscroll() {
	window.setTimeout(autoscroll, 100);
	jQuery('.scc_total_price_float').css({"z-index": "9999","position": "fixed", "bottom": "0%","left": "0","margin": "auto","width":"70%","height":"auto"});
}
if (window.location.pathname == '/wp-admin/') {
	var numberOfFields = jQuery('#allinputstoadd .addedFieldsStyle').length;
	var numberOfSections = 0;
}
var numberOfElements = 0;
// helps loading examples in the add new calculator page's template dropdown
function loadExample($this) {
	$fragment_refresh = {
		url: rt_vars.rt_urlajax,
		type: 'POST',
		data: {
			action: 'loadExample',
			data_example: jQuery($this).val()
		},
		success: function(data) {
			location.href = rt_vars.rt_adminurl + '?page=edit_sccbyid&id=' + data.trim();
		}
	};
	document.getElementById("scc-editing-area-loading") ? document.getElementById("scc-editing-area-loading").style.width = "100%" : null;
	jQuery.ajax($fragment_refresh);
}
// helps add the slider in the subsection
function addSlider($this) {
	demo = jQuery('#scc-demover').attr('data-demo');
	var elementsAdded = jQuery('.elements_added') ? jQuery('.elements_added').length : 0
	if(demo == 0 && elementsAdded > 3){
		jQuery('#scc-demover').html('You cannot add more than 3 elements. Purchase the pro version <a href="https://stylishcostcalculator.com/">here</a>.').fadeIn();
		jQuery('.hover_bkgr_fricc').show();
		jQuery("#hover_bkgr_fricc_message").html("<b><b>You cannot add more than 3 elements; However, you might able add more subsections or more elements within the currenct sections & subsections. <br> Purchase the pro version <a href=\"https://stylishcostcalculator.com/\">here</a>. It's a one-time purchase with free lifetime upgrades.</b></b>")
		return;
	}else{
		if (jQuery($this).parent().find('.inputoption_slidchk').is(':checked')){
			jQuery($this).parent().find('.inputoption_slidchk').prop('checked', false);
		} else {
			jQuery($this).parent().find('.inputoption_slidchk').prop('checked', true);
			var code = ""
			code += '    <div id="modalSliderInfo" class="scc-modal-2020 fade" role="dialog" data-backdrop="static" data-keyboard="false" >'
			code += '        <div class="scc-modal-dialog-2020" style="width:660px;top:250px;">'
			code += '          <div class="scc-modal-content-2020">'
			code += '            <div class="scc-modal-header-2020">'
			code += '             <button type="button" class="close" data-dismiss="modal">&times;</button>'
			code += '             <h4 class="scc-modal-title-2020">Slider information</h4>'
			code += '            </div>'
			code += '            <div class="scc-modal-body-2020" >'
			code += '<p> Please check this documentation in order to understand how the Slider works. </br><a target="_blank" href="https://designful.freshdesk.com/support/solutions/articles/48000964920-important-understanding-the-math-of-a-slider-sub-section-or-elements">Slider Documentation</a></p>'
			code += '<p> This video tutorial may help you too: <a target="_blank" href="https://www.youtube.com/watch?v=wDZZyg8U_hQ">Tutorial video</a> </p>'
			code += '            </div>'
			code += '            <div class="modal-footer">'
			code += '              <button type="button" class="btn btn-default" data-dismiss="modal" onclick="cancelSliderInfoModal()">Accept</button>'
			code += '            </div>'
			code += '           </div>'
			code += '        </div>'
			code += '      </div>'
			jQuery('#slider_info_modal').html(code)
			jQuery('#modalSliderInfo').modal('show')
		}
		jQuery($this).parent().parent().find('.selslideropt_3').slideToggle();
		jQuery($this).parent().parent().find('.selslideropt_3 .styled-accordion').sccAccordion();
		jQuery('html, body').animate({
			scrollTop: jQuery($this).parent().parent().find('.selslideropt_3').offset().top
		}, 1000);
	}
}
// hides slider info modal.
function cancelSliderInfoModal(){
	jQuery('#modalSliderInfo').modal('hide')
}
// removes the slider from the subsection
function removeSlider($this) {
	if (jQuery($this).closest('.boardOption').find('.inputoption_slidchk').is(':checked')){
		jQuery($this).closest('.boardOption').find('.inputoption_slidchk').prop('checked', false);
	} else {
		jQuery($this).closest('.boardOption').find('.inputoption_slidchk').prop('checked', true);
		var code = ""
		code += '    <div id="modalSliderInfo" class="scc-modal-2020 fade" role="dialog" data-backdrop="static" data-keyboard="false" >'
		code += '        <div class="scc-modal-dialog-2020" style="width:660px;top:250px;">'
		code += '          <div class="scc-modal-content-2020">'
		code += '            <div class="scc-modal-header-2020">'
		code += '             <button type="button" class="close" data-dismiss="modal">&times;</button>'
		code += '             <h4 class="scc-modal-title-2020">Slider information</h4>'
		code += '            </div>'
		code += '            <div class="scc-modal-body-2020" >'
		code += '<p> Please check this documentation in order to understand how the Slider works. </br><a target="_blank" href="https://designful.freshdesk.com/support/solutions/articles/48000964920-important-understanding-the-math-of-a-slider-sub-section-or-elements">Slider Documentation</a></p>'
		code += '<p> This video tutorial may help you too: <a target="_blank" href="https://www.youtube.com/watch?v=wDZZyg8U_hQ">Tutorial video</a> </p>'
		code += '            </div>'
		code += '            <div class="modal-footer">'
		code += '              <button type="button" class="btn btn-default" data-dismiss="modal" onclick="cancelSliderInfoModal()">Accept</button>'
		code += '            </div>'
		code += '           </div>'
		code += '        </div>'
		code += '      </div>'
		jQuery('#slider_info_modal').html(code)
		jQuery('#modalSliderInfo').modal('show')
	}
	jQuery($this).closest('.boardOption').find('.selslideropt_3').slideToggle();
	jQuery('html, body').animate({
		scrollTop: jQuery($this).closest('.boardOption').find('.selslideropt_3').offset().top
	}, 1000);
}
/*
  custom math functions
  */
  function addCustomMath($this) {
  	jQuery($this).parent().parent().find('.scc_custom_math').slideToggle()
  	jQuery($this).parent().parent().find('.scc_custom_math .styled-accordion').sccAccordion();
  	jQuery('html, body').animate({
  		scrollTop: jQuery($this).parent().parent().find('.scc_custom_math').offset().top
  	}, 1000);
  	if (jQuery($this).parent().find('.scc_custom_math_checkbox').is(':checked'))
  		jQuery($this).parent().find('.scc_custom_math_checkbox').attr('checked', false);
  	else {
  		jQuery($this).parent().find('.scc_custom_math_checkbox').attr('checked', true);
  	}
  }
  function removeCustomMath($this) {
  	jQuery($this).closest('.scc_custom_math').slideToggle();
  	if (jQuery($this).closest('.boardOption').find('.scc_custom_math_checkbox').is(':checked'))
  		jQuery($this).closest('.boardOption').find('.scc_custom_math_checkbox').attr('checked', false);
  	else {
  		jQuery($this).closest('.boardOption').find('.scc_custom_math_checkbox').attr('checked', true);
  	}
  }
/*
  custom math functions
  */
// opens/closes the slider settings in the editing area
function AaddSlider($this) {
	jQuery($this).parent().parent().find('.selslideropt_4').slideToggle();
}
// used by "Add A Product / Service Option" link in the editing area
function addAnotherSwitch($this) {
	var i = 0;
	jQuery($this).parent().parent().find(' .switchoption_3').each(function() {
		i++;
	});
	jQuery($this).parent().parent().find('.switchoption_2').append(jQuery('#switchoption .switchoption_2').html().replace(/XXYYXX/g, ((i / 1) + 1)));
}
// used by "Add A Product / Service Option" link in the editing area but for simple buttons
function addAnotherButton($this) {
	var i = 0;
	jQuery($this).parent().parent().find(' .buttonoption_3').each(function() {
		i++;
	});
	jQuery($this).parent().parent().find('.buttonoption_2').append(jQuery('#buttonoption .buttonoption_2').html().replace(/XXYYXX/g, ((i / 1) + 1)));
}
// the function is not being used anymore
function addAnotherDiscount($this) {
	jQuery($this).parent().parent().find('.switchoption_2').append('<div class="switchoption_3" style="margin-bottom: 5px; margin-top: 5px;"><label class="scc_label col-md-3">&#10080</label> <input placeholder="Name" type="text" class="col-xs-12 col-md-4 input_pad switchinputoption"   /><label class="scc_label " style="">$</label> <input placeholder="Price" type="text" class="col-xs-12 col-md-2 input_pad switchinputoption_2"   /><a href="javascript:void(0)" onClick="remove_field(this)">  &#10062</a></div>');
  // var i = 0;
  // jQuery($this).find('.fieldDatatoAdd .selslideropt_4').each(function() {  i++; } );
  // console.log(i);
  // jQuery($this).parent().parent().find('.fieldDatatoAdd .selslideropt_3').append( jQuery('#AsliderOption .selslideropt_3').html().replace(/XXYYXX/g, (( i / 1) + 1)) );
}
// converts translation table in the editing area to a JSON object then added to the parameters object
function tableToJson(table) {
	var TableData = new Array();
	jQuery('.translate_table tr').each(function(row, tr){
		TableData[row]={
			"key" : jQuery(tr).find('td:eq(0) input').val()
			, "lang" :jQuery(tr).find('td:eq(1) input').val()
			, "translation" : jQuery(tr).find('td:eq(2) input').val()
		}
	});
      TableData.shift();  // first row will be empty - so remove
      return TableData;
  }
// helps add new translation
function addNewTran($this) {
	jQuery($this).parent().parent().find('.translate_table').last().append('<tr><td ><input type="text" value=""/></td><td ><input type="text" value="en"/></td><td ><input type="text" value=""/></td><td><a href="javascript:void(0)" class="fa material-icons" onClick="remove_rowTran(this)" style="font-size: 15px;">x</a></td></tr>');
}
// in slider settings, to add new range, this function is used
function addNewRange($this) {
	var xmax = parseInt(jQuery($this).parent().parent().find('.price_table .sliderinputoption_2:last').val());
	jQuery($this).parent().parent().find('.price_table').last().append('<tr><th ><input type="number" min=' + (xmax + 1) + ' class="input_pad sliderinputoption" value="' + (xmax + 1) + '"    style="width:90px;margin-top:5px;margin-left:12px;padding:5px;height:40px;"align="center" disabled/></th><th ><input type="number" min=' + (xmax + 2) + ' class="input_pad sliderinputoption_2" value="' + (xmax + 100) + '" style="width: 90px;height:40px;margin-top:5px;margin-left:12px;padding:5px"align="center"/></th><th ><input type="number" min=0 class="input_pad sliderinputoption_5" value=""  style="width: 90px;margin-top:5px;height:40px;margin-left:12px;padding:5px;"align="center"/></th><th><a href="javascript:void(0)" class="fa material-icons" onClick="remove_row(this)" style="font-size: 14px;"> X</a></th></tr>');
	sliderPriceRangeInit();
}
// returns all price range rows in the slider settings, used to set relative value in the next rows
function getPriceRangeInputs() {
	return jQuery("#allinputstoadd .price_table .sliderinputoption_2");
};
// finds all "enable conditional element" switches and returns them, helps set on click events on them
function getConditionalSwitches() {
	return {
		slider : jQuery('.scc_accordion_section.slidoption_6'),
		dropdown: jQuery('.scc_conditioned_dropdown')
	};
}
// in slider settings, price ranges, it adds one number to the next row's first cell
function setRelativePrice(maxInput) {
	maxVal = parseInt(jQuery(maxInput).val());
	nextCell = jQuery(maxInput).closest('tr').next().find('.sliderinputoption');
	nextCellMin = parseInt(nextCell.val());
	return nextCell.val(maxVal + 1);
};
// kicks off the logic to set relative values in the price ranges of slider settings
function sliderPriceRangeInit() {
	jQuery.each(getPriceRangeInputs(), (i, elem) => {
		jQuery(elem).change(() => {
			setRelativePrice(elem);
		});
		jQuery(elem).on("input", (() => {
			setRelativePrice(elem);
		}));
	});
};
// jQuery("#allinputstoadd .price_table .sliderinputoption_2").change(function() {
//   var ind = parseInt(jQuery("#allinputstoadd .price_table .sliderinputoption_2").index(this));
//   var maxrange = parseInt(jQuery("#allinputstoadd .price_table .sliderinputoption_2:eq(" + ind + ")").val());
//   var minrange = parseInt(jQuery("#allinputstoadd .price_table .sliderinputoption:eq(" + ind + ")").val());
//   var maxrange1 = parseInt(jQuery("#allinputstoadd .price_table .sliderinputoption_2:eq(" + (ind + 1) + ")").val());
//   if (maxrange1 != NaN) {
//     if (maxrange <= minrange) {
//       jQuery("#allinputstoadd .price_table .sliderinputoption_2:eq(" + (ind) + ")").val(minrange + 100);
//       jQuery("#allinputstoadd .price_table .sliderinputoption:eq(" + (ind + 1) + ")").val(minrange + 101);
//     } else
//       jQuery("#allinputstoadd .price_table .sliderinputoption:eq(" + (ind + 1) + ")").val(maxrange + 1);
//   }
// });
// jQuery('.scc_accordion_section.slidoption_6').each((i, elem) => {
//   jQuery(elem).change(() => {
//     console.log(elem);
//   });
// });
var elementList = null;
// Intiates the conditional logic definitions in the advance settings accordion of the elements
async function initConditionalLogic() {
  // finds the conditional logic enable/disable switches
  jQuery(getConditionalSwitches().dropdown).map((i, elem) => {
	// sets onChange event handler
	jQuery(elem).unbind().change((event) => {
		isStageAInitiated = false;
		sourceElem = jQuery(event.target);
		if (!jQuery(elem).is(':checked')) {
		// handles switch off event of the conditional logic enabler
		jQuery(elem).closest('.elements_added').find('.conditional-selection').remove();
		try {
			delete conditionObject[jQuery(elem).closest('.content').data('uniqueId')];
		} catch (error) {
			throw error;
		}
	}
	  // calls the Conditions class and fetches the sections to populate data to the dropdowns
	  beta = new Conditions(elem);
	  dropdownTitleElement = sourceElem.closest('.scc-transition').find('.condition-container');
	  if (!dropdownTitleElement.parent().find('.conditional-selection').length && jQuery(elem).is(':checked')) dropdownTitleElement.html(beta.dropdown());
	});
});
  return true;
}
// same as the function 'initConditionalLogic' but unused, made to add onchange attribute to the conditional logic switches
function handleConditionalSwitchActions($this, event) {
	let elem = $this;
		isStageAInitiated = false;
		sourceElem = jQuery(event.target);
		if (!jQuery(elem).is(':checked')) {
		  // handles switch off event of the conditional logic enabler
		  jQuery(elem).closest('.scc-new-accordion-container').find('.conditional-selection').remove();
		  try {
		  	delete conditionObject[jQuery(elem).closest('.content').data('uniqueId')];
		  } catch (error) {
		  	throw error;
		  }
		}
		// calls the Conditions class and fetches the sections to populate data to the dropdowns
		beta = new Conditions(elem);
		dropdownTitleElement = sourceElem.closest('.scc-transition').find('.condition-container');
		if (!dropdownTitleElement.parent().find('.conditional-selection').length && jQuery(elem).is(':checked')) dropdownTitleElement.html(beta.dropdown());
	}
// in slider range settings in the backend, removes row of the ranges when the button clicked
function remove_row($this) {
	var maxrange = jQuery($this).parent().parent().next().find('.sliderinputoption_2').val();
	var maxrange1 = parseInt(jQuery($this).parent().parent().prev().find('.sliderinputoption_2').val());
	if (maxrange != undefined)
		jQuery($this).parent().parent().next().find('.sliderinputoption').val((maxrange1 + 1));
	jQuery($this).parent().parent().remove();
}
// in translation settings, removes the table row
function remove_rowTran($this) {
	jQuery($this).parent().parent().remove();
}
// unused
function addOptiontoSlider($this) {
	var i = 0;
	jQuery($this).parent().parent().parent().find('.fieldDatatoAdd .selslideropt_2 .selslideropt_3').each(function() {
		i++;
	})
	jQuery($this).parent().parent().parent().find('.fieldDatatoAdd .selslideropt_2').append("<hr />" + jQuery('#sliderOption .selslideropt_2').html().replace(/XXYYXX/g, ((i / 1) + 1)));
}
// unused
function addaOptiontoSlider($this) {
	var i = 0;
  // console.log(jQuery($this).parent().parent().parent().parent().find('.fieldDatatoAdd .selslideropt_2').get());
  //        jQuery($this).parent().parent().parent().find('.fieldDatatoAdd .selslideropt_2').append("<div Class=Test>");
  jQuery($this).parent().parent().parent().find('.fieldDatatoAdd .selslideropt_2 .selslideropt_3').each(function() {
  	i++;
  })
  jQuery($this).parent().parent().parent().find('.fieldDatatoAdd .selslideropt_2').append(" <hr />" + jQuery('#AsliderOption .selslideropt_2').html().replace(/XXYYXX/g, ((i / 1) + 1)));
} //.replace(/hide1/g, "hide"+(i + 1)) );
// related to woocommerce products selection
function addOptiontoSelect($this) {
	var i = 0;
	jQuery($this).parent().parent().find('.content .selectoption_2 .selopt3').each(function() {
		i++;
	})
	jQuery($this).parent().parent().find('.content .selectoption_2').append(jQuery('#selectoption .selectoption_2').html().replace(/XXYYXX/g, (i + 1)));
}
function fieldItems(fieldFormat, name, description, type, sevoptions) //used for the main item
{
	this.name = name;
	this.description = description;
	this.type = type;
	this.typeFormat = fieldFormat;
	this.allOptions = sevoptions;
}
/* handles "add Element" buttons feature, takes the value attribte of the buttons,
the optionValue is the number to be set default when using a checkbox/radio element */
function getFieldOptionx($f, optionValue) {
        var fieldOpt = jQuery($f).val(); //we fetch the HTML using the IDs:
        var fieldStyle = jQuery($f).parent().parent().parent().find('.fieldstyle');
        demo = jQuery('#scc-demover').attr('data-demo');
        var elementsAdded = jQuery('.elements_added') ? jQuery('.elements_added').length : 0
        if(jQuery('.selslideropt_3')){
        	if(jQuery('.selslideropt_3').css('display') === 'block'){
        		elementsAdded++
        	}
        }
        if(demo == 0 && elementsAdded >= 3){
        	jQuery('#scc-demover').html('You cannot add more than 3 elements. Purchase the pro version <a href="https://stylishcostcalculator.com/">here</a>.').fadeIn();
        	jQuery('.hover_bkgr_fricc').show();
        	jQuery("#hover_bkgr_fricc_message").html("<b><b>You cannot add more than 3 elements; However, you might able add more subsections or more elements within the currenct sections & subsections. <br> Purchase the pro version <a href=\"https://stylishcostcalculator.com/\">here</a>. It's a one-time purchase with free lifetime upgrades.</b></b>")
        	return;
        }else{
        	switch (fieldOpt) {
        		case "titledesc":
        		fieldOpt = jQuery('#titledescdiv').html();
        		fieldStyle.html('');
        		break;
        		case "sliderinput":
        		fieldOpt = jQuery('#sliderOption').html();
        		fieldStyle.html('');
        		break;
        		case "Asliderinput":
        		fieldOpt = jQuery('#AsliderOption').html();
        		fieldStyle.html('');
        		break;
        		case "switchinput":
        		fieldOpt = jQuery('#switchoption').html().replace(/XXYYXX/g, 1);
                //                fieldStyle.html(jQuery('#checkboxstyle').html());
                break;
                case "dropdowninput":
                fieldOpt = jQuery('#selectoption').html().replace(/XXYYXX/g, 1);
                fieldStyle.html('');
                break;
                case "simplebuttons":
                fieldOpt = jQuery('#buttonoption').html().replace(/XXYYXX/g, 1);
                fieldStyle.html('');
                break;
                case "comment_input":
                fieldOpt = jQuery('#comment_option').html().replace(/XXYYXX/g, 1);
                fieldStyle.html('');
                break;
                case "number_input":
                fieldOpt = jQuery('#number_option').html().replace(/XXYYXX/g, 1);
                fieldStyle.html('');
                break;
                case "file_input":
                fieldOpt = jQuery('#fileupload_option').html().replace(/XXYYXX/g, 1);
                fieldStyle.html('');
				break
                case "custom_code":
                fieldOpt = jQuery('#custom_code').html().replace(/XXYYXX/g, 1);
                fieldStyle.html('');
                break;
                default:
                fieldOpt = jQuery('#inputoptiontext').html();
                fieldStyle.html('');
            }
            var finalParent = jQuery($f).parent().parent()
            fieldOpt = '<div class="elements_added">' + fieldOpt + '</div>'
            var subSection = jQuery(finalParent.find('.subsection-area')[0]).append(fieldOpt)
            var createdElement = subSection.find('.elements_added:last');
            // initConditionalLogic();
            subSection.find('.styled-accordion').sccAccordion();
            createdElement.css({border: '2px dashed rgb(138, 153, 248)'});
            setTimeout(() => {
            	createdElement.css({border: '2px solid rgb(138, 153, 248)'});
            }, 10000);
            if(jQuery($f).val() === "switchinput"){
            	jQuery(finalParent.find('.fieldFormat')[finalParent.find('.fieldFormat').length - 1]).children('option').each( function() {
            		if(Number(jQuery(this).val()) === Number(optionValue)){
            			jQuery(this).prop('selected', true)
            		}
            	})
            }
            /*
              scroll to the new element added START
              */
              jQuery('html, body').animate({
              	scrollTop: jQuery(finalParent.find('.elements_added:last')).offset().top
              }, 1000);
          /*
              scroll to the new element added END
              */
          }
          if(window.hasOwnProperty("addSortableFeatureEachElement")){
          	addSortableFeatureEachElement(false)
          }
          jQuery($f).parent().hide(300);
          jQuery($f).parent().prev().show(300);
      }
// unused
function dropDownOptions(name, value, description, sliderChecked, slide_name, slidoption_1, slidoption_2, slidoption_3, slidoption_4, slidoption_5) //used for option-value pairs (select)
{
	this.name = name;
	this.value = value;
  this.description = description; //description will be null for checkboxes
  this.sliderChecked = sliderChecked;
  if (sliderChecked) {
  	this.slidename = slide_name;
  	this.slidoption_1 = slidoption_1;
  	this.slidoption_2 = slidoption_2;
  	this.slidoption_3 = slidoption_3;
  	this.slidoption_4 = slidoption_4;
  	this.slidoption_5 = slidoption_5;
  }
}
// function inputoptions(name, value, description) //used for option-value pairs (select)
// {
//   this.name = name;
//   this.value = value;
//   this.description = description; //description will be null for checkboxes
// }
function discountoptions(min, max, newprice) //used for option-value pairs (select)
{
	this.min = min;
	this.max = max;
	this.newprice = newprice;
}
// adding workaround for German characters
function germanCharacters(text) {
	if(typeof text == "string"){
		text = text.replace(/ä/g, '[a]')
		text = text.replace(/ö/g, '[o]')
		text = text.replace(/ü/g, '[u]')
		text = text.replace(/ß/g, '[b]')
		text = text.replace(/Ä/g, '[A]')
		text = text.replace(/Ö/g, '[O]')
		text = text.replace(/Ü/g, '[U]')
		text = text.replace(/ẞ/g, '[B]')
	}
	return text
}
// finishing workaround for German characters
// Takes the element's data and saves it
function ElementArray(No, title, name, value1, value2,mandatory,column_dskp,column_mobl, scc_woo_commerce_product_id, opt_default, showPriceHint, element, inputBoxVariant, uniqueId, dropdownLogo) {
	this.No = No;
	this.title = germanCharacters(title);
	this.name = germanCharacters(name);
	this.value1 = germanCharacters(value1);
	this.value2 = germanCharacters(value2);
	this.mandatory = mandatory;
	this.column_dskp = column_dskp;
	this.column_mobl = column_mobl;
	this.scc_woo_commerce_product_id = scc_woo_commerce_product_id;
	this.opt_default = opt_default;
	showPriceHint ? this.showPriceHint = showPriceHint : null;
	element ? this.elemnt = element : null;
	inputBoxVariant ? this.inputBoxVariant = inputBoxVariant : null;
	uniqueId ? this.uniqueId = uniqueId : null;
	dropdownLogo ? this.dropdownLogo = dropdownLogo : null;
}
// processes element values
function InputOptions (element,type,value,length, conditionInputID, uniqueId, mandatory){
	this.element = element;
	this.type = type;
	this.value = value;
	this.length = length;
	this.conditionInputID = conditionInputID;
	this.uniqueId = uniqueId;
	this.mandatory = mandatory || false;
}
function titleDescOption(title, description) {
	this.title = title;
	this.description = description;
} //used for the text option
function oneOption(value) {
	this.value = value;
} //used for the text option
// refernced in unused function previewFields
function previewDropDown($this) {
	var fieldDesc = jQuery($this).find('.fieldDescription').val();
	var fieldName = jQuery($this).find('.fieldServiceName').val();
	var theHTML = (fieldName != '') ? "<div><label>" + fieldName + "</label>" : '<div>';
	theHTML += (fieldDesc != '') ? "<div>" + fieldDesc + "</div>" : '';
	theHTML += '<select>';
	jQuery($this).find('.selectoption_2').find('.selopt3').each(function() {
		theHTML += "<option value='" + jQuery(this).find('.inputoption_2').val() + "'>" + jQuery(this).find('.inputoption').val() + "</option>";
	});
	theHTML += '</select></div><br />';
	return theHTML;
}
// unused
function previewFields() {
	var previewhtml = '';
	jQuery('#allinputstoadd .addedFieldsStyle').each(function() {
		var geptionx = jQuery(this).find('.getfieldoptionx').val();
		if ('dropdowninput' == geptionx) {
			previewhtml += previewDropDown(this);
		} else if ('switchinput' == geptionx) {
			previewhtml += previewSwitch(this);
		} else if ('sliderinput' == geptionx) {
			previewhtml += previewSlider(this);
		}
	});
	jQuery('#previewInputsAdd').html("<hr /><br />" + previewhtml);
}
// unused
function fieldsToEdit(fields) {
	numberOfFields = fields;
}
// unused
function wait(ms) {
	var start = new Date().getTime();
	var end = start;
	while (end < start + ms) {
		end = new Date().getTime();
	}
}
// Handles the "New Section" button in the backend
function addAnotherField() {
	numberOfFields = jQuery('#allinputstoadd .addedFieldsStyle').length;
	demo = jQuery('#scc-demover').attr('data-demo');
  // Add 2 Sections for demo...
  if (demo == 0 && numberOfFields > 1) {
  	jQuery('#scc-demover').html('You cannot add more than 2 sections. Purchase the pro version <a href="https://stylishcostcalculator.com/">here</a>.').fadeIn();
  	jQuery('.hover_bkgr_fricc').show();
  	return;
  } else {
  	jQuery('#scc-demover').html('').fadeOut();
  }
  // jQuery('#scc-wp-footer').fadeOut();console.log(numberOfFields);
  // if (numberOfFields != 1)
  // {
  //      jQuery('.down:eq('+(numberOfFields-2)+')').css("display", "block");
  // }
  var theOpt = jQuery('#inputtoadd').html();
  jQuery('#allinputstoadd').append(theOpt);
  jQuery('#allinputstoadd').find('.title_section_no_edit').text('Section Name')
  jQuery('#allinputstoadd').find('.description_section_no_edit').text('Section description')
  resort_updown();
  jQuery('.scc_new_subsec').click();
  jQuery('.getfieldoptionx').click(function() {
  	var fieldOpt = jQuery(this).val();
  	secondStep(this, fieldOpt, 'ascend')
  });
  jQuery(this).addClass("omsairam");
}
// handles the "Add Subsection" button in the backend
function addAnotherElement($this) {
  //numberOfElements++;
  demo = jQuery('#scc-demover').attr('data-demo');
  var xnumberOfFields = jQuery('#allinputstoadd .boardOption').length;
  if(xnumberOfFields == 0){
  	jQuery('.speech-bubble').show();
  }
  // Add only 2 Subsection for demo
  if (demo == 0 && xnumberOfFields > 1) {
  	jQuery('#scc-demover').html('You cannot add more than 2 subsections as a free user. Purchase the pro version <a href="https://stylishcostcalculator.com/">here</a>!').fadeIn();
  	jQuery('.hover_bkgr_fricc').show();
  	return;
  } else {
  	var thh = jQuery($this).parent().parent().parent().parent().find('.fieldDatatoAdd');
  	var theOpt = jQuery('#fieldDatatoAdd').html();
  	var theOpt1 = jQuery('#fieldDatatoAdd11').html();
    // jQuery($this).parent().parent().parent().find('.boardOption1').html(theOpt1);
    // thh.append(theOpt);
    jQuery($this).parent().parent().parent().find('.boardOption1').remove();
    thh.append(theOpt1+ theOpt);
}
}
// helps mounting the section, subsection and elements in the backend
function addAnotherElement1($this) {
	var theOpt = jQuery('#fieldDatatoAdd').html();
	var theOpt1 = jQuery('#fieldDatatoAdd11').html();
	jQuery($this).find('.boardOption1').remove();
	jQuery($this).find('.fieldDatatoAdd').append(theOpt1+theOpt);
}
// unused
function addAnotherOption($this) {
	numberOfSections = jQuery('#allinputstoadd .BodyOption').length;
	demo = jQuery('#scc-demover').attr('data-demo');
  // Add only 5 items for demo.
  if (demo == 0 && numberOfSections > 3) {
  	jQuery('#scc-demover').html('You cannot add more than five elements. Purchase the pro version <a href="https://stylishcostcalculator.com/">here</a>.').fadeIn();
  	jQuery('.hover_bkgr_fricc').show();
  	return;
  } else {
  	var theOpt = jQuery('#form-line').html();
  	jQuery($this).parent().parent().find('.form-line').append(theOpt);
    // resort_updown();
    // jQuery('.getfieldoptionx').click(function()
    // {
    //     var fieldOpt = jQuery(this).val();
    //     secondStep(this, fieldOpt, 'ascend')
    // });
}
}
// unused - referenced in usused function previewFields
function previewSlider($this) {
	var theHTML = '<div>';
	var fieldServiceName = jQuery($this).find('.fieldServiceName').val();
	var fieldDescription = jQuery($this).find('.fieldDescription').val();
	var min = jQuery($this).find('.inputoption').val();
	var max = jQuery($this).find('.inputoption_2').val();
	var step = jQuery($this).find('.inputoption_3').val();
	var defaultValue = jQuery($this).find('.inputoption_4').val();
	theHTML += '<label>' + fieldServiceName + '</label>';
	theHTML += '<div class="slidecontainer"  style="clear: both;">';
	theHTML += '<input data-inputtype="slider" type="range" min="' + min + '" max="' + max + '" step="' + step + '" value="' + defaultValue + '" class="slider itemCreated">';
	theHTML += '</div></div><div style="clear: both;"></div><br /><br />';
	return theHTML;
}
// unused - referenced in unused function previewFields
function previewSwitch($this) {
	var fieldDesc = jQuery($this).find('.fieldDescription').val();
	var fieldName = jQuery($this).find('.fieldServiceName').val();
	var price = jQuery($this).find('.inputoption').val();
	var theHTML = (fieldName != '') ? "<div><label>" + fieldName + "</label>" : '<div>';
	theHTML += '<label class="scc-switch">';
	theHTML += '<input type="checkbox" data-toggle="toggle" checked datainputprice="' + price + '" data-inputtype="switch" class="itemCreated">';
	theHTML += '<span class="slider_switch round"></span>';
	theHTML += '</label><div style="clear: both;"></div><br /><br />';
	return theHTML;
}
// Handles close button at the section level
function removeField($f) {
	numberOfFields--;
	jQuery($f).parent().parent().remove();
	resort_updown();
}
// Handles close button at the sub-section level
function removeField1($f) {
	numberOfElements--;
	jQuery($f).parent().parent().remove();
	resort_updown();
}
// unused
function removeField3($f) {
	numberOfElements--;
	jQuery($f).parent().remove();
	resort_updown();
}
// Handles the close button at the left side of the element name
function removeField2($f) {
	numberOfSections--;
 // jQuery($f).parent().remove();
 jQuery($f).parent().remove()
 /*
 jQuery($f).addClass("scc_crr_sbsctn");
 jQuery($f).next().next().addClass('scc_crr_clps');
//   jQuery($f).parent().remove()
 jQuery($f).next().remove();
 jQuery($f).next().next().remove();
 jQuery('.scc_crr_clps').remove();
 jQuery('.scc_crr_sbsctn').remove();
  jQuery('.elements_added').each(function(i, obj){
      if(jQuery(obj).children()){
        if(jQuery(obj).children().length === 1 ){
          jQuery(obj).remove()
        }
      }
  })
  */
  resort_updown();
}
// collapses the elements in the background
function colla($this) {
	var siggn = jQuery($this).text() == "-" ? "+" : "-";
	jQuery($this).text(siggn);
	jQuery($this).parent().find('.content').slideToggle({duration: 200, done: ({elem}) => {
		var targetElement = jQuery(elem);
		if (targetElement.is(':hidden')) {
			targetElement.closest('.elements_added').css({border: 'unset'});
		}
		if (targetElement.is(':visible')) {
			targetElement.closest('.elements_added').css({border: '2px solid #8a99f8'});
		}
	}});
	jQuery($this).parent().find('.selopt5').slideToggle({duration: 200, done: ({elem}) => {
		var targetElement = jQuery(elem);
		if (targetElement.is(':hidden')) {
			targetElement.parent('.elements_added').css({border: 'unset'});
		}
		if (targetElement.is(':visible')) {
			targetElement.parent('.elements_added').css({border: '2px solid #8a99f8'});
		}
	}});
	if(jQuery($this).data('collapseSectionType') == 'custom_math') {
		jQuery($this).closest('.content.scc_custom_math').find('.custom-math-section-container').slideToggle({duration: 200, done: ({elem}) => {
			var targetElement = jQuery(elem);
			var toolTipElement = targetElement.find('i.material-icons.with-tooltip');
		  		// set the padding tag to padding 0 if hidden
				// targetElement.is(':hidden') ? targetElement.prev().css({paddingBottom: '0'}) : targetElement.prev().css({paddingBottom: '20px'});
				if (targetElement.is(':hidden')) {
					targetElement.prev().css({paddingBottom: '0', border: 'unset'});
					if(toolTipElement.data('ui-tooltip')) {
						toolTipElement.tooltip('destroy');
					}
				}
				if (targetElement.is(':visible')) {
					targetElement.prev().css({paddingBottom: '20px', border: '2px solid #8a99f8', borderBottomStyle: 'hidden'});
					targetElement.css({border: '2px solid #8a99f8', borderTopStyle: 'hidden'});
					// register tooltip
					targetElement.find('i.material-icons.with-tooltip').tooltip({
						position: {
							my: "right bottom",
							at: "right top"
						}
					});
				}
			}
		});
	}
	if(jQuery($this).data('collapseSectionType') == 'slider_element') {
		jQuery($this).closest('.selslideropt_4').find('.slider-section-container').slideToggle({duration: 200, done: ({elem}) => {
			var targetElement = jQuery(elem);
			var toolTipElement = jQuery(elem).find('i.material-icons.with-tooltip');
		  		// set the padding tag to padding 0 if hidden
		  		if (targetElement.is(':hidden')) {
		  			targetElement.prev().css({paddingBottom: '0', border: 'unset'});
		  			if(toolTipElement.data('ui-tooltip')) {
		  				toolTipElement.tooltip('destroy');
		  			}
		  		}
		  		if (targetElement.is(':visible')) {
		  			targetElement.prev().css({paddingBottom: '20px'});
		  			targetElement.css({border: '2px solid #8a99f8', borderTopStyle: 'hidden'});
		  			targetElement.prev().css({border: '2px solid #8a99f8', borderBottomStyle: 'hidden'});
					// register tooltip
					targetElement.find('i.material-icons.with-tooltip').tooltip({
						position: {
							my: "right bottom",
							at: "right top"
						}
					});
				}
			}
		});
	}
}
// Currently unused
function resetFields() {
	jQuery('#allinputstoadd').html('');
	jQuery('#previewInputsAdd').html('');
}
var demo_calculators_instance_limit = 2
// saves the calculator
function saveFields(isLicensed, demo_calculators_already_done, isEditing, wooCommerceActivated) {
  if(isEditing || !isEditing && (isLicensed || demo_calculators_already_done < demo_calculators_instance_limit)){ // for licensed users and demo users with free calculators yet
  	if(!isEditing && !isLicensed ){
  		alert("Attention: You need to activate you license, first. \r\n\r\nTo get your License code, please visit https://members.stylishcostcalculator.com/forgot-password/. Use the same e-mail  which you purchased the license key, and then click 'Forgot Password' to obtain your credentials. The members area will have your license, invoices and download links.")
  		return ;
  	}
  	var wooCommerceElementsError = []
  	var fieldName = jQuery('#costcalculatorname').val();
  	if (fieldName.trim() == '')
  	{
  		jQuery('#themainwarning').html('Calculator must have a name');
  		return;
  	} else { jQuery('#themainwarning').html(''); }
  	var fontType = jQuery("#scc_fonttype").val().trim();
  	var fontTypeVariant = jQuery("#scc_fonttype_variant").val()?.trim() || 'regular';
  	var inheritFontType = jQuery('#inherit-fontfamily').prop('checked') ? 'true' : 'false';
  	var colorPicker = jQuery("#colorPicker").val();
  	var servicepricefontsize = jQuery('#servicepricefontsize').val();
  	var title_fontType = jQuery("#titlescc_fonttype").val().trim();
  	var title_fontType_variant = jQuery("#titlescc_fonttype_variant").val()?.trim() || 'regular';
  	var title_colorPicker = jQuery("#titlecolorPicker").val();
  	var title_servicepricefontsize = jQuery('#titlepricefontsize').val();
        //var fontType = jQuery("#scc_fonttype").val();
        var objectColorPicker = jQuery("#objectcolorPicker").val();
        var objectServicepricefontsize = jQuery('#objectservicepricefontsize').val();
        var adminsettingsid = jQuery('#adminsettingsid').attr('data-calculator_id');
        // var costcalculatordescription = jQuery('#costcalculatordescription').val();
        var objectsendquote = jQuery("#scc_send_quote:checked").val();
        var objectdetailedlist = jQuery("#scc_detailed_list:checked").val();
        var objectsaveicon = jQuery("#scc_save_icon:checked").val();
        var objectDisableUnitCol = jQuery("#scc_no_unit_col:checked").val();
        var objectscctax = jQuery("#turn_off_tax:checked").val();
        var toggle_boxshadow_style2 = jQuery("#toggle_boxshadow_style2:checked").val();
        var objectscccoupon = jQuery("#turn_off_coupon:checked") && jQuery("#turn_off_coupon:checked").val() ? jQuery("#turn_off_coupon:checked").val() : '';
        var objecttaxrate = jQuery("#scc_tax_amount").val();
		var showTaxBeforeTotal = jQuery('#scc_show_taxvat').prop('checked') ? 'true' : 'false';
        var userActionBtnStyle = jQuery(".form-control.scc_btn_style").val();
        var objectscccurrencylabel = jQuery("#scc_remove_currency_label:checked").val();
        var objectscctitlelabel = jQuery("#scc_remove_detailed_list_title:checked").val();
        var objectscctotalprice = jQuery("#scc_remove_total_price_frntd:checked").val();
        var objecttotalpricestyle = jQuery(".scc_total_price_style_view").val();
        var currency_style = jQuery(".scc_currency_style").val()
        var form_field_style = jQuery('select[name="form_field_style"]').val();
        var scc_cart_btn_action = jQuery('select[name="scc_wc_cart_btn_action"]').val();
        var objecttotalword = jQuery("#scc_change_total_word").val();
        var objectdetailedlistword = jQuery("#scc_change_detailed_list_word").val();
        var objectsendquoteword = jQuery("#scc_change_send_quote_word").val();
        var objectscctotalpricefloat = jQuery("#turn_on_total_price_float:checked").val();
        var fieldstosend = [['name', 'description']];
		var sccMinimumTotal = jQuery("#scc_minimum-total").val();
		var sccMinimumTotalAction = jQuery('#scc_minimum_total_placeholder').val();
        var a = 0;
        var switchError = false;
        var buttonError = false;
        var sliderError = false;
        var asliderError = false;
        var dropdownError = false;
        var textInputError = false;
        var section = 0;
        var a = 0;
        var SectionName = [];
        var elementOption = 0;
        var paypal_checked = false;
        var paypal_email = '';
        var paypal_shopping_cart_name = '';
        var paypal_currency = '';
        var isStripeEnabled = false;
        var forceEmailQuote = false;
        var isPayBtnHoverEffectEnabled = true;
        var userActionButtonStyle = Number(jQuery('select[name="scc_user_action_btn_style"]').val()) ? Number(jQuery('select[name="scc_user_action_btn_style"]').val()) : 1;
        var paypalSuccessURL = '';
        var paypalCancelURL = '';
        var objectTaxInclusionInPayPal = false;
        if(jQuery('.editing-action-cards.action-payment .card-action-btns.has-checkmark [data-btn-type="paypal"]').hasClass('active')){
        	paypal_checked = paypalConfig.paypal_checked;
        	paypal_email = paypalConfig.paypal_email;
        	paypal_shopping_cart_name = paypalConfig.paypal_shopping_cart_name;
        	paypal_currency = paypalConfig.paypal_currency;
        	paypalSuccessURL = paypalConfig.paypalSuccessURL;
        	objectTaxInclusionInPayPal = paypalConfig.objectTaxInclusionInPayPal;
        	paypalCancelURL = paypalConfig.paypalCancelURL;
        }
        if(jQuery('#stripe_checkbox').prop('checked')) {
			// isStripeEnabled = 'true'
		}
		if(jQuery('.editing-action-cards.action-payment [data-btn-type="stripe"]').hasClass('active')) {
			isStripeEnabled = 'true'
		}
		if (jQuery('#force-email-quote').prop('checked')) {
			forceEmailQuote = true;
		}
		if(jQuery('#paybuttonhovereffect').prop('checked')) {
			isPayBtnHoverEffectEnabled = false
		}
		// start of webhook settings object construction
		let webhookSettings = jQuery('#calc-settings-webhook input').map((i,e) => {
			let element = jQuery(e);
			let elementTarget = jQuery(e).data('target');
			let isCheckboxChecked = element.prop('checked');
			let webHookLink = jQuery(`[data-event-type=${elementTarget}]`).data('webhook') || '';
			return {[jQuery(e).attr('id')] : {
				enabled: isCheckboxChecked,
				webhook: webHookLink
			}};
		}).get();

		// end of webhook settings object construction
/*
        START Saving WooCommerce
        */
        var woocommerce_checked = false
        if(jQuery('#woocommerce_checked') && jQuery('#woocommerce_checked').prop('checked')) {
            // woocommerce_checked = jQuery('#woocommerce_checked').prop('checked')
        }
        if(jQuery('.editing-action-cards.action-payment [data-btn-type="woocommerce"]').hasClass('active')) {
        	woocommerce_checked = true;
        }
/*
        END Saving WooCommerce
        */
        var emptyValuesError = false
        jQuery('#allinputstoadd .addedFieldsStyle').each(function() {
        	var sliderChecked = 0;
        	var elementOption = jQuery(this).find('.boardOption').length;
        	if (elementOption != 0) {
        		var elementNo = 0;
        		var allfieldOptions2 = [];
        		jQuery(this).find('.boardOption').each(function(){
        			var allfieldOptions = [];
        			var is = 0;
        			jQuery(this).find('.BodyOption').each(function() {
        				jQuery(this).find('.content').each(function() {
        					var fieldType = jQuery(this).attr('value');
        					var count = 0;
        					var allfieldOptions1 = [];
        					switch (fieldType) {
        						case "buttonoption":
        						var fieldButtonServiceName = jQuery(this).find('.inputbuttonservice_title').val();
        						var s_length = jQuery(this).find('.buttonoption_3').length;
        						jQuery(this).find('.buttonoption_3').each(function() {
        							buttonError = validateSwitch(jQuery(this).parent().parent(), jQuery(this).find('.buttoninputoption').val(), jQuery(this).find('.buttoninputoption_2').val());
        							if (buttonError === true) {
        								return;
        							}
        							allfieldOptions1[count] = new ElementArray(count, fieldButtonServiceName, jQuery(this).find('.buttoninputoption').val(), jQuery(this).find('.buttoninputoption_2').val(), 0, jQuery(this).find('.scc_woo_commerce_product_id') ? jQuery(this).find('.scc_woo_commerce_product_id').val() : '');
        							count++;
        						});
        						allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length, null, generateUID(this));
        						is++;
        						break;
        						case "switchoption":
        						var s_length = jQuery(this).find('.switchoption_3').length;
        						var s_type = jQuery(this).find('.fieldFormat').val();
        						var isMandatory = jQuery(this).find('[name="chkbx-mandatory"]').prop('checked') || false;
        						jQuery(this).find('.switchoption_3').each(function() {
        							switchError = validateSwitch(jQuery(this).parent().parent(), jQuery(this).find('.switchinputoption').val(), jQuery(this).find('.switchinputoption_2').val());
        							if (switchError === true) {
        								emptyValuesError = switchError
        								return;
        							}
        							if(jQuery(this).parent().parent().find('.styled-accordion:eq(0) .scc_title_column_dskp_chkbx').val() != ''){
        								var scc_title_column_dskp_chkbx = jQuery(this).parent().parent().find('.styled-accordion:eq(0) .scc_title_column_dskp_chkbx').val();
        							}
        							if(jQuery(this).parent().parent().find('.styled-accordion:eq(0) .scc_title_column_mobl_chkbx').val() != ''){
        								var scc_title_column_mobl_chkbx = jQuery(this).parent().parent().find('.styled-accordion:eq(0) .scc_title_column_mobl_chkbx').val();
        							}
        							var scc_woo_commerce_product_id_switchoption = 0;
        							if(jQuery(this).find('.scc_woo_commerce_product_id').val() != '' && jQuery(this).find('.scc_woo_commerce_product_id').val() != null){
        								scc_woo_commerce_product_id_switchoption = jQuery(this).find('.scc_woo_commerce_product_id').val()
        							}
        							if(scc_woo_commerce_product_id_switchoption == 0) {
                     /*
                      wooCommerceElementsError.push({
                            name: jQuery(this).find('.switchinputoption').val(),
                            type: 'Checkbox / Toggle / Simple Button'
                          })
                          */
                      }
                      var isPriceHintEnabled = jQuery(this).parent().parent().find('input[name="chkbx-showhint"]').prop('checked');
                      allfieldOptions1[count] = new ElementArray(count, 0, jQuery(this).find('.switchinputoption').val(), jQuery(this).find('.switchinputoption_2').val(), s_type,'',scc_title_column_dskp_chkbx, scc_title_column_mobl_chkbx, scc_woo_commerce_product_id_switchoption, jQuery(this).find('.col-xs-2.col-md-2.tooltipadmin-left[data-selected="true"]').length ? true : false, isPriceHintEnabled, null, null, generateUID(this));
                      count++;
                  });
        						allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length, null, generateUID(this), isMandatory);
        						is++;
        						break;
        						case "selectoption":
              var fieldDropServiceName = jQuery(this).find('.inputoption_title').val(); //inputoption_title
              if(jQuery(this).find('.styled-accordion:eq(0) .scc_mandatory_dropdown').prop('checked')){
                var dropdownServiceMandatory = 'yes'; //mandatory dropdown
            }else{
                var dropdownServiceMandatory = 'no'; //mandatory dropdown
            }
            if(jQuery(this).find('.selopt3').parent().parent().find('.scc_title_column_dskp').val() != ''){
            	var scc_title_column_dskp = jQuery(this).find('.selopt3').parent().parent().find('.scc_title_column_dskp').val();
            }
            if(jQuery(this).find('.selopt3').parent().parent().find('.scc_title_column_mobl').val() != ''){
            	var scc_title_column_mobl = jQuery(this).find('.selopt3').parent().parent().find('.scc_title_column_mobl').val();
            }
            var s_length = jQuery(this).find('.selopt3').length;
            var conditionInputID = function($this) {
            	stageAElem = jQuery($this).find('.conditional-selection-steps .condition-stage-a');
            	stageA  = stageAElem.val() && stageAElem.val() !=="unset" ? stageAElem.val() : null;
                // stageB = jQuery($this).find('.conditional-selection-steps .condition-stage-b').val() ? jQuery($this).find('.conditional-selection-steps .condition-stage-b').val() : null;
                // final = stageA && stageB ? {id: stageA + '_' + stageB.split(',').slice(0, 2).join('_'), optVal: stageB.split(',')[2]} : null;
                if(!stageA) {
                	return;
                }
                final = {id: stageA.split(',').slice(0, 3).join('_'), optVal: stageA.split(',')[3]}
                return final;
            }
              var $thisDropDown = this; //inside the each loop, this will have a different value
              jQuery(this).find('.selopt3').each(function() {
              	dropdownError = validateDropDown(fieldDropServiceName, $thisDropDown, jQuery(this).find('.inputoption').val(), jQuery(this).find('.inputoption_2').val(),dropdownServiceMandatory);
              	if (dropdownError === true) {
              		emptyValuesError = dropdownError
              		return;
              	}
				let dropdownIcon = jQuery(this).find('.scc-image-picker').data('hasImage') ? encodeURIComponent(jQuery(this).find('.scc-image-picker').attr('src')) : false;
              	if(!jQuery(this).find('.scc_woo_commerce_product_id') || jQuery(this).find('.scc_woo_commerce_product_id').val() == 0 ||  jQuery(this).find('.scc_woo_commerce_product_id').val() == null) {
                  /*
                  wooCommerceElementsError.push({
                        name: fieldDropServiceName + ' | Option: '+ jQuery(this).find('.inputoption').val(),
                        type: 'Dropdown'
                      })
                      */
                  }
                  allfieldOptions1[count] = new ElementArray(count, fieldDropServiceName, jQuery(this).find('.inputoption').val(), jQuery(this).find('.inputoption_2').val(), jQuery(this).find('.inputoption_desc').val(),dropdownServiceMandatory,scc_title_column_dskp,scc_title_column_mobl, jQuery(this).find('.scc_woo_commerce_product_id') ? jQuery(this).find('.scc_woo_commerce_product_id').val() : '', jQuery(this).find('.col-xs-2.col-md-2.tooltipadmin-left[data-selected="true"]').length ? true : false, false, false, false, false, dropdownIcon);
                  count++;
              });
              allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length, conditionInputID(this), generateUID(this));
              is++;
              break;
              case "comment_option":
              var fieldCommentName = jQuery(this).find('.inputoption_title').val(); //inputoption_title
              if(jQuery(this).find('.scc_mandatory_comment').prop('checked')){
              var commentMandatory = 'yes'; //mandatory dropdown
          }else{
              var commentMandatory = 'no'; //mandatory dropdown
          }
          var s_length = jQuery(this).find('.selopt5').length;
              var $thisDropDown = this; //inside the each loop, this will have a different value
              var commentError = validateComment(fieldCommentName, $thisDropDown);
              if (commentError === true) {
              	emptyValuesError = commentError
              	return;
              }
              jQuery(this).find('.selopt5').each(function() {
              	if(jQuery(this).parent().find('.styled-accordion:eq(0) .scc_title_column_dskp_cmntbx').val() != ''){
              		var scc_title_column_dskp_cmntbx = jQuery(this).parent().find('.styled-accordion:eq(0) .scc_title_column_dskp_cmntbx').val();
              	}
              	if(jQuery(this).parent().find('.styled-accordion:eq(0) .scc_title_column_mobl_cmntbx').val() != ''){
              		var scc_title_column_mobl_cmntbx = jQuery(this).parent().find('.styled-accordion:eq(0) .scc_title_column_mobl_cmntbx').val();
              	}
              	allfieldOptions1[count] = new ElementArray(count, fieldCommentName, jQuery(this).find('.inputoption').val(), jQuery(this).find('.inputoption_2').val(), jQuery(this).find('.inputoption_desc').val(),commentMandatory,scc_title_column_dskp_cmntbx, scc_title_column_mobl_cmntbx,  jQuery(this).find('.scc_woo_commerce_product_id') ? jQuery(this).find('.scc_woo_commerce_product_id').val() : '');
              	count++;
              });
              allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length, null, generateUID(this));
              is++;
              break;
              case "number_option":
                  var fieldNumberName = jQuery(this).find('.inputoption_title').val(); //inputoption_title
                  if(jQuery(this).find('.scc_mandatory_number').prop('checked')){
                    var numberMandatory = 'yes'; //mandatory dropdown
                }else{
                    var numberMandatory = 'no'; //mandatory dropdown
                }
                var s_length = jQuery(this).find('.selopt3').length;
                  var $thisDropDown = this; //inside the each loop, this will have a different value
                  commentError = validateQuantityBox(fieldNumberName, $thisDropDown, jQuery(this).find('.inputoption_2').val());
                  if (commentError === true) {
                  	emptyValuesError = commentError
                  	return;
                  }
                  jQuery(this).find('.selopt3').each(function() {
                  	var getInputBoxVariant = jQuery(this).closest('.scc_number_box').find('[name="quantity-input--style-selection"]').val() || 'default';
                  	if(jQuery(this).parent().parent().find('.styled-accordion:eq(0) .scc_title_column_dskp_numbx').val() != ''){
                  		var scc_title_column_dskp_numbx = jQuery(this).parent().parent().find('.styled-accordion:eq(0) .scc_title_column_dskp_numbx').val();
                  	}
                  	if(jQuery(this).parent().parent().find('.styled-accordion:eq(0) .scc_title_column_mobl_numbx').val() != ''){
                  		var scc_title_column_mobl_numbx = jQuery(this).parent().parent().find('.styled-accordion:eq(0) .scc_title_column_mobl_numbx').val();
                  	}
                  	var scc_woo_commerce_product_id_number_box = 0;
                  	if(jQuery(this).parent().find('.scc_woo_commerce_product_id').val() != '' && jQuery(this).parent().find('.scc_woo_commerce_product_id').val() != null){
                  		scc_woo_commerce_product_id_number_box = jQuery(this).parent().find('.scc_woo_commerce_product_id').val()
                  	}
                  	if(jQuery(this).parent().parent().find('.styled-accordion:eq(0) .scc_title_column_mobl_numbx').val() != ''){
                  	}
                  	if(scc_woo_commerce_product_id_number_box == 0 ) {
                        /*
                        wooCommerceElementsError.push({
                                name: fieldNumberName,
                                type: 'Number Box'
                              })
                              */
                          }
                          allfieldOptions1[count] = new ElementArray(count, fieldNumberName, jQuery(this).find('.inputoption').val(), jQuery(this).find('.inputoption_2').val(), jQuery(this).find('.inputoption_desc').val(),numberMandatory,scc_title_column_dskp_numbx,scc_title_column_mobl_numbx, scc_woo_commerce_product_id_number_box, null, null, null, getInputBoxVariant);
                          count++;
                      });
                  allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length, null, generateUID(this));
                  is++;
                  break;
                  case "fileupload_option":
                  // allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length, null, generateUID(this));
                  console.log('hit fileupload opt', this);
                  var fieldTitle = jQuery(this).find('.inputoption_title').val();
                  var fileUploadMandatory = jQuery(this).find('.scc_mandatory_fileupload').prop('checked') ? 'yes' : 'no';
                  var fileSizeInput = parseFloat(jQuery(this).find('input[type="number"]').val());
                  var fileMaxSize = (fileSizeInput > 0 ? fileSizeInput : 100);
                  var fileUploadPlaceholderText = jQuery(this).find('input.inputoption_placeholder[type="text"]').val() || 'Please choose a file';
                  var fileUploadAllowedTypes = jQuery(this).find('input.inputoption_filetypes[type="text"]').val() || 'any';
                  // var fileMandatory = 'no';
                  var scc_title_column_dskp_fupl;
                  var scc_title_column_mobl_fupl;
                  if (jQuery(this).find('.scc_title_column_dskp_fupl').val() != '') {
                  	scc_title_column_dskp_fupl = jQuery(this).find('.scc_title_column_dskp_fupl').val();
                  }
                  if (jQuery(this).find('.scc_title_column_mobl_fupl').val() != '') {
                  	scc_title_column_mobl_fupl = jQuery(this).find('.scc_title_column_mobl_fupl').val();
                  }
                  var scc_woo_commerce_product_id_number_box;
                  var s_length = jQuery(this).find('.selopt3').length;
                  allfieldOptions1[0] = new ElementArray(count, fieldTitle, null, fileMaxSize, [{fileUploadPlaceholderText, fileUploadAllowedTypes}],fileUploadMandatory,scc_title_column_dskp_fupl,scc_title_column_mobl_fupl, scc_woo_commerce_product_id_number_box, null, null, null, null);
                  allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length, null, generateUID(this));
                  is++;
                  // scc_mandatory_fileipload
                  break;
				  case "custom_code":
					  // handle inputs
					  var fieldTitle = jQuery(this).find('.inputoption_title').val();
					  var fieldCodeText = jQuery(this).find('.inputoption_text').val();
					  var column_desktop = jQuery(this).find('.scc_title_column_dskp_custom_code').val();
					  var column_mobile = jQuery(this).find('.scc_title_column_mobl_custom_code').val();
					  allfieldOptions1[0] = new ElementArray(count, fieldTitle, fieldCodeText, null, null, null, column_desktop, column_mobile, null, null, null, null, null, generateUID(this), null);
					  allfieldOptions[is] = new InputOptions(is, fieldType, allfieldOptions1, 1, null, generateUID(this) );
				    is++
				  break;
                  default:
              }
          });
});
if(jQuery(this).find('.scc_custom_math_checkbox').is(':checked') && jQuery(this).find('.scc_custom_math').is(':visible')) {
            //No, title, name, value1, value2,mandatory,column_dskp,column_mobl, scc_woo_commerce_product_id, opt_default) {
            	var allfieldOptionsCustomMath=[];
            	var scc_custom_math_display_front_end = false;
            	if(jQuery(this).find('.scc_custom_math_display_front_end').is(':checked')){
            		scc_custom_math_display_front_end = true;
            	}
            	var scc_custom_math_display_detailed_list = false
            	if(jQuery(this).find('.scc_custom_math_display_detailed_list').is(':checked')){
            		scc_custom_math_display_detailed_list = true
            	}
            	var custom_math_name = jQuery(this).find('.scc_custom_math_name').val()
            	var custom_math_type = jQuery(this).find('.scc_custom_math_type option:selected:last').val()
            	var custom_math_value = jQuery(this).find('.scc_custom_math_value').val()
              var $thisDropDown = this; //inside the each loop, this will have a different value
              customMathError = validateCustomMath(custom_math_name, $thisDropDown, custom_math_value);
              if (customMathError === true) {
              	emptyValuesError = customMathError
              	return;
              }
              allfieldOptionsCustomMath.push(new ElementArray(0, custom_math_name, custom_math_type, 0, custom_math_value,"",scc_custom_math_display_front_end,scc_custom_math_display_detailed_list, ""))
            //count++;
            allfieldOptions[is] = new InputOptions (is,"'scc_custom_math'",allfieldOptionsCustomMath,1, null, generateUID(jQuery(this).find('.content.scc_custom_math')));
            is++;
        }
        if (jQuery(this).find('.inputoption_slidchk').is(':checked')) {
        	sliderChecked = 1; var allfieldOptions3=[];
        	var fieldServiceName = jQuery(this).find('.sliderinputoption_T').val();
        	var s_length = jQuery(this).find('.price_table tbody tr').length;
        	var ktable=0;
        	sliderError = validateSlider(this, fieldServiceName)
        	if(sliderError === true) {
        		emptyValuesError = sliderError
        		return
        	}
        	if(jQuery(this).find('.scc_title_column_dskp_slider').val() != ''){
        		var scc_title_column_dskp_slider = jQuery(this).find('.scc_title_column_dskp_slider').val();
        	}
        	if(jQuery(this).find('.scc_title_column_mobl_slider').val() != ''){
        		var scc_title_column_mobl_slider = jQuery(this).find('.scc_title_column_mobl_slider').val();
        	}
        	var scc_woo_commerce_product_id_slider = 0;
        	if (jQuery(this).find('.scc_woo_commerce_product_id option:selected:last').val() != ''){
        		var scc_woo_commerce_product_id_slider = jQuery(this).find('.scc_woo_commerce_product_id option:selected:last').val()
        	}
        	if(scc_woo_commerce_product_id_slider == 0) {
        		wooCommerceElementsError.push({
        			name: fieldServiceName,
        			type: 'Slider'
        		})
        	}
        	jQuery(this).find('.price_table tbody tr').each(function() {
        		allfieldOptions3[ktable] = new ElementArray(ktable, fieldServiceName, jQuery(this).find('.sliderinputoption').val(), jQuery(this).find('.sliderinputoption_2').val(), jQuery(this).find('.sliderinputoption_5').val(),'',scc_title_column_dskp_slider,scc_title_column_mobl_slider,  scc_woo_commerce_product_id_slider);
        		ktable++;
        	});
                      // allfieldOptions3[ktable] = new ElementArray(ktable, fieldServiceName, jQuery(this).find('.sliderinputoption').val(), jQuery(this).find('.sliderinputoption_2').val(), jQuery(this).find('.sliderinputoption_5').val(),'',scc_title_column_dskp_slider,scc_title_column_mobl_slider,  scc_woo_commerce_product_id_slider);
                      var step = jQuery(this).find('.slidoption_3').val();
                      var defaultValue = jQuery(this).find('.slidoption_4').val();
					  var isSliderMandatory = jQuery(this).find('[name="slider-mandatory"]').prop('checked');
                      var showPriceHint = jQuery(this).find('.slidoption_5').prop('checked');
                      var isSlidingScale = jQuery(this).find('.slider-discount-type').val() == 'sliding-scale';
                      var uniqueID = jQuery(this).find('.selslideropt_4.content').data('uniqueId');
                      allfieldOptions2[elementNo] = new SubOptions(elementNo,allfieldOptions, allfieldOptions3, step, defaultValue, showPriceHint, isSlidingScale, uniqueID, isSliderMandatory);
                  }
                  else {
                  	sliderChecked = 0;
                  	allfieldOptions3 = [];
                  	allfieldOptions2[elementNo] = new SubOptions(elementNo, allfieldOptions, allfieldOptions3, 0, 0, 0);
                  }
                  elementNo++;
              });
}
else {
	var allfieldOptions2 = [];
}
          /* OLD SectionOptions without Title Column and WITH accordion, OLD Save
            SectionName[a] = new sliderOptions(jQuery(this).find('.sectiontitle').val(), jQuery(this).find('.sectionDescription').val().replace(/(\r\n|\n|\r)/gm,'<br />') + (jQuery(this).find('.scc_accordion_section').prop("checked") ? '///accordion:yes///' : ''),a,allfieldOptions2);
            */
         // new SectionOptions
         var title_column_desktop = jQuery(this).find('.title_column_desktop') && jQuery(this).find('.title_column_desktop').val() ? jQuery(this).find('.title_column_desktop').val() : 4
         var title_column_mobile = jQuery(this).find('.title_column_mobile') && jQuery(this).find('.title_column_mobile').val() ? jQuery(this).find('.title_column_mobile').val() : 10
         var showSectionTotal = jQuery(this).find('input[name="scc-section-total"]').prop('checked') || false;
         SectionName[a] = new sectionOptions( jQuery(this).find('.sectiontitle').val(), jQuery(this).find('.sectionDescription').val().replace(/(\r\n|\n|\r)/gm,'<br />'),jQuery(this).find('.scc_accordion_section:eq(0)').prop("checked"), title_column_desktop, title_column_mobile, a,allfieldOptions2, showSectionTotal);
         a++;
     });
var dict = tableToJson(jQuery('#allinputstoadd').find('.translate_table tbody'));
if(!switchError || !dropdownError || !buttonError){
	if(wooCommerceActivated == true && jQuery('#woocommerce_checked') && jQuery('#woocommerce_checked').prop('checked')) {
		var allElementsLinkedToWooCommerceProducts = wooCommerceElementsError
		if(allElementsLinkedToWooCommerceProducts.length > 0) {
			var text = "Warning, the following elements are not correctly linked with your WooCommerce Products:";
			for (var i = 0; i < allElementsLinkedToWooCommerceProducts.length; i ++ ) {
				text += `
				\n Element: ` + allElementsLinkedToWooCommerceProducts[i].type + ` | name: ` + allElementsLinkedToWooCommerceProducts[i].name + `
				`;
			}
			text += " \n Save anyway?"
			if(confirm(text)) {
			}else {
				return false;
			}
		}
	}
	console.log(SectionName);
	var data = {
		action: 'sccSaveField',
		objectColorPicker: objectColorPicker,
		objectServicepricefontsize: objectServicepricefontsize,
		title_fontType: title_fontType,
		title_fontType_variant: title_fontType_variant,
		title_colorPicker: title_colorPicker,
		title_servicepricefontsize: title_servicepricefontsize,
		inheritFontType: inheritFontType,
		objectsendquote: objectsendquote,
		objectdetailedlist: objectdetailedlist,
		objectsaveicon: objectsaveicon,
		objectDisableUnitCol: objectDisableUnitCol,
		objectscctax: objectscctax,
		objecttaxrate: objecttaxrate,
		showTaxBeforeTotal: showTaxBeforeTotal,
		userActionBtnStyle: userActionBtnStyle,
		objectscccoupon: objectscccoupon,
		objectscccurrencylabel: objectscccurrencylabel,
		objectscctitlelabel: objectscctitlelabel,
		objectscctotalprice: objectscctotalprice,
		objecttotalpricestyle: objecttotalpricestyle,
		objecttotalword: objecttotalword,
		objectdetailedlistword: objectdetailedlistword,
		objectsendquoteword: objectsendquoteword,
		objectscctotalpricefloat: objectscctotalpricefloat,
		toggle_boxshadow_style2: toggle_boxshadow_style2,
		paypal_checked: paypal_checked,
		paypal_email: paypal_email,
		objectTaxInclusionInPayPal: objectTaxInclusionInPayPal,
		paypal_shopping_cart_name: paypal_shopping_cart_name,
		paypal_currency: paypal_currency,
		paypalSuccessURL: paypalSuccessURL,
		paypalCancelURL: paypalCancelURL,
		woocommerce_checked: woocommerce_checked,
		isStripeEnabled: isStripeEnabled,
		forceEmailQuote: forceEmailQuote,
		isPayBtnHoverEffectEnabled: isPayBtnHoverEffectEnabled,
		userActionButtonStyle: userActionButtonStyle,
		currency_style: currency_style,
		fontType: fontType.toString(),
		fontTypeVariant: fontTypeVariant,
		colorPicker: colorPicker,
		servicepricefontsize: servicepricefontsize,
		adminsettingsid: adminsettingsid,
		fieldname: fieldName,
		sccMinimumTotal: sccMinimumTotal,
		sccMinimumTotalAction: sccMinimumTotalAction,
		fieldPreview: JSON.stringify(SectionName),
		conditionObject: JSON.stringify(conditionObject),
            // fieldform: Base64.encode(JSON.stringify(jQuery('#allinputstoadd').html().trim())),
            // fieldform: "",
            dictionary: JSON.stringify(dict),
            formFieldsArray: JSON.stringify(formFieldsArray.flat()),
			webhookSettings: JSON.stringify(webhookSettings),
            form_field_style: form_field_style,
            scc_cart_btn_action: scc_cart_btn_action
        };
        var $fragment_refresh = {
        	url: rt_vars.rt_urlajax,
        	type: 'POST',
        	data: data,
       //     contentType: "charset=UTF-8",
       success: function( data ) {
       	location.href = rt_vars.rt_adminurl + '?page=edit_sccbyid&id=' + data.trim();
       }
   };
       //   console.log(JSON.stringify(SectionName))
       if(!emptyValuesError){
       	document.getElementById("scc-editing-area-loading") ? document.getElementById("scc-editing-area-loading").style.width = "100%" : null;
       	jQuery.ajax( $fragment_refresh );
       }
   }
}else{
	if(!isLicensed && !isEditing && demo_calculators_already_done >= demo_calculators_instance_limit){
		alert('You have created ' + demo_calculators_already_done + ' free calculators. You can create '
			+ (demo_calculators_instance_limit - demo_calculators_already_done) + ' more as a Demo user. Please, become a licensed user to create unlimited calculators.')
	}
}
}
function onChangeFieldStyle(element) {
	if(jQuery(element).children("option:selected"). val() == 'style_1') {
		jQuery('#toggle_boxshadow_style2').css('display','none')
	}else {
		jQuery('#toggle_boxshadow_style2').css('display','block')
	}
}
function checkIfParentIsAccordionAndOpenIt(element) {
	if( jQuery(element).parent().parent().css('display') === 'none') {
		var section_id_raw = jQuery(element).attr('id')
		if(section_id_raw && typeof section_id_raw == 'string' && section_id_raw.split('_').length > 1) {
			try {
				var section_id = section_id_raw.split('_')[1]
				jQuery('#section_' + section_id)[0].click()
			}catch(err) {
			}
		}
	}
}
function showWooCommerceLoadingModal(buttonBackground) {
	var code = `
	<div id="showWooCommerceModal" class="scc-modal-2020 fade" role="dialog" style="opacity:1">
	<div class="scc-modal-dialog-2020" style="width:560px;top:250px;">
	<div class="scc-modal-content-2020">
	<div class="scc-modal-header-2020">
	<button type="button" class="close" data-dismiss="modal">&times;</button>
	</div>
	<div class="scc-modal-body-2020">
	<center><div id="woocommerce_loading_bar"></div></center>
	</div>
	</div>
	</div>
	</div>
	`;
	jQuery('#showWooCommerceModalContainer').html(code)
	jQuery('#showWooCommerceModal').modal('show')
	var bar=new RadialProgress(document.getElementById("woocommerce_loading_bar"),{indeterminate:false,colorFg:buttonBackground,thick:10,fixedTextSize:0.2});
	bar.setValue(0.5);
}
function showWooCommerceModal(redirect_url, buttonBackground) {
	var code = `
	<div id="showWooCommerceModal" class="scc-modal-2020 fade" role="dialog"  style="opacity:1">
	<div class="scc-modal-dialog-2020" style="width:560px;top:250px;">
	<div class="scc-modal-content-2020">
	<div class="scc-modal-header-2020" style="border:0px!important;">
	<button type="button" class="close" data-dismiss="modal">&times;</button>
	</div>
	<div class="scc-modal-body-2020" style="border:0px!important;">
	<p style="trn">Items added to cart.</p>
	</div>
	<div class="modal-footer" style="border:0px!important;">
	<button type="button" class="btn btn-default trn" style="background: `+ buttonBackground + `!important; color: white !important;" onClick="wooCommerceRedirectToCheckOut('`+ redirect_url + `')">Checkout</button>
	</div>
	</div>
	</div>
	</div>
	`;
  // jQuery('#showWooCommerceModalContainer').html(code)
  // jQuery('#showWooCommerceModal').modal('show')
  // wooCommerceRedirectToCheckOut('`+ redirect_url + `');
  setTimeout( function () {
  	jQuery('body').find('.modal-backdrop, .fade, .in').each(function(index, ob) {
  		if( typeof jQuery(ob).attr('id') == "undefined") {
  			jQuery(ob).remove()
  		}
  	})
  }, 1000)
}
function wooCommerceCancelCart() {
}
function wooCommerceRedirectToCheckOut( url ) {
	location.href = url
}
function setDefaultOption(elem) {
	let optBtn = jQuery(elem)
	optBtn.attr("data-selected") ? optBtn.css( "background-color", "#F0F0F0" ).removeAttr('data-selected').attr('data-tooltip', 'Click me make this option default.') : optBtn.css('background-color', '#56b665').removeAttr('data-tooltip').attr('data-selected', true)
  // jQuery(elem).css('background-color', '#56b665').removeAttr('data-tooltip').attr('data-selected', true)
  optRoot = jQuery(elem).closest(".content[value='selectoption']")
  opts = optRoot.find('.col-xs-2.col-md-2.tooltipadmin-left').not(elem)
  opts.css( "background-color", "#F0F0F0" ).removeAttr('data-selected').attr('data-tooltip', 'Click me make this option default.')
}
function secondStep($this, fieldOpt, ascdesc) {
	switch (fieldOpt) {
		case "sliderinput":
		fieldOpt = jQuery('#sliderOption').html().replace(/XXYYXX/g, 1);
		break;
		case "Asliderinput":
		fieldOpt = jQuery('#AsliderOption').html().replace(/XXYYXX/g, 1);
		break;
		case "switchinput":
		fieldOpt = jQuery('#switchoption').html().replace(/XXYYXX/g, 1);
		break;
		case "dropdowninput":
		fieldOpt = jQuery('#selectoption').html().replace(/ XXYYXX/g, 1);
		break;
		default:
		fieldOpt = jQuery('#inputoption').html();
	}
	if (ascdesc == 'ascend') {
		jQuery($this).parent().parent().parent().find('.fieldDatatoAdd').html(fieldOpt);
	} else if (ascdesc == 'descend') jQuery($this).find('.fieldDatatoAdd').html(fieldOpt);
}
function sliderOptions(name, desc, section, value) {
	this.name = name;
	this.desc = desc;
	this.section = section;
	this.value = value;
}
function sectionOptions(name, desc, accordion, title_column_desktop, title_column_mobile, section, value, showSectionTotal) {
	this.name = germanCharacters(name);
	this.desc = germanCharacters(desc);
	this.section = section;
	this.value = value;
	this.accordion = accordion;
	this.showSectionTotal = showSectionTotal || false;
	this.title_column_desktop = title_column_desktop;
	this.title_column_mobile = title_column_mobile;
}
function SubOptions(subsection, Nooptions, minmax, step, defaultValue, showPriceHint, isSlidingScale = false, uniqueID = null, isSliderMandatory = false) {
	this.subsection = subsection;
	this.Nooptions = Nooptions;
	this.minmax = minmax;
	this.step = step;
	this.defaultValue = defaultValue;
	this.showPriceHint = showPriceHint;
	this.isSlidingScale = isSlidingScale;
	this.uniqueID = uniqueID;
	this.isSliderMandatory = isSliderMandatory;
}
function sliderOptions1(name, step, defaultValue, discount, ndiscount) {
	this.name = name;
  // this.min = min;
  // this.max = max;
  this.step = step;
  this.defaultValue = defaultValue;
  // this.multiplier = multiplier;
  this.discount = discount;
  this.ndiscount = ndiscount;
}
function validateTextInput(fieldInputName, $this, textInputVar) {
	jQuery($this).find('.warning').html('');
	if (fieldInputName.trim() == '') {
		jQuery($this).find('.warning').html('Product/Service name cannot be empty');
		return;
	}
	if (textInputVar.trim() == '' || isNaN(textInputVar)) {
		jQuery($this).find('.warning').html('Error - Price Value is not numeric');
		return true;
	}
	return false;
}
function validateComment(fieldDropServiceName, $this) {
	jQuery($this).parent().find('.warning').html('');
	if (fieldDropServiceName == '') {
		jQuery($this).parent().find('.warning').html('Please, check the title. It can not be empty');
		jQuery('html, body').animate({
			scrollTop: jQuery($this).parent().find('.warning').offset().top - 200
		}, 1000);
		setTimeout(function() {
			alert('Comment: Please, check the title. It can not be empty')
		}, 1000)
		return true;
	}
	return false;
}
function validateCustomMath(fieldDropServiceName, $this, value_2) {
	jQuery($this).find('.scc_custom_math').find('.warning').html('');
	if (fieldDropServiceName == '') {
		jQuery($this).find('.scc_custom_math').find('.warning').html('Please, check the title. It can not be empty');
		jQuery('html, body').animate({
			scrollTop: jQuery($this).find('.scc_custom_math').find('.warning').offset().top - 200
		}, 1000);
		setTimeout(function() {
			alert('Custom Math: Please, check the title. It can not be empty')
		}, 1000)
		return true;
	}
	if (value_2 == '' || isNaN(value_2)) {
		jQuery($this).find('.scc_custom_math').find('.warning').html('Error - Price values must be numeric');
		jQuery('html, body').animate({
			scrollTop: jQuery($this).find('.scc_custom_math').find('.warning').offset().top - 200
		}, 1000);
		setTimeout(function() {
			alert('Custom Math: Please, check the fields. Price values must be numeric')
		}, 1000)
		return true;
	}
	return false;
}
function validateQuantityBox(fieldDropServiceName, $this, value_2) {
	jQuery($this).parent().find('.warning').html('');
	if (fieldDropServiceName == '') {
		jQuery($this).parent().find('.warning').html('Please, check the title. It can not be empty');
		jQuery('html, body').animate({
			scrollTop: jQuery($this).parent().find('.warning').offset().top - 200
		}, 1000);
		setTimeout(function() {
			alert('Quantity Box: Please, check the title. It can not be empty')
		}, 1000)
		return true;
	}
	if (value_2 == '' || isNaN(value_2)) {
		jQuery($this).parent().find('.warning').html('Error - Price values must be numeric');
		jQuery('html, body').animate({
			scrollTop: jQuery($this).parent().find('.warning').offset().top - 200
		}, 1000);
		setTimeout(function() {
			alert('Quantity Box: Please, check the fields. Price values must be numeric')
		}, 1000)
		return true;
	}
	return false;
}
function validateDropDown(fieldDropServiceName, $this, value_1, value_2,dropdownServiceMandatory) {
	jQuery($this).find('.warning').html('');
	if (fieldDropServiceName == '') {
		jQuery($this).find('.warning').html('One of the names is empty');
		jQuery('html, body').animate({
			scrollTop: jQuery($this).find('.warning').parent().parent().offset().top - 200
		}, 1000);
		setTimeout(function() {
			alert('Dropwdown: Please, check the fields. They can not be empty')
		}, 1000)
		return true;
	}
	if (value_1 == '') {
		jQuery($this).find('.warning').html('One of the names is empty');
		jQuery('html, body').animate({
			scrollTop: jQuery($this).find('.warning').parent().parent().offset().top - 200
		}, 1000);
		setTimeout(function() {
			alert('Dropwdown: Please, check the fields. They can not be empty')
		}, 1000)
		return true;
	}
	if (value_2 == '' || isNaN(value_2)) {
		jQuery($this).find('.warning').html('Error - price values must be numeric');
		jQuery('html, body').animate({
			scrollTop: jQuery($this).find('.warning').parent().parent().offset().top - 200
		}, 1000);
		setTimeout(function() {
			alert('Dropwdown: Please, check the fields. Price values must be numeric')
		}, 1000)
		return true;
	}
	return false;
}
function validateSwitch($this, value_1, value_2) {
	jQuery($this).find('.warning').html('');
	if (value_1 == '') {
		jQuery($this).find('.warning').html('One of the names is empty');
		jQuery('html, body').animate({
			scrollTop: jQuery($this).find('.warning').parent().parent().offset().top - 200
		}, 1000);
		setTimeout(function() {
			alert('Checkbox / Toggle / Button: Please, check the fields. They can not be empty')
		}, 1000)
		return true;
	}
	if (value_2 && (value_2.trim() == '' || isNaN(value_2))) {
		jQuery($this).find('.warning').html('Error - price values must be numeric');
		jQuery('html, body').animate({
			scrollTop: jQuery($this).find('.warning').parent().parent().offset().top - 200
		}, 1000);
		setTimeout(function() {
			alert('Checkbox / Toggle / Button: Please, check the fields. Price values must be numeric')
		}, 1000)
		return true;
	}
	return false;
}
function validateSlider($this, fieldName) {
	var errors = false
	if (fieldName.trim() == '') {
		jQuery($this).find('.selslideropt_3').find('.warning').html('Product/Service name cannot be empty');
		jQuery('html, body').animate({
			scrollTop: jQuery($this).find('.selslideropt_3').find('.warning').offset().top - 200
		}, 1000);
		setTimeout(function() {
			alert('Slider: Product/Service name cannot be empty')
		}, 1000)
		errors = true
		return true;
	}
	var step = jQuery($this).find('.selslideropt_3').find('.slidoption_3').val();
	if (!step || step.trim() == '' || isNaN(step)) {
		jQuery($this).find('.selslideropt_3').find('.warning').html('Step value is not numeric');
		jQuery('html, body').animate({
			scrollTop: jQuery($this).find('.selslideropt_3').find('.warning').offset().top - 200
		}, 1000);
		setTimeout(function() {
			alert('Slider: Step value is not numeric')
		}, 1000)
		errors = true
		return true;
	}
	var defaultValue = jQuery($this).find('.selslideropt_3').find('.slidoption_4').val();
	if (!defaultValue || defaultValue.trim() == '' || isNaN(defaultValue)) {
		jQuery($this).find('.selslideropt_3').find('.warning').html('Starting Number value is not numeric');
		jQuery('html, body').animate({
			scrollTop: jQuery($this).find('.selslideropt_3').find('.warning').offset().top - 200
		}, 1000);
		setTimeout(function() {
			alert('Slider: Starting Number value is not numeric')
		}, 1000)
		errors = true
		return true;
	}
	var maxArray = []
	var minArray = []
	var pricesArray = []
  // min ranges:
  jQuery($this).find('.selslideropt_3').find('.sliderinputoption').each(function(index, ob){
  	var min = jQuery(ob).val() == '' ? undefined : Number(jQuery(ob).val());
  	if (typeof min != 'number') {
  		jQuery($this).find('.selslideropt_3').find('.warning').html('Minimum value (from) is not numeric or above 0');
  		jQuery('html, body').animate({
  			scrollTop: jQuery($this).find('.selslideropt_3').find('.warning').offset().top - 200
  		}, 1000);
  		setTimeout(function() {
  			alert('Slider: Minimum value (from) is not numeric or above 0')
  		}, 1000)
  		errors = true
  		return true;
  	}
  	minArray.push(min)
  })
  // max ranges:
  jQuery($this).find('.selslideropt_3').find('.sliderinputoption_2').each(function(index, ob){
  	var max = jQuery(ob).val() == '' ? undefined : Number(jQuery(ob).val());
  	if (typeof max != 'number') {
  		jQuery($this).find('.selslideropt_3').find('.warning').html('Minimum value (from) is not numeric or above 0');
  		jQuery('html, body').animate({
  			scrollTop: jQuery($this).find('.selslideropt_3').find('.warning').offset().top - 200
  		}, 1000);
  		setTimeout(function() {
  			alert('Slider: Maximum value is not numeric')
  		}, 1000)
  		errors = true
  		return true;
  	}
  	maxArray.push(max)
  })
  // prices ranges:
  jQuery($this).find('.selslideropt_3').find('.sliderinputoption_5').each(function(index, ob){
  	var rangePrice = jQuery(ob).val() == '' ? undefined : Number(jQuery(ob).val());
  	if (typeof rangePrice != 'number') {
  		jQuery($this).find('.selslideropt_3').find('.warning').html('Range price value is not numeric');
  		jQuery('html, body').animate({
  			scrollTop: jQuery($this).find('.selslideropt_3').find('.warning').offset().top - 200
  		}, 1000);
  		setTimeout(function() {
  			alert('Slider: Range price value is not numeric')
  		}, 1000)
  		errors = true
  		return true;
  	}
  	pricesArray.push(rangePrice)
  })
  for(var i = 0; i < maxArray.length; i++){
  	var min = minArray[i]
  	var max = maxArray[i]
      /*
          if (parseInt(defaultValue) < parseInt(min) || parseInt(defaultValue) > parseInt(max)) {
            jQuery($this).find('.selslideropt_3').find('.warning').html('Starting Number Value cannot be greater than the maximum value, or smaller than the minimum value');
            errors = true
            return true;
          }
          */
          if (parseInt(min) > parseInt(max) && (parseInt(min) !=0) ) {
          	jQuery($this).find('.selslideropt_3').find('.warning').html('Minimum value has to be smaller than the maximum value')
          	jQuery('html, body').animate({
          		scrollTop: jQuery($this).find('.selslideropt_3').find('.warning').offset().top - 200
          	}, 1000);
          	setTimeout(function() {
          		alert('Slider: Minimum value has to be smaller than the maximum value')
          	}, 1000)
          	errors = true
          	return true;
          }
          if (parseInt(step) > max && max !=0 && min !=0) {
          	jQuery($this).find('.selslideropt_3').find('.warning').html('Step Value cannot be more than the maximum value');
          	jQuery('html, body').animate({
          		scrollTop: jQuery($this).find('.selslideropt_3').find('.warning').offset().top - 200
          	}, 1000);
          	setTimeout(function() {
          		alert('Slider: Step Value cannot be more than the maximum value')
          	}, 1000)
          	errors = true
          	return true;
          }
      }
      if(!errors){
      	jQuery($this).find('.selslideropt_3').find('.warning').html('');
      }
      return errors;
  }
  function resort_updown() {
  	jQuery('#allinputstoadd .down:last').css("display", "none");
  	jQuery('#allinputstoadd .up:first').css("display", "none");
  	jQuery('#allinputstoadd .down').not(':last').css("display", "block");
  	jQuery('#allinputstoadd .up').not(':first').css("display", "block");
  	jQuery('#allinputstoadd .fieldDatatoAdd .sdown:last-child').css("display", "none");
  	jQuery('#allinputstoadd .fieldDatatoAdd .sup:first-child').css("display", "none");
  	jQuery('#allinputstoadd .fieldDatatoAdd .sdown').not(':last').css("display", "block");
  	jQuery('#allinputstoadd .fieldDatatoAdd .sup').not(':first').css("display", "block");
  }
  function remove_field($this) {
  	jQuery($this).parent('div').remove();
  }
  function rup($this) {
  var wrapper = jQuery($this).closest('.addedFieldsStyle'); //.closest('div');
  wrapper.insertBefore(wrapper.prev());
  resort_updown();
}
function rdown($this) {
  var wrapper = jQuery($this).closest('.addedFieldsStyle'); //.closest('div');
  wrapper.insertAfter(wrapper.next());
  resort_updown();
}
function ClosePopup(){
	jQuery('.hover_bkgr_fricc').hide();
}
function ClosePopup1(){
	jQuery('.speech-bubble').hide();
}
function openNav() {
	document.getElementById("myNav").style.width = "100%";
}
function closeNav() {
	document.getElementById("myNav").style.width = "0%";
}
sccWhenAvailable('jQuery',function(){
	if (typeof(sccMain) !== 'undefined') Object.keys(sccMain).forEach(async e => {await initConditionalLogicFront(e)})
		jQuery('.scc_button_section').change(function(){
			if(jQuery(this).is(":checked")) {
				jQuery(this).parent().addClass("btn-selected");
			} else {
				jQuery(this).parent().removeClass("btn-selected");
			}
		});
	jQuery('[data-toggle="tooltip"]').tooltip();

	sliderPriceRangeInit();
  // initConditionalLogic();
  if(document.getElementById('wpfooter')){
  	document.getElementById('wpfooter').style='position: absolute !important'
  }
  if (!!jQuery.prototype.datepicker) {
  	if(jQuery("#coupon_start_date")) {
  		jQuery("#coupon_start_date").datepicker({
  			dateFormat: 'mm/dd/yy',
  			onSelect: function(selected) {
  				jQuery("#coupon_end_date").datepicker("option","minDate", selected)
  			}
  		})
  	}
  	if(jQuery("#coupon_end_date")) {
  		jQuery("#coupon_end_date").datepicker({
  			dateFormat: 'mm/dd/yy',
  			onSelect: function(selected) {
  				jQuery("#coupon_start_date").datepicker("option","maxDate", selected)
  			}
  		})
  	}
  } else {
  	jQuery.getScript('https://code.jquery.com/ui/1.12.0/jquery-ui.min.js', function(data) {
  		if (!!jQuery.prototype.datepicker) {
  			if(jQuery("#coupon_start_date")) {
  				jQuery("#coupon_start_date").datepicker({
  					dateFormat: 'mm/dd/yy',
  					onSelect: function(selected) {
  						jQuery("#coupon_end_date").datepicker("option","minDate", selected)
  					}
  				})
  			}
  			if(jQuery("#coupon_end_date")) {
  				jQuery("#coupon_end_date").datepicker({
  					dateFormat: 'mm/dd/yy',
  					onSelect: function(selected) {
  						jQuery("#coupon_start_date").datepicker("option","maxDate", selected)
  					}
  				})
  			}
  		}
  	})
  }
  jQuery('.save_button').each(function (index, value) {
  	jQuery(this).css('pointer-events', 'auto')
  })
  if(typeof checkPluginCacheHasBeenLoaded === "function"){
  	checkPluginCacheHasBeenLoaded()
  }
  if(jQuery('#save_coupon_modal')){
  	jQuery('#save_coupon_modal').modal('show')
  }
  if(jQuery('#deleted_info_coupon_modal')){
  	jQuery('#deleted_info_coupon_modal').modal('show')
  }
		// START of Multiple Total shortcode with combine attribute's frontend javascript
		jQuery('.scc-multiple-total-wrapper[data-combination]').on('valueChange', function(event) {
			/* showCurrencySymbol : if the currency symbol be showed or not it finds the value from the data attribute
				values : gets the total values from the calculator IDs
				*/
				let showCurrencySymbol = jQuery(this).data('currSym');
				let values = jQuery(this).data('combination').map(e => jQuery(`#scc_form_${e} #totalvalue`).text());
			// the combined value is a variable that goes through a loop and adds the values in the previously defined 'values' variable
			let combinedValue = 0;
			for (let index = 0; index < values.length; index++) {
				combinedValue+= parseFloat(values[index]);
			}
			// finally we apply the currency symbol and the value in the html elements
			showCurrencySymbol ? jQuery(this).find('.multi-total-currency-prefix').text(currencySymbol(currencyLabel)) : jQuery(this).find('.multi-total-currency-suffix').text(currencyLabel);
			jQuery(this).find('.scc-total').text(combinedValue).trigger('doMath');
		});
		// End of Multiple Total shortcode with combine attribute's frontend javascript
		// START of Multiple Total shortcode with apply-math attribute's frontend javascript
		jQuery('.scc-multiple-total-wrapper[data-math] .scc-total').on('doMath', function(event) {
			let $this = jQuery(this);
			// mathOperator: gets the data-math attribute's value
			let mathOperator = $this.parent().data('math');
			let elementTotal = parseFloat($this.text());
			// if there are math operators, we apply the math here
			if (elementTotal && mathOperator.length == 2) {
				let opKey = mathOperator[0];
				let opVal = parseFloat(mathOperator[1]);
				switch (opKey) {
					case 'divide':
					if (opVal > 0) elementTotal = elementTotal / parseFloat(opVal);
					break;
					case 'multiply':
					elementTotal = elementTotal * parseFloat(opVal);
					break;
					case 'add':
					elementTotal = elementTotal + parseFloat(opVal);
					break;
					case 'subtract':
					elementTotal = elementTotal - parseFloat(opVal);
					break;
					default:
					break;
				}
				$this.text(elementTotal);
			}
		})
		// END of Multiple Total shortcode with apply-math attribute's frontend javascript
})
// COUPONS FUNCTIONS !!
function saveCoupon(){
	if(couponValidation()){
		jQuery('#coupon_saving_button').html('<i class="fa fa-circle-o-notch fa-spin"></i> Saving...')
		$coupon_form = {
			url: rt_vars.rt_urlajax,
			type: 'POST',
			data: {
				action: 'sscSaveCoupon',
				id: jQuery('#coupon_id').val(),
				name: jQuery('#coupon_name').val(),
				code: jQuery('#coupon_code').val(),
				startdate: jQuery('#coupon_start_date').val(),
				enddate: jQuery('#coupon_end_date').val(),
				discountpercentage: typeof Number(jQuery('#coupon_discountpercentage').val()) === 'number' && (jQuery('#coupon_discountpercentage').val() > 0 || jQuery('#coupon_discountpercentage').val() === "0") ? jQuery('#coupon_discountpercentage').val() : -1,
				discountvalue: typeof Number(jQuery('#coupon_discountvalue').val()) === 'number' && (jQuery('#coupon_discountvalue').val() > 0 || jQuery('#coupon_discountvalue').val() === "0") ? jQuery('#coupon_discountvalue').val() : -1,
				minspend: typeof Number(jQuery('#coupon_minspend').val()) === 'number' && (jQuery('#coupon_minspend').val() > 0 || jQuery('#coupon_minspend').val() === "0") ? jQuery('#coupon_minspend').val() : -1,
				maxspend: typeof Number(jQuery('#coupon_maxspend').val()) === 'number' && jQuery('#coupon_maxspend').val() > 0? jQuery('#coupon_maxspend').val() : -1
			},
			success: function( data ){
     //     console.log("data.split('new_id=')[1]", data.split('new_id=')[1])
     //     var url = window.location.href.indexOf('&id=') != -1 ?   window.location.href : window.location.href + '&id=' + (data.split('new_id=')[1])
     var url = window.location.href
     url = url.indexOf('&saved') != -1 ?   url : url + '&saved=true'
     window.location.replace(url)
     jQuery('#coupon_saving_button').html('Saved')
 }
};
jQuery.ajax( $coupon_form );
}else{
}
}
function couponValidation(){
	var ok = true
	jQuery('#coupon_name_error').html('')
	jQuery('#coupon_code_error').html('')
	jQuery('#coupon_start_date_error').html('')
	jQuery('#coupon_end_date_error').html('')
	jQuery('#coupon_discountpercentage_error').html('')
	jQuery('#coupon_discountvalue_error').html('')
	jQuery('#coupon_minspend_error').html('')
	jQuery('#coupon_maxspend_error').html('')
	if(jQuery('#coupon_name').val() < 2){
		jQuery('#coupon_name_error').html('Invalid name')
		ok = false
	}
	if(jQuery('#coupon_code').val() < 4){
		jQuery('#coupon_code_error').html('Invalid coupon code. Please, 4 characters at least.')
		ok = false
	}
	if(jQuery('#coupon_start_date').val().length != 10){
		jQuery('#coupon_start_date_error').html('Invalid start date. Please, use the datepicker to add the date.')
		ok = false
	}
	if(jQuery('#coupon_end_date').val().length != 10){
		jQuery('#coupon_end_date_error').html('Invalid end date. Please, use the datepicker to add the date.')
		ok = false
	}
	if(jQuery('#coupon_discountpercentage').val() < 0 || jQuery('#coupon_discountpercentage').val() >100){
		jQuery('#coupon_discountpercentage_error').html('Discount percentage has to be between 0 and 100.')
		ok = false
	}
	if(jQuery('#coupon_discountvalue').val() < 0 ){
		jQuery('#coupon_discountvalue_error').html('Discount value has to be more than 0.')
		ok = false
	}
	if((typeof Number(jQuery('#coupon_discountpercentage').val()) === 'number'
		&& typeof Number(jQuery('#coupon_discountvalue').val()) === 'number')
		&&  Number(jQuery('#coupon_discountpercentage').val()) > 0
		&&  Number(jQuery('#coupon_discountvalue').val()) > 0){
		jQuery('#coupon_discountpercentage_error').html('Please, Add only one type of discount. (delete value to remove the discount type)')
	jQuery('#coupon_discountvalue_error').html('Please, Add only one type of discount. (delete value to remove the discount type)')
	ok = false
}
if(( (jQuery('#coupon_discountpercentage').val() === 0 || jQuery('#coupon_discountpercentage').val() === "0") && (jQuery('#coupon_discountvalue').val() === 0 && jQuery('#coupon_discountvalue').val() === "0"))
	|| (jQuery('#coupon_discountpercentage').val() === '' && jQuery('#coupon_discountvalue').val() === '')){
	jQuery('#coupon_discountpercentage_error').html('Please add one type of discount.')
jQuery('#coupon_discountvalue_error').html('Please add one type of discount.')
ok = false
}if(Number(jQuery('#coupon_minspend').val()) > Number(jQuery('#coupon_maxspend').val())){
	jQuery('#coupon_minspend_error').html('Minimum spend can not be equal or higher than maximum spend.')
	jQuery('#coupon_maxspend_error').html('Minimum spend can not be equal or higher than maximum spend.')
	ok = false
}
if(jQuery('#coupon_discountvalue').val().indexOf('e') != -1){
	jQuery('#coupon_discountvalue_error').html('Invalid numeric value.')
	ok = false
}
if(jQuery('#coupon_discountpercentage').val().indexOf('e') != -1){
	jQuery('#coupon_discountpercentage_error').html('Invalid numeric value.')
	ok = false
}
if(jQuery('#coupon_minspend').val().indexOf('e') != -1){
	jQuery('#coupon_minspend_error').html('Invalid numeric value.')
	ok = false
}
if(jQuery('#coupon_maxspend').val().indexOf('e') != -1){
	jQuery('#coupon_maxspend_error').html('Invalid numeric value.')
	ok = false
}
return ok
}
function deleteCouponModal(id, name){
	var code = ""
	code += '<div id="delete_coupon_modal" class="scc-modal-2020 fade"  role="dialog">'
	code += '	<div class="scc-modal-dialog-2020">'
	code += '		<div class="scc-modal-content-2020" style="margin-top:100px">'
	code += '		<div class="scc-modal-header-2020">'
	code += '			<button type="button" class="close" data-dismiss="modal">&times;</button>'
	code += '			<h3 class="scc-modal-title-2020">Delete ' + name + '</h3>'
	code += '		</div>'
	code += '		<div class="scc-modal-body-2020" >'
	code += '        <p>Are you sure do you want to delete the coupon \'' + name + '\'</p>'
	code += '       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'
	code += '       <button type="button" class="btn btn-danger" onClick="deleteCoupon(' + id + ')">Delete</button>'
	code += '		</div>'
	code += '		</div>'
	code += '	</div>'
	code += '</div>'
	var codeNew = `<div class="df-scc-euiOverlayMask df-scc-euiOverlayMask--aboveHeader">
	<div class="df-scc-euiModal df-scc-euiModal--maxWidth-default df-scc-euiModal--confirmation">
	<button class="df-scc-euiButtonIcon df-scc-euiButtonIcon--text df-scc-euiModal__closeIcon" type="button" data-dismiss="modal"><svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" class="df-scc-euiIcon df-scc-euiIcon--medium df-scc-euiButtonIcon__icon" focusable="false" role="img" aria-hidden="true"><path d="M7.293 8L3.146 3.854a.5.5 0 11.708-.708L8 7.293l4.146-4.147a.5.5 0 01.708.708L8.707 8l4.147 4.146a.5.5 0 01-.708.708L8 8.707l-4.146 4.147a.5.5 0 01-.708-.708L7.293 8z"></path></svg></button>
	<div class="df-scc-euiModal__flex">
	<div class="df-scc-euiModalHeader"><div class="df-scc-euiModalHeader__title">Delete ${name}?</div></div>
	<div class="df-scc-euiModalBody">
	<div class="df-scc-euiModalBody__overflow">
	<div class="df-scc-euiText df-scc-euiText--medium">
	<p>Are you sure do you want to delete the coupon ${name}?</p>
	</div>
	</div>
	</div>
	<div class="df-scc-euiModalFooter">
	<button class="df-scc-euiButtonEmpty df-scc-euiButtonEmpty--primary" type="button" data-dismiss="modal">
	<span class="df-scc-euiButtonContent df-scc-euiButtonEmpty__content"><span class="df-scc-euiButtonEmpty__text">Cancel</span></span>
	</button>
	<button class="df-scc-euiButton df-scc-euiButton--primary df-scc-euiButton--fill" type="button" onclick="javascript:deleteCoupon(${id});">
	<span class="df-scc-euiButtonContent df-scc-euiButton__content"><span class="df-scc-euiButton__text">Yes</span></span>
	</button>
	</div>
	</div>
	</div>
	</div>`;
	jQuery('#delete_coupon_modal_container').html(codeNew)
	jQuery('#delete_coupon_modal_container').modal('show')
}
function deleteCoupon(id){
	$coupon_form_delete = {
		url: rt_vars.rt_urlajax,
		type: 'POST',
		data: {
			action: 'sccDeleteCoupon',
			id: id
		},
		success: function( data ){
			window.location.replace(window.location.href.indexOf('&deleted') != -1 ?   window.location.href : window.location.href + '&deleted=true')
		}
	};
	jQuery.ajax( $coupon_form_delete );
}
;(function() {
	window.scc_inputNumber = function(el) {
		var min = el.attr('min') || false;
		var max = el.attr('max') || false;
    // var els = {};
    // els.dec = el.prev();
    // els.inc = el.next();
    el.each(function() {
    	init(jQuery(this));
    });
    function init(el) {
    	el.prev().on('click', decrement);
    	el.next().on('click', increment);
    	function decrement() {
    		var value = el[0].value;
    		value--;
    		if(!min || value >= min) {
    			el[0].value = value;
    			el.trigger('change');
    		}
    	}
    	function increment() {
    		var value = el[0].value;
    		value++;
    		if(!max || value <= max) {
    			el[0].value = value++;
    			el.trigger('change');
    		}
    	}
    }
}
})();
sccWhenAvailable('jQuery', () => {
	scc_inputNumber(jQuery('.scc_wrapper .number_box_2_text'));
});
function df_scc_processAction(actionType, parentElement, element) {
	if (actionType == 'show') {
		parentElement.show(300);
	}
	if (actionType == 'hide') {
		// if (parentElement.attr('data-show-detailed-list')) {
		// 	return;
		// }
		df_scc_resetValues(element);
		parentElement.hide(300);
	}
}
function df_scc_resetValues(element) {
	switch(element.data('inputtype')) {
		case("dropdowninput"): {
			if(element.val().length) element.val('').trigger('change');
			break;
		}
		case("number_input"): {
			if(element.val().length) element.val('').trigger('change');
			break;
		}
		case("sliderinput"): {
			let calculatorId = element.data('calculatorId');
			let sliderId = element.attr('id');
			let slider = sccMain[calculatorId].sliders[sliderId];
			if (slider.getValue()) slider.setValue(0, true, true);
		}
		default: {
			if (typeof(element.data('inputtype')) == 'undefined' && element.find('input').data('inputtype') == "switchoption") {
				if (element.find('input').prop('checked')) element.find('input').click();
			}
		}
	}
	return;
}
// all input fields will have an unique ID
//Start OF CONDITION LOGIC FRONTEND INITILIZATION
async function initConditionalLogicFront(calculatorId) {
	const conditionsSrcTargetBinding = [];
	try {
		Object.keys(sccMain[calculatorId].conditionObjFront).map((obj, index) => {
			return (sccMain[calculatorId].conditionObjFront[obj].map((e,i) => {
				return Object.keys(e).map((ee) => {
					let showHideTargetElement = jQuery(`[data-uniqueId=${calculatorId+obj}]`);
					let showHideTargetElementClosest = jQuery(`[data-uniqueId=${calculatorId+obj}]`).closest('.scc-form-field-item');
					if (!(Array.isArray(conditionsSrcTargetBinding[calculatorId+ee]))) {
						conditionsSrcTargetBinding[calculatorId+ee] = [];
						conditionsSrcTargetBinding[calculatorId+ee].push({obj, showHideTargetElement, showHideTargetElementClosest});
					} else {
						conditionsSrcTargetBinding[calculatorId+ee].push({obj, showHideTargetElement, showHideTargetElementClosest});
					}
				})
			}))
		});
	} catch (error) {
	}
	console.log(conditionsSrcTargetBinding);
	Object.keys(conditionsSrcTargetBinding).forEach((e) => {
		jQuery(`[data-uniqueId=${e}]`).on('change', (event) => {
			let toShow = [];
			let toHide = [];
			let toReset = [];
			conditionsSrcTargetBinding[e].forEach((data,index) => {
				let {obj, showHideTargetElement, showHideTargetElementClosest} = data;
				if (df_scc_evaluate(obj, calculatorId)) {
					showHideTargetElementClosest.get().forEach(e => {
						// exclude if custom math is set to not show on frontend
						if (typeof(jQuery(e).data('display-frontend')) == 'undefined') toShow.push(e);
						if (jQuery(e).data('default')) {
							jQuery(e).find('input').click();
						};
					})
				} else {
					showHideTargetElementClosest.get().forEach(e => toHide.push(e));
					showHideTargetElement.get().forEach(e => toReset.push(e));
				}
			});
			jQuery(toShow).show();
			jQuery(toHide).hide();
			setTimeout(() => {
				jQuery.each(toReset, (i, e) => {
					df_scc_resetValues(jQuery(e));
				})
			}, 1);
		})
		jQuery(`[data-uniqueId=${e}]`).trigger('change');
	})
	return true;
};
//END OF CONDITION LOGIC FRONTEND INITILIZATION
function execMatchVerification(arg, elementUniqueId, calculatorId) {
	arg.match = false;
	element = jQuery(`[data-uniqueId=${calculatorId+elementUniqueId}]`);
	elementValue = function() {
		switch (element.data('inputtype')) {
			case 'dropdowninput':
			return element.prop('selectedIndex');
			case 'switchoption':
			return element.prop('checked');
			default:
			return element.val()
		}
	}();
  // elementValue = element.prop('name') == 'selectbasic' ? element.prop('selectedIndex') : element.prop('checked');
  switch(arg.op) {
  	case("eq"): {
      // console.log(arg, 'hit');
      if(elementValue == parseInt(arg.val)) {
      	arg.match = true;
      }
      break;
  }
  case("gt"): {
  	if (elementValue > parseInt(arg.val)) {
  		arg.match = true;
  	}
  	break;
  }
  case("ne"): {
  	if (elementValue != parseInt(arg.val)) {
  		arg.match = true;
  	}
  	break;
  }
  case("less"): {
  	if (elementValue < parseInt(arg.val)) {
  		arg.match = true;
  	}
  	break;
  }
  case("any"): {
  	if (elementValue != 'unset' && elementValue != 0 && elementValue != '' ) {
  		arg.match = true;
  	}
  	break;
  }
  case("true"): {
  	if (elementValue) {
  		arg.match = true;
  	}
  	break;
  }
  case("false"): {
  	if (!elementValue) {
  		arg.match = true;
  	}
  	break;
  }
  default: {
  	arg.match = false;
  }
}
return arg;
}
function df_scc_evaluate(data, calculatorId) {
	let checker = arr => arr.every(v => v === true);
	let finalVal = (element) => element === true;
  // TODO trycatch it
  res = checkConditionFulfilment((sccMain[calculatorId].conditionObjFront[data].map((e,i) => {
  	return Object.keys(e).map(ee => {
  		return execMatchVerification(e[ee], ee, calculatorId );
  	})
  })));
  return res.map(v => {
    // console.log(v);
    return checker(v);
}).some(finalVal);
}
function checkConditionFulfilment(e) {
    // console.log(e);
    return e.map(ee => {
    	return ee.map(eee => {
    		return eee.match;
    	})
    })
}
function sccProcessRecaptcha(recaptchaSiteKey, element) {
	var htmlData = `<div class="df-scc-euiModalBody__overflow recaptcha">
	<div class="df-scc-euiText df-scc-euiText--medium">
	<p class="trn">${translatorJson['Prove that you are not a robot'] ? translatorJson['Prove that you are not a robot'].en : 'Prove that you are not a robot'}</p>
	<div class="scc-g-recaptcha form-field"></div>
	</div>
	</div>`;
	jQuery.getScript('https://www.google.com/recaptcha/api.js')
	.done(function( script, textStatus ) {
		console.log(script);
		var modalBody = jQuery(element).closest('.df-scc-euiModal').find('.df-scc-euiModalBody');
		modalBody.children().hide();
		modalBody.children(':first').after(htmlData)
		return grecaptcha.ready(function() {
			console.log('ready');
			grecaptcha.render(modalBody.find('.scc-g-recaptcha')[0], {
				'sitekey' : recaptchaSiteKey,
				'callback' : function(e) {
					jQuery(element).data('recaptcha-key', e);
					jQuery(element).find('button[type=submit]').click();
				},
			});
		});
	})
	.fail(function(  jqxhr, settings, exception ) {
	});
	return;
}
sccWhenAvailable('jQuery', function($) {
	$.fn.customFile = function() {
		$file = this.find('input[type="file"]');
		$uploadBtn = this.find('.scc-ui.scc-fu-button');
		$uploadFileNamePlaceholder= this.find('.scc-ui.scc-fu-action.scc-fu-input input[type="text"]');
		$uploadBtn.unbind().click(function() {
			$(this).parent().find("input:file").click();
		});
		$uploadFileNamePlaceholder.unbind().click(function() {
			$(this).parent().find("input:file").click();
		});
		$file.on('change', function(e) {
			var name = function() {
				try {
					return e.target.files[0].name;
				} catch (error) {
					return '';
				}
			}
			try {
				if (e.target.files[0].size / 1024 > $(e.target).data('maxSize')) {
					var warnText = $(this).closest('.scc-form-field-item').find('.alert.alert-danger');
					warnText.html('<span class="trn">file size excheeds the limit</span>').show() && $(this).val('').trigger('change');
					initTranslationScriptSCC(warnText[0], {lang: "en", t: translatorJson});
					setTimeout(() => {
						warnText.hide(300);
					}, 5000);
				}
			} catch (error) {
			}
			$('input:text', $(e.target).parent()).val(name);
		});
	}
});
sccWhenAvailable('jQuery', () => {
	jQuery('.scc-file-upload').customFile();
});
sccWhenAvailable('jQuery', function($) {
	$.fn.sccAccordion = function() {
		this.find('.scc-title').unbind().on('click', function() {
      // console.log('w', this);
      var tarnsitionContent = $(this).next('.scc-content').children(' .scc-transition');
      var icon = $(this).children('i.material-icons');
      tarnsitionContent.toggleClass('hidden');
      tarnsitionContent.is(':visible') ? icon.text('keyboard_arrow_down') : icon.text('keyboard_arrow_right');
  })
	}
});
function addItemsToPayPalForm(items, tax, comments, calculator_id, isTaxInclusionEnabled = false){
	total = 0
	var itemsToAddPaypalForm = ""
	var itemsAdded = 0
	for(var i=0; i < items.length; i++){
		var item_value = ((items[i].unit === null || isNaN(items[i].unit)) ? items[i].value : (items[i].value * items[i].unit))
		var item_name  = ((items[i].unit === null  || items[i].unit === 1 || isNaN(items[i].unit)) ? items[i].paypal_name : ( items[i].unit + ' units: ' + items[i].paypal_name ))
		if (items[i].comment) {
			item_name = items[i].paypal_title + ': ' + items[i].paypal_text;
		}
	//    if(item_value > 0){
		if (item_name) {
			itemsToAddPaypalForm += '  <input type="hidden" name="item_name_'+ (itemsAdded+1) + '" value="' + item_name + '" class="btPayPalItem">'
			itemsToAddPaypalForm += '  <input type="hidden" name="amount_'+ (itemsAdded+1) + '" value="' + item_value.toFixed(2) + '" class="btPayPalItem">'
			itemsAdded++
		}
	//    }
	total += ((items[i].unit === null || isNaN(items[i].unit)) ? items[i].value : (items[i].value * items[i].unit));
}
	/*
	if(tax && tax > 0){
	console.log('tax included!')
	itemsToAddPaypalForm += '  <input type="hidden" name="item_name_'+ (items.length+1) + '" value="taxs" class="btPayPalItem">'
	itemsToAddPaypalForm += '  <input type="hidden" name="amount_'+ (items.length+1) + '" value="' + tax.toFixed(2) + '" class="btPayPalItem">'
	total += tax
	}
	*/
	if (tax && isTaxInclusionEnabled) {
		itemsToAddPaypalForm += '  <input type="hidden" name="item_name_'+ (itemsAdded+1) + '" value="tax" class="btPayPalItem">'
		itemsToAddPaypalForm += '  <input type="hidden" name="amount_'+ (itemsAdded+1) + '" value="' + tax.toFixed(2) + '" class="btPayPalItem">'
	}
	jQuery(`#scc_form_${calculator_id}`).find('form.paypal_form .paypal_form_add_items').html(itemsToAddPaypalForm);
}
function addToStripe(items, calculator_id) {
	// var itemsAdded = 0
	var processedItems = []
	for(var i=0; i < items.length; i++){
		var itemUnitValue = Number(items[i].value)
		var itemAddCount = items[i].unit
		var itemName  = items[i].paypal_name
		if (items[i].comment) {
			itemName = items[i].paypal_title + ': ' + items[i].paypal_text;
		}
		//    if(item_value > 0){
			if (itemName.length > 0 && itemUnitValue && itemAddCount) {
				processedItems.push({
					name: itemName,
					valuePerUnit: Number(itemUnitValue.toFixed(2)),
					units: itemAddCount
				})
			}
		}
		if (sccMain[calculator_id]) {
			sccMain[calculator_id].stripeCart = {processedItems};
		}
	}
	function onchangeComments($this){
		var sourceCalc = jQuery($this).attr('calculator_id');
		jQuery(`#scc_submit_${sourceCalc}`).click();
	}
	function sccProcessCheckout(calculator_id) {
		console.log(sccMain[calculator_id].stripeCart);
		$fragment_refresh = {
			url: rt_vars.rt_urlajax,
			type: 'POST',
			data: {
				action: 'scc_stripe_action',
				data: Base64.encode(JSON.stringify(sccMain[calculator_id].stripeCart)),
				currency: currencyLabel
			},
			success: function(session) {
				if (!session.error) {
					return stripe.redirectToCheckout({ sessionId: session.id });
				} else {
			  // jQuery('#stripe-bad-key').text(session.error);
			  console.log(session.error);
			}
		}
	};
	var validationCheckResult = sccMandatoryValidationCheck(null, null, calculator_id);
	if (validationCheckResult) jQuery.ajax($fragment_refresh);
}
function addWooCommerce(buttonBackground, calcId, cartAddAction = 'open_checkout') {
	var scc_mandatory = '';
	jQuery('.mandatory_yes_' + calcId).each(function(){
		if(jQuery(this).val() ==''  && jQuery(this).is(':visible')){
			// adding an onetime on change event handler to remove warning if value is truthy
			jQuery(this).one('change', function () {
				if (jQuery(this).val() !== '') {
					jQuery(this).parent().parent().find('.alert-danger').css('display','none');
				}
			})
			jQuery(this).parent().parent().parent().find('.alert-danger').html('<span class="trn">Please choose an option</span>');
			jQuery(this).parent().parent().parent().find('.alert-danger').css('display','block');
			if(window.hasOwnProperty("translatorJson")){
				initTranslationScriptSCC('body', {lang: "en", t: translatorJson});
			}
			checkIfParentIsAccordionAndOpenIt(this)
			jQuery('html, body').animate({
				scrollTop: jQuery(this).offset().top
			}, 1000);
			scc_mandatory = 'scc_remains';
		}
	});
	// check if mandatory sliders are utilized
	jQuery('#scc_form_' + calcId + ' ' + '[data-slider-mandatory=yes]').each((i,e) => {
		scc_mandatory += sliderMandatoryCheck(e);
	})
	if (scc_mandatory == '') {
		showWooCommerceLoadingModal(buttonBackground)
		// sanitize PDFJson, so it doesn't trigger errors
		var sanitizedPDFJson = eval('jsonPDF_' + calcId);
		sanitizedPDFJson.rows = sanitizedPDFJson.rows.filter(e => Object.keys(e).length);
		$ajaxQuery= {
			url: rt_vars.rt_urlajax,
			type: 'POST',
			xhrFields: {
				responseType: ''
			},
			data: {
				action: 'sccAddWooCommerce',
				payload: Base64.encode(JSON.stringify(sanitizedPDFJson)),
				cartAddAction: cartAddAction,
			},
			success: function(data){
				window.location = data;
			// showWooCommerceModal(data, buttonBackground)
		},
		error: function(err){
		}
	}
	jQuery.ajax($ajaxQuery);
}
}
function checkBoxMandatoryCheck(e) {
	var inputTags = jQuery('input', e);
	var isNoneChecked = !(inputTags.map((i,ee) => {return jQuery(ee).is(':checked')}).get().some(eee => eee == true))
	if (isNoneChecked && jQuery(e).find('div').filter('[data-uniqueId]').is(':visible')) {
		// adding an onetime on change event handler to remove warning if value is truthy
		inputTags.one('change', function () {
			if (jQuery(this).val() !== '') {
				jQuery(e).find('.alert-danger').css('display','none');
			}
		})
		jQuery(e).find('.alert-danger').html('<span class="trn">Please choose an option</span>').css('display','block');
		jQuery(e).parent().find('.scc-accordion').click();
		jQuery('html, body').animate({
			scrollTop: jQuery(e).offset().top
		}, 1000);
		if(window.hasOwnProperty("translatorJson")){
			initTranslationScriptSCC('body', {lang: "en", t: translatorJson});
		}
		return 'scc_remains';
	} else {
		jQuery(e).find('.alert-danger').hide();
		return '';
		// scc_mandatory == '';
	}
}
function sliderMandatoryCheck(element) {
	if (!Number(jQuery(element).val())) {
		jQuery(element).closest('.scc-form-field-item').next('.alert-danger').show();
		jQuery(element).one('change', () => {
			jQuery(element).closest('.scc-form-field-item').next('.alert-danger').hide();
		})
		return 'scc_remains';
	} else {
		jQuery(element).closest('.scc-form-field-item').next('.alert-danger').hide();
		return '';
	}
}
function sccMandatoryValidationCheck($this, submitEvent, calcId) {
	if(submitEvent) submitEvent.preventDefault();
	if (!calcId && $this) {
		calcId = jQuery($this).closest('.scc_wrapper').attr('id').split('scc_form_')[1];
	}
	var scc_mandatory = '';
	jQuery('.mandatory_yes_' + calcId).each(function(){
		if(jQuery(this).val() =='' && jQuery(this).is(':visible')){
			// adding an onetime on change event handler to remove warning if value is truthy
			jQuery(this).one('change', function () {
				if (jQuery(this).val() !== '') {
					jQuery(this).parent().parent().find('.alert-danger').css('display','none');
				}
			})
			jQuery(this).parent().parent().find('.alert-danger').html('<span class="trn">Please choose an option</span>');
			jQuery(this).parent().parent().find('.alert-danger').css('display','block');
			jQuery('html, body').animate({
				scrollTop: jQuery(this).offset().top
			}, 1000);
			scc_mandatory = 'scc_remains';
			if(window.hasOwnProperty("translatorJson")){
				initTranslationScriptSCC('body', {lang: "en", t: translatorJson});
			}
			checkIfParentIsAccordionAndOpenIt($this)
		}
	});
	// check if mandatory checkbox/button/switches are checked
	jQuery('#scc_form_' + calcId + ' ' + '[data-mandatory=yes]').each((i,e) => {
		scc_mandatory += checkBoxMandatoryCheck(e);
	})
	// check if mandatory sliders are utilized
	jQuery('#scc_form_' + calcId + ' ' + '[data-slider-mandatory=yes]').each((i,e) => {
		scc_mandatory += sliderMandatoryCheck(e);
	})
	if (scc_mandatory == '') {
		if(Number(total) && Number(total) > 0){
			if (submitEvent) submitEvent.target.submit();
			if (!submitEvent) return true;
			// jQuery("#paypal_form").submit();
			// jQuery("#paypal_form")[0].submit();
		}
	}
};
async function initiateQuoteForm(calcId, callbackFn = null) {
	var args = sccMain[calcId].quoteFormParams;
	var color = args[0];
	var isCaptchaEnabled = args[1];
	var disableUnitColumn = args[2];
	var recaptchaSiteKey = args[3];
	var scc_mandatory = '';
	jQuery(`.mandatory_yes_${calcId}`).each(function(){
		if(jQuery(this).val() =='' && jQuery(this).is(':visible')){
			// adding an onetime on change event handler to remove warning if value is truthy
			jQuery(this).one('change', function () {
				if (jQuery(this).val() !== '') {
					jQuery(this).parent().parent().find('.alert-danger').css('display','none');
				}
			})
			jQuery(this).parent().parent().find('.alert-danger').html('<span class="trn">Please choose an option</span>');
			jQuery(this).parent().parent().find('.alert-danger').css('display','block');
			jQuery('html, body').animate({
				scrollTop: jQuery(this).offset().top
			}, 1000);
			scc_mandatory = 'scc_remains';
			if(window.hasOwnProperty("translatorJson")){
				initTranslationScriptSCC('body', {lang: "en", t: translatorJson});
			}
			checkIfParentIsAccordionAndOpenIt(this)
		}
	});
	// check if mandatory checkbox/button/switches are checked
	jQuery('#scc_form_' + calcId + ' ' + '[data-mandatory=yes]').each((i,e) => {
		scc_mandatory += checkBoxMandatoryCheck(e);
	})
	// check if mandatory sliders are utilized
	jQuery('#scc_form_' + calcId + ' ' + '[data-slider-mandatory=yes]').each((i,e) => {
		scc_mandatory += sliderMandatoryCheck(e);
	})
	if (scc_mandatory == '') {
		// jQuery('.alert-danger').html('');
		jQuery('.alert-danger').css('display','none');
		let quoteFormPlaceholder = jQuery('#quote-form-placeholder');
		quoteFormPlaceholder.unbind("hidden.bs.modal").on('hidden.bs.modal', function () {
			var $this = jQuery(this);
			$this.removeClass('show');
		});
		let emailQuoteFormTitle = window.hasOwnProperty('translatorJson') && translatorJson['Email Quote Form'] ? translatorJson['Email Quote Form'].en : 'Email Quote Form';
		let quoteForm = await wp.template("scc-quote-text-field")({title: emailQuoteFormTitle, calcId, color, isCaptchaEnabled, disableUnitColumn, recaptchaSiteKey});
		if(quoteForm) {
			quoteFormPlaceholder.html(quoteForm);
			jQuery('input.comment_box_text', `#scc_form_${calcId}`).filter((i,e) => {
				var checkIfEmail = jQuery(e);
				var emailEvaluation = !(!checkIfEmail || !checkIfEmail.val() || !checkIfEmail.val().includes('@') || !checkIfEmail.val().includes('.') || checkIfEmail.val().includes('#') || checkIfEmail.val().length < 4)
				emailEvaluation && quoteFormPlaceholder.find('input[type="email"]').val(checkIfEmail.val());
			})
			if (callbackFn) {
				quoteFormPlaceholder.find('form').data('callback', {cb: callbackFn, node: event.currentTarget});
			}
			quoteFormPlaceholder.modal('show').addClass('show');
		}
	}
}
function handleQuoteSubmission(calcId, $this, color = 'cyan', isCaptchaEnabled = false, disableUnitColumn = false, recaptchaSiteKey = '') {
	event.preventDefault();
	var captchaResponse = jQuery($this).data('recaptcha-key');
	if (isCaptchaEnabled && !captchaResponse) {
		sccProcessRecaptcha(recaptchaSiteKey, $this);
		return;
	}
	// sanitize PDFJson, so it doesn't trigger errors
	var sanitizedPDFJson = eval('jsonPDF_' + calcId);
	sanitizedPDFJson.rows = sanitizedPDFJson.rows.filter(e => Object.keys(e).length);
	let userSubmittedData = new FormData($this);
	let toSubmitData = new FormData();
	let pageReferer =  document.referrer;
	let encodedQuoteData = Base64.encode(JSON.stringify({referer: pageReferer, pdf: sanitizedPDFJson}));
	toSubmitData.append('action', 'sccQuoteSubmission');
	toSubmitData.append('data', JSON.stringify([...userSubmittedData.entries()]));
	toSubmitData.append('quote_data', encodedQuoteData);
	toSubmitData.append('calcId', calcId);
	toSubmitData.append('captchaResponse', captchaResponse);
	toSubmitData.append('disableUnitColumn', disableUnitColumn);
	jQuery(`.scc_wrapper.calc-id-${calcId}`).find('.scc-file-upload input[type="file"]').each(function(i, e) {
		toSubmitData.append(`file-${i}`, e.files[0]);
	})
	jQuery.ajax({
		url: rt_vars.rt_urlajax,
		type: 'POST',
		context: $this,
		processData: false,
		contentType: false,
		data: toSubmitData,
		beforeSend: function() {
			let pleaseWaitText = window.hasOwnProperty("translatorJson") && translatorJson['Please wait...'] ? translatorJson['Please wait...'].en : 'Please wait...';
			jQuery(this).find('.df-scc-euiText.df-scc-euiText--medium').html(jQuery(`<div class="df-scc-progress df-scc-progress-striped active">
				<div class="df-scc-progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="background-color: ${color}; width: 100%">
				</div>
				</div>`));
			jQuery(this).find('.df-scc-euiModalHeader__title').text(pleaseWaitText);
			jQuery(this).find('.df-scc-euiModalFooter').hide();
		},
		success: async function( data ) {
			let failedMessage = jQuery(`
				<p><span class="trn">Email quote sending failed. Please review your recaptcha/email provider settings. And verify you have the PHP GD library installed on your server.</span></p>
				`);
			let checkSpamTip = typeof(translatorJson) !== 'undefined' && 
				translatorJson['Remember to check your spam folder.'] ?
				translatorJson['Remember to check your spam folder.'].en : translatorJson['Remember to check your spam folder']?.en || 'Remember to check your spam folder.';
			let successMessage = jQuery(`
				<p><span class="trn">Thank you! We sent your quote to</span> ${userSubmittedData.get('email')}.</p>
				<p style="font-size:12px;margin-top:-10px;">${checkSpamTip}</p>
				`);
			let message = successMessage;
			if (data?.error) {
				message = failedMessage;
				console.log(data.error);
			}
			if ( !data?.error && sccMain[calcId].webhookEvents?.quote_send ) {
				let rawQuoteItems = JSON.parse(JSON.stringify(sanitizedPDFJson));
				let calculator_name = rawQuoteItems.pdf_title;
				let quoteItemsA = rawQuoteItems.rows.filter(e => e?.attr?.name && e?.type == 'element').map(e => {
					e.attr.element_price = e.attr.total_price;
					delete e.attr.total_price;
					return {[e.attr.name] : e.attr};
				});
				let quoteItemsB = rawQuoteItems.rows.filter(e => e?.attr?.name && e?.type == 'element_dropdown').map(e => {
					e.attr.element_price = e.attr.total_price;
					delete e.attr.total_price;
					return {[e.elementTitle] : e.attr};
				});
				let quoteItemsC = rawQuoteItems.rows.filter(e => e?.type == 'comment').map(e => ({[e.attr.title] : e.attr}));
				// let quoteItemsD = rawQuoteItems.rows.filter(e => e?.type == 'total').map(e => ({[e.attr.title] : e.attr}));
				let quoteItemsD = rawQuoteItems.rows.filter(e => e?.type == 'total').map(e => {
					// check if currency conversion exist
					let price = e.attr.price;
					let convertedCurrencyStringIndex = price.indexOf('<');
					if (convertedCurrencyStringIndex > 0) {
						// using split the totals
						let totalPrice = price.substr(0,convertedCurrencyStringIndex);
						let convertedPrice = jQuery(price.substr(convertedCurrencyStringIndex)).text().trim().replace('(', '').replace(')', '');
						return {[e.attr.title] : {
							price: totalPrice,
							convertedPrice: convertedPrice,
							title: e.attr.title
						}};
					}
					if (convertedCurrencyStringIndex < 0 ) {
						return {[e.attr.title] : e.attr};
					}
				});
				let taxInfo = rawQuoteItems.rows.filter(e => e?.type == 'tax').map(e => { e.attr.tax_rate = e.attr.title_second_part; delete e.attr.title_second_part; return ({[e.attr.title] : e.attr})});
				let subTotal = rawQuoteItems.rows.filter(e => e?.type == 'subtotal_tax').map(e => ({[e.attr.title] : e.attr}));
				jQuery.ajax({
					url: rt_vars.rt_urlajax,
					type: "POST",
					data: {
						action: "scc_do_webhooks",
						type: "quote_send",
						calcId : calcId,
						data: {
							quoteItems : JSON.stringify([...quoteItemsA, ...quoteItemsB, ...quoteItemsC, ...quoteItemsD, {calculator_name}, ...taxInfo, ...subTotal]),
							emailQuoteForm: toSubmitData.get('data')
						}
					},
					success: async function() {
						if (jQuery($this).data('callback')) {
							let cb = jQuery($this).data('callback').cb;
							let node = jQuery($this).data('callback').node;
							cb(node);
							jQuery('#quote-form-placeholder').modal('hide');
						}
					}
				});
			}
			if (jQuery($this).data('callback') && !sccMain[calcId].webhookEvents?.quote_send && !data?.error) {
				let cb = jQuery($this).data('callback').cb;
				let node = jQuery($this).data('callback').node;
				cb(node);
				jQuery('#quote-form-placeholder').modal('hide');
			}
			if (!jQuery($this).data('callback')) {
				jQuery(this).find('.df-scc-euiText.df-scc-euiText--medium').html(message);
				jQuery(this).find('.df-scc-euiModalHeader__title').text('');
			}
			if (data?.error) {
				jQuery(this).find('.errorModalFooter').css({display: 'flex'});
			}
			// reset captcha response
			jQuery($this).data('recaptcha-key', '');
			// jQuery($this).find('.df-scc-euiModalFooter').hide();
			if(window.hasOwnProperty("translatorJson")){
				initTranslationScriptSCC($this, {lang: "en", t: translatorJson});
			}
		}
	})
	// [...x.entries()].map(e => e[0])
	// formFieldsArray.map(e => Object.keys(e)[0]).findIndex(e => e == "xtpi1q")
	// [...x.entries()].map(e => formFieldsArray[formFieldsArray.map(ee => Object.keys(ee)[0]).findIndex(eee => eee == e[0])][e[0]])
}
var scc_toDisablekeys = {37: 1, 38: 1, 39: 1, 40: 1};
function scc_preventDefault(e) {
	e.preventDefault();
}
function scc_preventDefaultForScrollKeys(e) {
	if (scc_toDisablekeys[e.keyCode]) {
		preventDefault(e);
		return false;
	}
}
// modern Chrome requires { passive: false } when adding event
var scc_supportsPassive = false;
try {
	window.addEventListener("test", null, Object.defineProperty({}, 'passive', {
		get: function () { scc_supportsPassive = true; }
	}));
} catch(e) {}
var wheelOpt = scc_supportsPassive ? { passive: false } : false;

var scc_wheelEvent = 'onwheel' in document.createElement('div') ? 'wheel' : 'mousewheel';
// call this to Disable
function scc_DisableScroll() {
	window.addEventListener('DOMMouseScroll', scc_preventDefault, false); // older FF
	window.addEventListener(scc_wheelEvent, scc_preventDefault, wheelOpt); // modern desktop
	window.addEventListener('touchmove', scc_preventDefault, wheelOpt); // mobile
	window.addEventListener('keydown', scc_preventDefaultForScrollKeys, false);
}
// call this to Enable
function scc_EnableScroll() {
	window.removeEventListener('DOMMouseScroll', scc_preventDefault, false);
	window.removeEventListener(scc_wheelEvent, scc_preventDefault, wheelOpt);
	window.removeEventListener('touchmove', scc_preventDefault, wheelOpt);
	window.removeEventListener('keydown', scc_preventDefaultForScrollKeys, false);
}
// this handles number input box change events
function onchangeNumberBox($this){
	let calculatorId = parseInt($this.getAttribute('calculator_id'));
	jQuery('#scc_submit_'+calculatorId).click();
}