var scc_jQuery = window.jQuery;

(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}});
/**
 * @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.
 *
 */
 (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 && !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;
};
})(scc_jQuery);
// 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 || {};
(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',
		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
})(scc_jQuery);
"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;
  						};
  						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);
   			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";
   						sliderTrackSelection = document.createElement("div");
   						sliderTrackSelection.className = "slider-selection";
   						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 " + 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";
   							tooltipElem.appendChild(arrow);
   							tooltipElem.appendChild(inner);
   						};
   						/* 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.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) {
				console.log('eeeeejadnasdadnajsdjasdn')
				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] + "%";
				console.log('asdfasd positionPercentages[0]', 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] + "%";
                                    }
                                    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;
});
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>');
}
if(scc_jQuery('.totalPrice').hasClass('scc_total_price_float')){
	autoscroll();
}
function autoscroll() {
	window.setTimeout(autoscroll, 100);
	scc_jQuery('.scc_total_price_float').css({"z-index": "9999","position": "fixed", "bottom": "0%","left": "0","margin": "auto","width":"70%","height":"auto"});
}
var numberOfFields = scc_jQuery('#allinputstoadd .addedFieldsStyle').length;
var numberOfSections = 0;
var numberOfElements = 0;
function removeField1($f) {
	numberOfElements--;
	console.log('removeField1')
	scc_jQuery($f).parent().parent().remove();
	resort_updown();
}
function loadExample($this) {
	$fragment_refresh = {
		url: rt_vars.rt_urlajax,
		type: 'POST',
		data: {
			action: 'loadExample',
			data_example: scc_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;
	scc_jQuery.ajax($fragment_refresh);
}
function addSlider($this) {
	demo = scc_jQuery('#scc-demover').attr('data-demo');
	var elementsAdded = scc_jQuery('.elements_added') ? scc_jQuery('.elements_added').length : 0;
		if (scc_jQuery($this).parent().find('.inputoption_slidchk').is(':checked')){
			scc_jQuery($this).parent().find('.inputoption_slidchk').prop('checked', false);
		} else {
			scc_jQuery($this).parent().find('.inputoption_slidchk').prop('checked', true);
			console.log('show modal!')
			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>'
			scc_jQuery('#slider_info_modal').html(code)
			scc_jQuery('#modalSliderInfo').modal('show')
		}
		scc_jQuery($this).parent().parent().find('.selslideropt_3').slideToggle();
		scc_jQuery($this).parent().parent().find('.selslideropt_3 .styled-accordion').sccAccordion();
		scc_jQuery('html, body').animate({
			scrollTop: scc_jQuery($this).parent().parent().find('.selslideropt_3').offset().top
		}, 1000);
}
function cancelSliderInfoModal(){
	scc_jQuery('#modalSliderInfo').modal('hide')
}
function removeSlider($this) {
	console.log(scc_jQuery($this).parent().parent().parent().parent())
	if (scc_jQuery($this).parent().parent().parent().parent().find('.inputoption_slidchk').is(':checked')){
		scc_jQuery($this).parent().parent().parent().parent().find('.inputoption_slidchk').prop('checked', false);
	} else {
		scc_jQuery($this).parent().parent().parent().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>'
		scc_jQuery('#slider_info_modal').html(code)
		scc_jQuery('#modalSliderInfo').modal('show')
	}
	scc_jQuery($this).parent().parent().parent().parent().find('.selslideropt_3').slideToggle();
	scc_jQuery('html, body').animate({
		scrollTop: scc_jQuery($this).parent().parent().parent().parent().find('.selslideropt_3').offset().top
	}, 1000);
}
  /*
+  custom math functions
+*/
function addCustomMath($this) {
	scc_jQuery($this).parent().parent().find('.scc_custom_math').slideToggle()
	scc_jQuery('html, body').animate({
		scrollTop: scc_jQuery($this).parent().parent().find('.scc_custom_math').offset().top
	}, 1000);
	if (scc_jQuery($this).parent().find('.scc_custom_math_checkbox').is(':checked'))
		scc_jQuery($this).parent().find('.scc_custom_math_checkbox').attr('checked', false);
	else {
		scc_jQuery($this).parent().find('.scc_custom_math_checkbox').attr('checked', true);
	}
}
function removeCustomMath($this) {
	console.log('removeCustomMath -> I will to slideToggle()',scc_jQuery($this).parent().parent().parent())
	scc_jQuery($this).parent().parent().parent().parent().find('.scc_custom_math').slideToggle();
	if (scc_jQuery($this).parent().find('.scc_custom_math_checkbox').is(':checked'))
		scc_jQuery($this).parent().find('.scc_custom_math_checkbox').attr('checked', false);
	else {
		scc_jQuery($this).parent().find('.scc_custom_math_checkbox').attr('checked', true);
	}
}
  /*
    custom math functions
    */
    function AaddSlider($this) {
    	scc_jQuery($this).parent().parent().find('.selslideropt_4').slideToggle();
    }
    function addAnotherSwitch($this) {
    	var i = 0;
    	scc_jQuery($this).parent().parent().find(' .switchoption_3').each(function() {
    		i++;
    	});
    	scc_jQuery($this).parent().parent().find('.switchoption_2').append(scc_jQuery('#switchoption .switchoption_2').html().replace(/XXYYXX/g, ((i / 1) + 1)));
    }
    function addAnotherButton($this) {
    	var i = 0;
    	scc_jQuery($this).parent().parent().find(' .buttonoption_3').each(function() {
    		i++;
    	});
    	scc_jQuery($this).parent().parent().find('.buttonoption_2').append(scc_jQuery('#buttonoption .buttonoption_2').html().replace(/XXYYXX/g, ((i / 1) + 1)));
    }
    function addAnotherDiscount($this) {
    	scc_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;
  // scc_jQuery($this).find('.fieldDatatoAdd .selslideropt_4').each(function() {  i++; } );
  // console.log(i);
  // scc_jQuery($this).parent().parent().find('.fieldDatatoAdd .selslideropt_3').append( scc_jQuery('#AsliderOption .selslideropt_3').html().replace(/XXYYXX/g, (( i / 1) + 1)) );
}
function tableToJson(table) {
	var TableData = new Array();
	scc_jQuery('.translate_table tr').each(function(row, tr){
		TableData[row]={
			"key" : scc_jQuery(tr).find('td:eq(0) input').val()
			, "lang" :scc_jQuery(tr).find('td:eq(1) input').val()
			, "translation" : scc_jQuery(tr).find('td:eq(2) input').val()
		}
	});
      TableData.shift();  // first row will be empty - so remove
      return TableData;
  }
  function addNewTran($this) {
  	scc_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>');
  }
  function addNewRange($this) {
  	var xmax = parseInt(scc_jQuery($this).parent().parent().find('.price_table .sliderinputoption_2:last').val());
  	scc_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;margin-top:5px;height:40px;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();
  }
  function getPriceRangeInputs() {
  	return scc_jQuery("#allinputstoadd .price_table .sliderinputoption_2");
  };
  function setRelativePrice(maxInput) {
  	maxVal = parseInt(scc_jQuery(maxInput).val());
  	nextCell = scc_jQuery(maxInput).closest('tr').next().find('.sliderinputoption');
  	nextCellMin = parseInt(nextCell.val());
  	return nextCell.val(maxVal + 1);
  };
  function sliderPriceRangeInit() {
  	scc_jQuery.each(getPriceRangeInputs(), (i, elem) => {
  		scc_jQuery(elem).change(() => {
  			setRelativePrice(elem);
  		});
  		scc_jQuery(elem).on("input", (() => {
  			setRelativePrice(elem);
  		}));
  	});
  };
  scc_jQuery("#allinputstoadd .price_table .sliderinputoption_2").change(function() {
  	var ind = parseInt(scc_jQuery("#allinputstoadd .price_table .sliderinputoption_2").index(this));
  	var maxrange = parseInt(scc_jQuery("#allinputstoadd .price_table .sliderinputoption_2:eq(" + ind + ")").val());
  	var minrange = parseInt(scc_jQuery("#allinputstoadd .price_table .sliderinputoption:eq(" + ind + ")").val());
  	var maxrange1 = parseInt(scc_jQuery("#allinputstoadd .price_table .sliderinputoption_2:eq(" + (ind + 1) + ")").val());
  	if (maxrange1 != NaN) {
  		if (maxrange <= minrange) {
  			scc_jQuery("#allinputstoadd .price_table .sliderinputoption_2:eq(" + (ind) + ")").val(minrange + 100);
  			scc_jQuery("#allinputstoadd .price_table .sliderinputoption:eq(" + (ind + 1) + ")").val(minrange + 101);
  		} else
  		scc_jQuery("#allinputstoadd .price_table .sliderinputoption:eq(" + (ind + 1) + ")").val(maxrange + 1);
  	}
  });
  function remove_row($this) {
  	var maxrange = scc_jQuery($this).parent().parent().next().find('.sliderinputoption_2').val();
  	var maxrange1 = parseInt(scc_jQuery($this).parent().parent().prev().find('.sliderinputoption_2').val());
  	if (maxrange != undefined)
  		scc_jQuery($this).parent().parent().next().find('.sliderinputoption').val((maxrange1 + 1));
  	scc_jQuery($this).parent().parent().remove();
  }
  function remove_rowTran($this) {
  	scc_jQuery($this).parent().parent().remove();
  }
  function remove_field($this) {
  	scc_jQuery($this).parent('div').remove();
  }
  function addOptiontoSlider($this) {
  	var i = 0;
  	scc_jQuery($this).parent().parent().parent().find('.fieldDatatoAdd .selslideropt_2 .selslideropt_3').each(function() {
  		i++;
  	})
  	scc_jQuery($this).parent().parent().parent().find('.fieldDatatoAdd .selslideropt_2').append("<hr />" + scc_jQuery('#sliderOption .selslideropt_2').html().replace(/XXYYXX/g, ((i / 1) + 1)));
  }
  function addaOptiontoSlider($this) {
  	var i = 0;
  // console.log(scc_jQuery($this).parent().parent().parent().parent().find('.fieldDatatoAdd .selslideropt_2').get());
  //        scc_jQuery($this).parent().parent().parent().find('.fieldDatatoAdd .selslideropt_2').append("<div Class=Test>");
  scc_jQuery($this).parent().parent().parent().find('.fieldDatatoAdd .selslideropt_2 .selslideropt_3').each(function() {
  	i++;
  })
  scc_jQuery($this).parent().parent().parent().find('.fieldDatatoAdd .selslideropt_2').append(" <hr />" + scc_jQuery('#AsliderOption .selslideropt_2').html().replace(/XXYYXX/g, ((i / 1) + 1)));
} //.replace(/hide1/g, "hide"+(i + 1)) );
function addOptiontoSelect($this) {
	var i = 0;
	scc_jQuery($this).parent().parent().find('.content .selectoption_2 .selopt3').each(function() {
		i++;
	})
	scc_jQuery($this).parent().parent().find('.content .selectoption_2').append(scc_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;
}
/* old version getFieldOptionx()
function getFieldOptionx($f) {
  var fieldOpt = scc_jQuery($f).val(); //we fetch the HTML using the IDs:
  var fieldStyle = scc_jQuery($f).parent().parent().parent().find('.fieldstyle');
  switch (fieldOpt) {
    case "titledesc":
      fieldOpt = scc_jQuery('#titledescdiv').html();
      fieldStyle.html('');
      break;
    case "sliderinput":
      fieldOpt = scc_jQuery('#sliderOption').html();
      fieldStyle.html('');
      break;
    case "Asliderinput":
      fieldOpt = scc_jQuery('#AsliderOption').html();
      fieldStyle.html('');
      break;
    case "switchinput":
      fieldOpt = scc_jQuery('#switchoption').html().replace(/XXYYXX/g, 1);
      //                fieldStyle.html(scc_jQuery('#checkboxstyle').html());
      break;
    case "dropdowninput":
      fieldOpt = scc_jQuery('#selectoption').html().replace(/XXYYXX/g, 1);
      fieldStyle.html('');
      break;
    case "simplebuttons":
      fieldOpt = scc_jQuery('#buttonoption').html().replace(/XXYYXX/g, 1);
      fieldStyle.html('');
      break;
    default:
      fieldOpt = scc_jQuery('#inputoptiontext').html();
      fieldStyle.html('');
  }
  var finalParent = scc_jQuery($f).parent()
  //var finalParent = scc_jQuery('#subsection-to-add')
  finalParent.html(fieldOpt);
}
*/
function getFieldOptionx($f, optionValue) {
  var fieldOpt = scc_jQuery($f).val(); //we fetch the HTML using the IDs:
  var fieldStyle = scc_jQuery($f).parent().parent().parent().find('.fieldstyle');
  demo = scc_jQuery('#scc-demover').attr('data-demo');
  var elementsAdded = scc_jQuery('.elements_added') ? scc_jQuery('.elements_added').length : 0
  if(scc_jQuery('.selslideropt_3')){
  	if(scc_jQuery('.selslideropt_3').css('display') === 'block'){
  		elementsAdded++
  	}
  }
  switch (fieldOpt) {
  	case "titledesc":
  	fieldOpt = scc_jQuery('#titledescdiv').html();
  	fieldStyle.html('');
  	break;
  	case "sliderinput":
  	fieldOpt = scc_jQuery('#sliderOption').html();
  	fieldStyle.html('');
  	break;
  	case "Asliderinput":
  	fieldOpt = scc_jQuery('#AsliderOption').html();
  	fieldStyle.html('');
  	break;
  	case "switchinput":
  	fieldOpt = scc_jQuery('#switchoption').html().replace(/XXYYXX/g, 1);
          //                fieldStyle.html(scc_jQuery('#checkboxstyle').html());
          break;
          case "dropdowninput":
          fieldOpt = scc_jQuery('#selectoption').html().replace(/XXYYXX/g, 1);
          fieldStyle.html('');
          break;
          case "simplebuttons":
          fieldOpt = scc_jQuery('#buttonoption').html().replace(/XXYYXX/g, 1);
          fieldStyle.html('');
          break;
          case "comment_input":
          fieldOpt = scc_jQuery('#comment_option').html().replace(/XXYYXX/g, 1);
          fieldStyle.html('');
          break;
          case "number_input":
          fieldOpt = scc_jQuery('#number_option').html().replace(/XXYYXX/g, 1);
          fieldStyle.html('');
          break;
          default:
          fieldOpt = scc_jQuery('#inputoptiontext').html();
          fieldStyle.html('');
      }
      var finalParent = scc_jQuery($f).closest('.boardOption')
      fieldOpt = '<div class="elements_added">' + fieldOpt + '</div>'
      var subSection = scc_jQuery(finalParent.find('.subsection-area')[0]).append(fieldOpt)
      var createdElement = subSection.find('.elements_added:last');
      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(scc_jQuery($f).val() === "switchinput"){
      	scc_jQuery(finalParent.find('.fieldFormat')[finalParent.find('.fieldFormat').length - 1]).children('option').each( function() {
      		console.log('inside', scc_jQuery(this).val())
      		console.log('optionValue', optionValue)
      		if(Number(scc_jQuery(this).val()) === Number(optionValue)){
      			scc_jQuery(this).prop('selected', true)
      		}
      	})
      }
      /*
        scroll to the new element added START
        */
        scc_jQuery('html, body').animate({
        	scrollTop: scc_jQuery(finalParent.find('.elements_added:last')).offset().top
        }, 1000);
      /*
        scroll to the new element added END
        */
        if(window.hasOwnProperty("addSortableFeatureEachElement")){
        	addSortableFeatureEachElement(false)
        }
        scc_jQuery($f).parent().hide(300);
        scc_jQuery($f).parent().prev().show(300);
    }
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;
}
function ElementArray(No, title, name, value1, value2,mandatory,column_dskp,column_mobl, opt_default, inputBoxVariant) {
	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;
	opt_default ? this.opt_default = opt_default : null;
	this.inputBoxVariant = inputBoxVariant;
}
function InputOptions (element,type,value,length, mandatory){
	this.element = element;
	this.type = type;
	this.value = value;
	this.length = length;
	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
function previewDropDown($this) {
	var fieldDesc = scc_jQuery($this).find('.fieldDescription').val();
	var fieldName = scc_jQuery($this).find('.fieldServiceName').val();
	var theHTML = (fieldName != '') ? "<div><label>" + fieldName + "</label>" : '<div>';
	theHTML += (fieldDesc != '') ? "<div>" + fieldDesc + "</div>" : '';
	theHTML += '<select>';
	scc_jQuery($this).find('.selectoption_2').find('.selopt3').each(function() {
		theHTML += "<option value='" + scc_jQuery(this).find('.inputoption_2').val() + "'>" + scc_jQuery(this).find('.inputoption').val() + "</option>";
	});
	theHTML += '</select></div><br />';
	return theHTML;
}
function previewFields() {
	var previewhtml = '';
	scc_jQuery('#allinputstoadd .addedFieldsStyle').each(function() {
		var geptionx = scc_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);
		}
	});
	scc_jQuery('#previewInputsAdd').html("<hr /><br />" + previewhtml);
}
function fieldsToEdit(fields) {
	numberOfFields = fields;
}
function wait(ms) {
	var start = new Date().getTime();
	var end = start;
	while (end < start + ms) {
		end = new Date().getTime();
	}
}
function addAnotherField() {
	numberOfFields = scc_jQuery('#allinputstoadd .addedFieldsStyle').length;
	demo = scc_jQuery('#scc-demover').attr('data-demo');
	scc_jQuery('#scc-demover').html('').fadeOut();
  // scc_jQuery('#scc-wp-footer').fadeOut();console.log(numberOfFields);
  // if (numberOfFields != 1)
  // {
  //      scc_jQuery('.down:eq('+(numberOfFields-2)+')').css("display", "block");
  // }
  var theOpt = scc_jQuery('#inputtoadd').html();
  scc_jQuery('#allinputstoadd').append(theOpt);
  scc_jQuery('#allinputstoadd').find('.title_section_no_edit').text('Section Name')
  scc_jQuery('#allinputstoadd').find('.description_section_no_edit').text('Description')
  resort_updown();
  scc_jQuery('.scc_new_subsec').click();
  scc_jQuery('.getfieldoptionx').click(function() {
  	var fieldOpt = scc_jQuery(this).val();
  	secondStep(this, fieldOpt, 'ascend')
  });
  scc_jQuery(this).addClass("omsairam");
}
function addAnotherElement($this) {
  //numberOfElements++;
  demo = scc_jQuery('#scc-demover').attr('data-demo');
  console.log(demo);
  var xnumberOfFields = scc_jQuery('#allinputstoadd .boardOption').length;
  if(xnumberOfFields == 0){
  	scc_jQuery('.speech-bubble').show();
  }
  var thh = scc_jQuery($this).parent().parent().parent().parent().find('.fieldDatatoAdd');
  var theOpt = scc_jQuery('#fieldDatatoAdd').html();
  var theOpt1 = scc_jQuery('#fieldDatatoAdd11').html();
    // scc_jQuery($this).parent().parent().parent().find('.boardOption1').html(theOpt1);
    // thh.append(theOpt);
    scc_jQuery($this).parent().parent().parent().find('.boardOption1').remove();
    thh.append(theOpt1+ theOpt);
}
function addAnotherElement1($this) {
	var theOpt = scc_jQuery('#fieldDatatoAdd').html();
	var theOpt1 = scc_jQuery('#fieldDatatoAdd11').html();
	scc_jQuery($this).find('.boardOption1').remove();
	scc_jQuery($this).find('.fieldDatatoAdd').append(theOpt1+theOpt);
}
function addAnotherOption($this) {
	numberOfSections = scc_jQuery('#allinputstoadd .BodyOption').length;
	demo = scc_jQuery('#scc-demover').attr('data-demo');
	var theOpt = scc_jQuery('#form-line').html();
	scc_jQuery($this).parent().parent().find('.form-line').append(theOpt);
}
function previewSlider($this) {
	var theHTML = '<div>';
	var fieldServiceName = scc_jQuery($this).find('.fieldServiceName').val();
	var fieldDescription = scc_jQuery($this).find('.fieldDescription').val();
	var min = scc_jQuery($this).find('.inputoption').val();
	var max = scc_jQuery($this).find('.inputoption_2').val();
	var step = scc_jQuery($this).find('.inputoption_3').val();
	var defaultValue = scc_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;
}
function previewSwitch($this) {
	var fieldDesc = scc_jQuery($this).find('.fieldDescription').val();
	var fieldName = scc_jQuery($this).find('.fieldServiceName').val();
	var price = scc_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;
}
function removeField($f) {
	numberOfFields--;
	scc_jQuery($f).parent().parent().remove();
	resort_updown();
}
function removeField3($f) {
	numberOfElements--;
	console.log('removeField3')
	scc_jQuery($f).parent().remove();
	resort_updown();
}
function removeField2($f) {
	numberOfSections--;
	scc_jQuery($f).parent().remove();
 /*
 scc_jQuery($f).addClass("scc_crr_sbsctn");
 scc_jQuery($f).next().next().addClass('scc_crr_clps');
//   scc_jQuery($f).parent().remove()
 scc_jQuery($f).next().remove();
 scc_jQuery($f).next().next().remove();
 scc_jQuery('.scc_crr_clps').remove();
 scc_jQuery('.scc_crr_sbsctn').remove();
  scc_jQuery('.elements_added').each(function(i, obj){
      if(scc_jQuery(obj).children()){
        if(scc_jQuery(obj).children().length === 1 ){
          scc_jQuery(obj).remove()
        }
      }
  })
  */
  resort_updown();
}
function colla($this) {
	var siggn = scc_jQuery($this).text() == "-" ? "+" : "-";
	scc_jQuery($this).text(siggn);
	scc_jQuery($this).parent().find('.content').slideToggle({duration: 200, done: ({elem}) => {
		var targetElement = jQuery(elem);
		if (targetElement.is(':hidden')) {
			targetElement.parent().css({paddingBottom: '0', border: 'unset'});
		}
		if (targetElement.is(':visible')) {
			targetElement.parent().css({border: '2px solid #8a99f8'});
				// targetElement.prev().css({border: '2px solid #8a99f8', borderBottomStyle: 'hidden'});
			}
		}
	});
  // scc_jQuery($this).parent().find('.selopt5').slideToggle(200);
  if(scc_jQuery($this).data('collapseSectionType') == 'slider_element') {
  	scc_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"
						}
					});
				}
			}
		});
  }
}
function resetFields() {
	scc_jQuery('#allinputstoadd').html('');
	scc_jQuery('#previewInputsAdd').html('');
}
var demo_calculators_instance_limit = 20
function saveFields(isLicensed, demo_calculators_already_done, isEditing) {
  if(isEditing || !isEditing && (isLicensed || demo_calculators_already_done < demo_calculators_instance_limit)){ // for licensed users and demo users with free calculators yet
  	var fieldName = scc_jQuery('#costcalculatorname').val();
  	if (fieldName.trim() == '')
  	{
  		scc_jQuery('#themainwarning').html('Calculator must have a name');
  		return;
  	} else { scc_jQuery('#themainwarning').html(''); }
  	var fontType = scc_jQuery("#scc_fonttype").val().trim();
  	var colorPicker = scc_jQuery("#colorPicker").val();
  	var servicepricefontsize = scc_jQuery('#servicepricefontsize').val();
  	var title_fontType = scc_jQuery("#titlescc_fonttype").val().trim();
  	var title_colorPicker = scc_jQuery("#titlecolorPicker").val();
  	var title_servicepricefontsize = scc_jQuery('#titlepricefontsize').val();
        //var fontType = scc_jQuery("#scc_fonttype").val();
        var objectColorPicker = scc_jQuery("#objectcolorPicker").val();
        var objectServicepricefontsize = scc_jQuery('#objectservicepricefontsize').val();
        var adminsettingsid = scc_jQuery('#adminsettingsid').attr('data-calculator_id');
        // var costcalculatordescription = scc_jQuery('#costcalculatordescription').val();
        var objectsendquote = scc_jQuery("#scc_send_quote:checked").val();
        var objectdetailedlist = scc_jQuery("#scc_detailed_list:checked").val();
        var objectsaveicon = scc_jQuery("#scc_save_icon:checked").val();
        var objectscctax = scc_jQuery("#turn_off_tax:checked").val();
        var toggle_boxshadow_style2 = scc_jQuery("#toggle_boxshadow_style2:checked").val() || '';
        var objectscccoupon = scc_jQuery("#turn_off_coupon:checked") && scc_jQuery("#turn_off_coupon:checked").val() ? scc_jQuery("#turn_off_coupon:checked").val() : '';
        var objecttaxrate = scc_jQuery("#scc_tax_amount").val();
        var objectscccurrencylabel = scc_jQuery("#scc_remove_currency_label:checked").val();
        var objectscctitlelabel = scc_jQuery("#scc_remove_detailed_list_title:checked").val();
        var objectscctotalprice = scc_jQuery("#scc_remove_total_price_frntd:checked").val();
        var objecttotalpricestyle = scc_jQuery(".scc_total_price_style_view").val();
        var currency_style = scc_jQuery(".scc_currency_style").val()
        var form_field_style = scc_jQuery('select[name="form_field_style"]').val();
        var objecttotalword = scc_jQuery("#scc_change_total_word").val();
        var objectdetailedlistword = scc_jQuery("#scc_change_detailed_list_word").val();
        var objectsendquoteword = scc_jQuery("#scc_change_send_quote_word").val();
        var objectscctotalpricefloat = scc_jQuery("#turn_on_total_price_float:checked").val();
        var fieldstosend = [['name', 'description']];
        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 = ''
        if(scc_jQuery('#paypal_checkbox').prop('checked')){
        	paypal_checked = scc_jQuery('#paypal_checkbox').prop('checked')
        	paypal_email = scc_jQuery('#paypal_email').val()
        	paypal_shopping_cart_name = scc_jQuery('#paypal_shopping_cart_name').val()
        	paypal_currency = scc_jQuery('#paypal_currency').val()
        }
        var emptyValuesError = false
        scc_jQuery('#allinputstoadd .addedFieldsStyle').each(function() {
        	var sliderChecked = 0;
        	var elementOption = scc_jQuery(this).find('.boardOption').length;
        	if (elementOption != 0) {
        		var elementNo = 0;
        		var allfieldOptions2 = [];
        		scc_jQuery(this).find('.boardOption').each(function(){
        			var allfieldOptions = [];
        			var is = 0;
        			scc_jQuery(this).find('.BodyOption').each(function() {
        				scc_jQuery(this).find('.content').each(function() {
        					var fieldType = scc_jQuery(this).attr('value');
        					var count = 0;
        					var allfieldOptions1 = [];
        					switch (fieldType) {
        						case "buttonoption":
        						var fieldButtonServiceName = scc_jQuery(this).find('.inputbuttonservice_title').val();
        						var s_length = scc_jQuery(this).find('.buttonoption_3').length;
        						console.log('s_length', s_length)
        						scc_jQuery(this).find('.buttonoption_3').each(function() {
        							buttonError = validateSwitch(scc_jQuery(this).parent().parent(), scc_jQuery(this).find('.buttoninputoption').val(), scc_jQuery(this).find('.buttoninputoption_2').val());
        							if (buttonError === true) {
        								return;
        							}
        							allfieldOptions1[count] = new ElementArray(count, fieldButtonServiceName, scc_jQuery(this).find('.buttoninputoption').val(), scc_jQuery(this).find('.buttoninputoption_2').val(), 0);
        							count++;
        						});
        						allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length);
        						console.log(allfieldOptions);
        						is++;
        						break;
        						case "switchoption":
        						var s_length = scc_jQuery(this).find('.switchoption_3').length;
        						var s_type = scc_jQuery(this).find('.fieldFormat').val();
        						var isMandatory = scc_jQuery(this).find('[name="chkbx-mandatory"]').prop('checked') || false;
        						scc_jQuery(this).find('.switchoption_3').each(function() {
        							switchError = validateSwitch(scc_jQuery(this).parent().parent(), scc_jQuery(this).find('.switchinputoption').val(), scc_jQuery(this).find('.switchinputoption_2').val());
        							if (switchError === true) {
        								emptyValuesError = switchError
        								return;
        							}
        							if(scc_jQuery(this).parent().parent().find('.scc_title_column_dskp_chkbx').val() != ''){
        								var scc_title_column_dskp_chkbx = scc_jQuery(this).parent().parent().find('.scc_title_column_dskp_chkbx').val();
        							}
        							if(scc_jQuery(this).parent().parent().find('.scc_title_column_mobl_chkbx').val() != ''){
        								var scc_title_column_mobl_chkbx = scc_jQuery(this).parent().parent().find('.scc_title_column_mobl_chkbx').val();
        							}
        							allfieldOptions1[count] = new ElementArray(count, 0, scc_jQuery(this).find('.switchinputoption').val(), scc_jQuery(this).find('.switchinputoption_2').val(), s_type,'',scc_title_column_dskp_chkbx, scc_title_column_mobl_chkbx, scc_jQuery(this).find('.col-xs-2.col-md-2.tooltipadmin-left[data-selected="true"]').length ? true : false );
        							count++;
        						});
        						allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length, isMandatory );
        						is++;
        						break;
        						case "selectoption":
                      var fieldDropServiceName = scc_jQuery(this).find('.inputoption_title').val(); //inputoption_title
                      if(scc_jQuery(this).find('.scc_mandatory_dropdown').prop('checked')){
                      var dropdownServiceMandatory = 'yes'; //mandatory dropdown
                  }else{
                      var dropdownServiceMandatory = 'no'; //mandatory dropdown
                  }
                  if(scc_jQuery(this).find('.selopt3').parent().parent().find('.scc_title_column_dskp').val() != ''){
                  	var scc_title_column_dskp = scc_jQuery(this).find('.selopt3').parent().parent().find('.scc_title_column_dskp').val();
                  }
                  if(scc_jQuery(this).find('.selopt3').parent().parent().find('.scc_title_column_mobl').val() != ''){
                  	var scc_title_column_mobl = scc_jQuery(this).find('.selopt3').parent().parent().find('.scc_title_column_mobl').val();
                  }
                  var s_length = scc_jQuery(this).find('.selopt3').length;
                      var $thisDropDown = this; //inside the each loop, this will have a different value
                      scc_jQuery(this).find('.selopt3').each(function() {
                      	dropdownError = validateDropDown(fieldDropServiceName, $thisDropDown, scc_jQuery(this).find('.inputoption').val(), scc_jQuery(this).find('.inputoption_2').val(),dropdownServiceMandatory);
                      	if (dropdownError === true) {
                      		emptyValuesError = dropdownError
                      		return;
                      	}
                      	allfieldOptions1[count] = new ElementArray(count, fieldDropServiceName, scc_jQuery(this).find('.inputoption').val(), scc_jQuery(this).find('.inputoption_2').val(), scc_jQuery(this).find('.inputoption_desc').val(),dropdownServiceMandatory,scc_title_column_dskp,scc_title_column_mobl, scc_jQuery(this).find('.col-xs-2.col-md-2.tooltipadmin-left[data-selected="true"]').length ? true : false);
                      	count++;
                      });
                      allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length);
                      is++;
                      break;
                      case "comment_option":
                      var fieldCommentName = scc_jQuery(this).find('.inputoption_title').val(); //inputoption_title
                      if(scc_jQuery(this).find('.scc_mandatory_comment').prop('checked')){
                      var commentMandatory = 'yes'; //mandatory dropdown
                  }else{
                      var commentMandatory = 'no'; //mandatory dropdown
                  }
                  var s_length = scc_jQuery(this).find('.selopt5').length;
                  console.log("s_length", s_length)
                      var $thisDropDown = this; //inside the each loop, this will have a different value
                      commentError = validateComment(fieldCommentName, $thisDropDown);
                      if (commentError === true) {
                      	emptyValuesError = commentError
                      	return;
                      }
                      scc_jQuery(this).find('.selopt5').each(function() {
                      //  dropdownError = validateDropDown(fieldCommentName, $thisDropDown, scc_jQuery(this).find('.inputoption').val(), scc_jQuery(this).find('.inputoption_2').val(),dropdownServiceMandatory);
                      //  if (dropdownError === true) {
                      //    return;
                      //  }
                      if(scc_jQuery(this).parent().find('.styled-accordion:eq(0) .scc_title_column_dskp_cmntbx').val() != ''){
                      	var scc_title_column_dskp_cmntbx = scc_jQuery(this).parent().find('.styled-accordion:eq(0) .scc_title_column_dskp_cmntbx').val();
                      }
                      if(scc_jQuery(this).parent().find('.styled-accordion:eq(0) .scc_title_column_mobl_cmntbx').val() != ''){
                      	var scc_title_column_mobl_cmntbx = scc_jQuery(this).parent().find('.styled-accordion:eq(0) .scc_title_column_mobl_cmntbx').val();
                      }
                      allfieldOptions1[count] = new ElementArray(count, fieldCommentName, scc_jQuery(this).find('.inputoption').val(), scc_jQuery(this).find('.inputoption_2').val(), scc_jQuery(this).find('.inputoption_desc').val(),commentMandatory,scc_title_column_dskp_cmntbx, scc_title_column_mobl_cmntbx);
                      count++;
                  });
                      allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length);
                      is++;
                      break;
                      case "number_option":
                          var fieldNumberName = scc_jQuery(this).find('.inputoption_title').val(); //inputoption_title
                          if(scc_jQuery(this).find('.scc_mandatory_number').prop('checked')){
                          var numberMandatory = 'yes'; //mandatory dropdown
                      }else{
                          var numberMandatory = 'no'; //mandatory dropdown
                      }
                      var s_length = scc_jQuery(this).find('.selopt3').length;
                      var getInputBoxVariant = scc_jQuery(this).find('[name="quantity-input--style-selection"]').val();
                          var $thisDropDown = this; //inside the each loop, this will have a different value
                          commentError = validateQuantityBox(fieldNumberName, $thisDropDown, scc_jQuery(this).find('.inputoption_2').val());
                          if (commentError === true) {
                          	emptyValuesError = commentError
                          	return;
                          }
                          scc_jQuery(this).find('.selopt3').each(function() {
                          //  dropdownError = validateDropDown(fieldNumberName, $thisDropDown, scc_jQuery(this).find('.inputoption').val(), scc_jQuery(this).find('.inputoption_2').val(),dropdownServiceMandatory);
                          //  if (dropdownError === true) {
                          //    return;
                          //  }
                          if(scc_jQuery(this).parent().parent().find('.styled-accordion:eq(0) .scc_title_column_dskp_numbx').val() != ''){
                          	var scc_title_column_dskp_numbx = scc_jQuery(this).parent().parent().find('.styled-accordion:eq(0) .scc_title_column_dskp_numbx').val();
                          }
                          if(scc_jQuery(this).parent().parent().find('.styled-accordion:eq(0) .scc_title_column_mobl_numbx').val() != ''){
                          	var scc_title_column_mobl_numbx = scc_jQuery(this).parent().parent().find('.styled-accordion:eq(0) .scc_title_column_mobl_numbx').val();
                          }
                          allfieldOptions1[count] = new ElementArray(count, fieldNumberName, scc_jQuery(this).find('.inputoption').val(), scc_jQuery(this).find('.inputoption_2').val(), scc_jQuery(this).find('.inputoption_desc').val(),numberMandatory,scc_title_column_dskp_numbx,scc_title_column_mobl_numbx, null, getInputBoxVariant);
                          count++;
                      });
                          allfieldOptions[is] = new InputOptions (is,fieldType,allfieldOptions1,s_length);
                          is++;
                          break;
                          default:
                      }
                  });
});
if(scc_jQuery(this).find('.scc_custom_math_checkbox').is(':checked')) {
                //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(scc_jQuery(this).find('.scc_custom_math_display_front_end').attr('checked') == "checked"){
                		scc_custom_math_display_front_end = true;
                	}
                	var scc_custom_math_display_detailed_list = false
                	if(scc_jQuery(this).find('.scc_custom_math_display_detailed_list').attr('checked')){
                		scc_custom_math_display_detailed_list = true
                	}
                	var custom_math_name = scc_jQuery(this).find('.scc_custom_math_name').val()
                	var custom_math_type = scc_jQuery(this).find('.scc_custom_math_type option:selected:last').val()
                	var custom_math_value = scc_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);
                is++;
            }
            if (scc_jQuery(this).find('.inputoption_slidchk').is(':checked')) {
            	sliderChecked = 1; var allfieldOptions3=[];
            	var fieldServiceName = scc_jQuery(this).find('.sliderinputoption_T').val();
            	var s_length = scc_jQuery(this).find('.price_table tbody tr').length;
            	var ktable=0;
            	sliderError = validateSlider(this, fieldServiceName)
            	if(sliderError === true) {
            		emptyValuesError = sliderError
            		return
            	}
            	if(scc_jQuery(this).find('.scc_title_column_dskp_slider').val() != ''){
            		var scc_title_column_dskp_slider = scc_jQuery(this).find('.scc_title_column_dskp_slider').val();
            	}
            	if(scc_jQuery(this).find('.scc_title_column_mobl_slider').val() != ''){
            		var scc_title_column_mobl_slider = scc_jQuery(this).find('.scc_title_column_mobl_slider').val();
            	}
            	scc_jQuery(this).find('.price_table tbody tr').each(function() {
            		allfieldOptions3[ktable] = new ElementArray(ktable, fieldServiceName, scc_jQuery(this).find('.sliderinputoption').val(), scc_jQuery(this).find('.sliderinputoption_2').val(), scc_jQuery(this).find('.sliderinputoption_5').val(),'',scc_title_column_dskp_slider,scc_title_column_mobl_slider);
            		ktable++;
            	});
                // allfieldOptions3[ktable] = new ElementArray(ktable, fieldServiceName, scc_jQuery(this).find('.sliderinputoption').val(), scc_jQuery(this).find('.sliderinputoption_2').val(), scc_jQuery(this).find('.sliderinputoption_5').val(),'',scc_title_column_dskp_slider,scc_title_column_mobl_slider);
                var step = scc_jQuery(this).find('.slidoption_3').val();
                var defaultValue = scc_jQuery(this).find('.slidoption_4').val();
                var isSlidingScale = scc_jQuery(this).find('.slider-discount-type').val() == 'sliding-scale';
                allfieldOptions2[elementNo] = new SubOptions(elementNo,allfieldOptions, allfieldOptions3, step, defaultValue, isSlidingScale);
            }
            else {
            	sliderChecked = 0;
            	allfieldOptions3 = [];
            	allfieldOptions2[elementNo] = new SubOptions(elementNo, allfieldOptions, allfieldOptions3, 0, 0, isSlidingScale);
            }
            elementNo++;
        });
      //         console.log(allfieldOptions2);
  }
  else {
  	var allfieldOptions2 = [];
  }
  var showSectionTotal = scc_jQuery(this).find('input[name="scc-section-total"]').prop('checked') || false;
  SectionName[a] = new sliderOptions(scc_jQuery(this).find('.sectiontitle').val(), scc_jQuery(this).find('.sectionDescription').val().replace(/(\r\n|\n|\r)/gm,'<br />') + (scc_jQuery(this).find('.scc_accordion_section').prop("checked") ? '///accordion:yes///' : ''),a,allfieldOptions2, showSectionTotal);
  a++;
});
var dict = tableToJson(scc_jQuery('#allinputstoadd').find('.translate_table tbody'));
if(!switchError || !dropdownError || !buttonError){
	var data = {
		action: 'sccSaveField',
		objectColorPicker: objectColorPicker,
		objectServicepricefontsize: objectServicepricefontsize,
		title_fontType: title_fontType,
		title_colorPicker: title_colorPicker,
		title_servicepricefontsize: title_servicepricefontsize,
		objectsendquote: objectsendquote,
		objectdetailedlist: objectdetailedlist,
		objectsaveicon: objectsaveicon,
		toggle_boxshadow_style2: toggle_boxshadow_style2,
		objectscctax: objectscctax,
		objecttaxrate: objecttaxrate,
		objectscccoupon: objectscccoupon,
		objectscccurrencylabel: objectscccurrencylabel,
		objectscctitlelabel: objectscctitlelabel,
		objectscctotalprice: objectscctotalprice,
		objecttotalpricestyle: objecttotalpricestyle,
		objecttotalword: objecttotalword,
		objectdetailedlistword: objectdetailedlistword,
		objectsendquoteword: objectsendquoteword,
		objectscctotalpricefloat: objectscctotalpricefloat,
		paypal_checked: paypal_checked,
		paypal_email: paypal_email,
		paypal_shopping_cart_name: paypal_shopping_cart_name,
		paypal_currency: paypal_currency,
		currency_style: currency_style,
		fontType: fontType.toString(),
		colorPicker: colorPicker,
		servicepricefontsize: servicepricefontsize,
		adminsettingsid: adminsettingsid,
		fieldname: fieldName,
		fieldPreview: JSON.stringify(SectionName),
            // fieldform: Base64.encode(JSON.stringify(scc_jQuery('#allinputstoadd').html().trim())),
     //       fieldform: "",
     dictionary: JSON.stringify(dict),
     form_field_style: form_field_style,
 };
 var $fragment_refresh = {
 	url: rt_vars.rt_urlajax,
 	type: 'POST',
 	data: data,
 	success: function( data ) {
 		location.href = rt_vars.rt_adminurl + '?page=edit_sccbyid&id=' + data.trim();
 	}
 };
 if(!emptyValuesError){
 	console.log('emptyValuesError', emptyValuesError)
 	document.getElementById("scc-editing-area-loading") ? document.getElementById("scc-editing-area-loading").style.width = "100%" : null;
 	scc_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(scc_jQuery(element).children("option:selected"). val() == 'style_1') {
		scc_jQuery('#toggle_boxshadow_style2').css('display','none')
	}else {
		scc_jQuery('#toggle_boxshadow_style2').css('display','block')
	}
}
function setDefaultOption(elem) {
	let optBtn = scc_jQuery(elem)
	optBtn.attr("data-selected") ? optBtn.css( "background-color", "#F0F0F0" ).removeAttr('data-selected').attr('data-tooltip', 'Click me to make this option default.') : optBtn.css('background-color', '#56b665').removeAttr('data-tooltip').attr('data-selected', true)
  // scc_jQuery(elem).css('background-color', '#56b665').removeAttr('data-tooltip').attr('data-selected', true)
  optRoot = scc_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 to make this option default.')
}
function secondStep($this, fieldOpt, ascdesc) {
	switch (fieldOpt) {
		case "sliderinput":
		fieldOpt = scc_jQuery('#sliderOption').html().replace(/XXYYXX/g, 1);
		break;
		case "Asliderinput":
		fieldOpt = scc_jQuery('#AsliderOption').html().replace(/XXYYXX/g, 1);
		break;
		case "switchinput":
		fieldOpt = scc_jQuery('#switchoption').html().replace(/XXYYXX/g, 1);
		break;
		case "dropdowninput":
		fieldOpt = scc_jQuery('#selectoption').html().replace(/ XXYYXX/g, 1);
		break;
		default:
		fieldOpt = scc_jQuery('#inputoption').html();
	}
	if (ascdesc == 'ascend') {
		scc_jQuery($this).parent().parent().parent().find('.fieldDatatoAdd').html(fieldOpt);
	} else if (ascdesc == 'descend') scc_jQuery($this).find('.fieldDatatoAdd').html(fieldOpt);
}
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
}
function sliderOptions(name, desc, section, value, showSectionTotal) {
	this.name = germanCharacters(name);
	this.desc = germanCharacters(desc);
	this.section = section;
	this.showSectionTotal = showSectionTotal || false;
	this.value = value;
}
function SubOptions(subsection, Nooptions, minmax, step, defaultValue, isSlidingScale) {
	this.subsection = subsection;
	this.Nooptions = Nooptions;
	this.minmax = minmax;
	this.step = step;
	this.defaultValue = defaultValue;
	this.isSlidingScale = isSlidingScale;
}
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) {
	scc_jQuery($this).find('.warning').html('');
	if (fieldInputName.trim() == '') {
		scc_jQuery($this).find('.warning').html('Product/Service name cannot be empty');
		return;
	}
	if (textInputVar.trim() == '' || isNaN(textInputVar)) {
		scc_jQuery($this).find('.warning').html('Error - Price Value is not numeric');
		return true;
	}
	return false;
}
function validateComment(fieldDropServiceName, $this) {
	console.log('validateComment fieldDropServiceName', fieldDropServiceName)
	scc_jQuery($this).parent().find('.warning').html('');
	if (fieldDropServiceName == '') {
		scc_jQuery($this).parent().find('.warning').html('Please, check the title. It can not be empty');
		scc_jQuery('html, body').animate({
			scrollTop: scc_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) {
	scc_jQuery($this).find('.scc_custom_math').find('.warning').html('');
	console.log(scc_jQuery($this))
	if (fieldDropServiceName == '') {
		scc_jQuery($this).find('.scc_custom_math').find('.warning').html('Please, check the title. It can not be empty');
		scc_jQuery('html, body').animate({
			scrollTop: scc_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)) {
		scc_jQuery($this).find('.scc_custom_math').find('.warning').html('Error - Price values must be numeric');
		scc_jQuery('html, body').animate({
			scrollTop: scc_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) {
	scc_jQuery($this).parent().find('.warning').html('');
	if (fieldDropServiceName == '') {
		scc_jQuery($this).parent().find('.warning').html('Please, check the title. It can not be empty');
		scc_jQuery('html, body').animate({
			scrollTop: scc_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)) {
		scc_jQuery($this).parent().find('.warning').html('Error - Price values must be numeric');
		scc_jQuery('html, body').animate({
			scrollTop: scc_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) {
	scc_jQuery($this).find('.warning').html('');
	if (fieldDropServiceName == '') {
		scc_jQuery($this).find('.warning').html('One of the names is empty');
		scc_jQuery('html, body').animate({
			scrollTop: scc_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 == '') {
		scc_jQuery($this).find('.warning').html('One of the names is empty');
		scc_jQuery('html, body').animate({
			scrollTop: scc_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)) {
		scc_jQuery($this).find('.warning').html('Error - price values must be numeric');
		scc_jQuery('html, body').animate({
			scrollTop: scc_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) {
	scc_jQuery($this).find('.warning').html('');
	if (value_1 == '') {
		scc_jQuery($this).find('.warning').html('One of the names is empty');
		scc_jQuery('html, body').animate({
			scrollTop: scc_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))) {
		scc_jQuery($this).find('.warning').html('Error - price values must be numeric');
		scc_jQuery('html, body').animate({
			scrollTop: scc_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() == '') {
		scc_jQuery($this).find('.selslideropt_3').find('.warning').html('Product/Service name cannot be empty');
		scc_jQuery('html, body').animate({
			scrollTop: scc_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 = scc_jQuery($this).find('.selslideropt_3').find('.slidoption_3').val();
	if (!step || step.trim() == '' || isNaN(step)) {
		scc_jQuery($this).find('.selslideropt_3').find('.warning').html('Step value is not numeric');
		scc_jQuery('html, body').animate({
			scrollTop: scc_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 = scc_jQuery($this).find('.selslideropt_3').find('.slidoption_4').val();
	if (!defaultValue || defaultValue.trim() == '' || isNaN(defaultValue)) {
		scc_jQuery($this).find('.selslideropt_3').find('.warning').html('Starting Number value is not numeric');
		scc_jQuery('html, body').animate({
			scrollTop: scc_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:
  scc_jQuery($this).find('.selslideropt_3').find('.sliderinputoption').each(function(index, ob){
  	var min = scc_jQuery(ob).val() == '' ? undefined : Number(scc_jQuery(ob).val());
  	if (typeof min != 'number') {
  		scc_jQuery($this).find('.selslideropt_3').find('.warning').html('Minimum value (from) is not numeric or above 0');
  		scc_jQuery('html, body').animate({
  			scrollTop: scc_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:
  scc_jQuery($this).find('.selslideropt_3').find('.sliderinputoption_2').each(function(index, ob){
  	var max = scc_jQuery(ob).val() == '' ? undefined : Number(scc_jQuery(ob).val());
  	if (typeof max != 'number') {
  		scc_jQuery($this).find('.selslideropt_3').find('.warning').html('Maximum value is not numeric');
  		scc_jQuery('html, body').animate({
  			scrollTop: scc_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:
  scc_jQuery($this).find('.selslideropt_3').find('.sliderinputoption_5').each(function(index, ob){
  	var rangePrice = scc_jQuery(ob).val() == '' ? undefined : Number(scc_jQuery(ob).val());
  	if (typeof rangePrice != 'number') {
  		scc_jQuery($this).find('.selslideropt_3').find('.warning').html('Range price value is not numeric');
  		scc_jQuery('html, body').animate({
  			scrollTop: scc_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)) {
            scc_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) ) {
          	scc_jQuery($this).find('.selslideropt_3').find('.warning').html('Minimum value has to be smaller than the maximum value')
          	scc_jQuery('html, body').animate({
          		scrollTop: scc_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) {
          	scc_jQuery($this).find('.selslideropt_3').find('.warning').html('Step Value cannot be more than the maximum value');
          	scc_jQuery('html, body').animate({
          		scrollTop: scc_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){
      	scc_jQuery($this).find('.selslideropt_3').find('.warning').html('');
      }
      return errors;
  }
  function checkIfParentIsAccordionAndOpenIt(element) {
  	if( scc_jQuery(element).parent().parent().css('display') === 'none') {
  		var section_id_raw = scc_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]
  				scc_jQuery('#section_' + section_id)[0].click()
  			}catch(err) {
  			}
  		}
  	}
  }
  function resort_updown() {
  	scc_jQuery('#allinputstoadd .down:last').css("display", "none");
  	scc_jQuery('#allinputstoadd .up:first').css("display", "none");
  	scc_jQuery('#allinputstoadd .down').not(':last').css("display", "block");
  	scc_jQuery('#allinputstoadd .up').not(':first').css("display", "block");
  	scc_jQuery('#allinputstoadd .fieldDatatoAdd .sdown:last-child').css("display", "none");
  	scc_jQuery('#allinputstoadd .fieldDatatoAdd .sup:first-child').css("display", "none");
  	scc_jQuery('#allinputstoadd .fieldDatatoAdd .sdown').not(':last').css("display", "block");
  	scc_jQuery('#allinputstoadd .fieldDatatoAdd .sup').not(':first').css("display", "block");
  }
  function remove_field($this) {
  	scc_jQuery($this).parent('div').remove();
  }
  function rup($this) {
  var wrapper = scc_jQuery($this).closest('.addedFieldsStyle'); //.closest('div');
  wrapper.insertBefore(wrapper.prev());
  resort_updown();
}
function rdown($this) {
  var wrapper = scc_jQuery($this).closest('.addedFieldsStyle');; //.closest('div');
  wrapper.insertAfter(wrapper.next());
  resort_updown();
}
function ClosePopup(){
	scc_jQuery('.hover_bkgr_fricc').hide();
}
function ClosePopup1(){
	scc_jQuery('.speech-bubble').hide();
}
function openNav() {
	document.getElementById("myNav").style.width = "100%";
}
function closeNav() {
	document.getElementById("myNav").style.width = "0%";
}
scc_jQuery(document).ready(function(){
	scc_jQuery('.scc_button_section').change(function(){
		if(scc_jQuery(this).is(":checked")) {
			scc_jQuery(this).parent().addClass("btn-selected");
		} else {
			scc_jQuery(this).parent().removeClass("btn-selected");
		}
	});
})
scc_jQuery(document).ready(function(){
	scc_jQuery('[data-toggle="tooltip"]').tooltip();
});
// COUPONS FUNCTIONS !!
window.onload = function() {
	sliderPriceRangeInit();
	if(document.getElementById('wpfooter')){
		document.getElementById('wpfooter').style='position: absolute !important'
	}
	if (!!scc_jQuery.prototype.datepicker) {
		if(scc_jQuery("#coupon_start_date")) {
			scc_jQuery("#coupon_start_date").datepicker({
				dateFormat: 'mm/dd/yy',
				onSelect: function(selected) {
					scc_jQuery("#coupon_end_date").datepicker("option","minDate", selected)
				}
			})
		}
		if(scc_jQuery("#coupon_end_date")) {
			scc_jQuery("#coupon_end_date").datepicker({
				dateFormat: 'mm/dd/yy',
				onSelect: function(selected) {
					scc_jQuery("#coupon_start_date").datepicker("option","maxDate", selected)
				}
			})
		}
	} else {
            // scc_jQuery.getScript('https://code.jquery.com/ui/1.12.0/jquery-ui.min.js', function(data) {
            //     if (!!scc_jQuery.prototype.datepicker) {
            //       if(scc_jQuery("#coupon_start_date")) {
            //         scc_jQuery("#coupon_start_date").datepicker({
            //             dateFormat: 'mm/dd/yy',
            //             onSelect: function(selected) {
            //               scc_jQuery("#coupon_end_date").datepicker("option","minDate", selected)
            //             }
            //         })
            //       }
            //       if(scc_jQuery("#coupon_end_date")) {
            //         scc_jQuery("#coupon_end_date").datepicker({
            //             dateFormat: 'mm/dd/yy',
            //             onSelect: function(selected) {
            //               scc_jQuery("#coupon_start_date").datepicker("option","maxDate", selected)
            //             }
            //         })
            //       }
            //     }
            // })
        }
        scc_jQuery('.save_button').each(function (index, value) {
        	scc_jQuery(this).css('pointer-events', 'auto')
        })
        if(typeof checkPluginCacheHasBeenLoaded === "function"){
        	checkPluginCacheHasBeenLoaded()
        }
        if(scc_jQuery('#save_coupon_modal')){
        	scc_jQuery('#save_coupon_modal').modal('show')
        }
        if(scc_jQuery('#deleted_info_coupon_modal')){
        	scc_jQuery('#deleted_info_coupon_modal').modal('show')
        }
    };
    function saveCoupon(){
    	if(couponValidation()){
    		console.log("typeof scc_jQuery('#coupon_discountpercentage').val() === 'number'",typeof Number(scc_jQuery('#coupon_discountpercentage').val()))
    		console.log("scc_jQuery('#coupon_minspend').val()",scc_jQuery('#coupon_minspend').val())
    		console.log("scc_jQuery('#coupon_minspend').val()",(scc_jQuery('#coupon_minspend').val())=== "0")
    		scc_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: scc_jQuery('#coupon_id').val(),
    				name: scc_jQuery('#coupon_name').val(),
    				code: scc_jQuery('#coupon_code').val(),
    				startdate: scc_jQuery('#coupon_start_date').val(),
    				enddate: scc_jQuery('#coupon_end_date').val(),
    				discountpercentage: typeof Number(scc_jQuery('#coupon_discountpercentage').val()) === 'number' && (scc_jQuery('#coupon_discountpercentage').val() > 0 || scc_jQuery('#coupon_discountpercentage').val() === "0") ? scc_jQuery('#coupon_discountpercentage').val() : -1,
    				discountvalue: typeof Number(scc_jQuery('#coupon_discountvalue').val()) === 'number' && (scc_jQuery('#coupon_discountvalue').val() > 0 || scc_jQuery('#coupon_discountvalue').val() === "0") ? scc_jQuery('#coupon_discountvalue').val() : -1,
    				minspend: typeof Number(scc_jQuery('#coupon_minspend').val()) === 'number' && (scc_jQuery('#coupon_minspend').val() > 0 || scc_jQuery('#coupon_minspend').val() === "0") ? scc_jQuery('#coupon_minspend').val() : -1,
    				maxspend: typeof Number(scc_jQuery('#coupon_maxspend').val()) === 'number' && scc_jQuery('#coupon_maxspend').val() > 0? scc_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)
     scc_jQuery('#coupon_saving_button').html('Saved')
 }
};
scc_jQuery.ajax( $coupon_form );
}else{
	console.log('something wrong')
}
}
function couponValidation(){
	var ok = true
	scc_jQuery('#coupon_name_error').html('')
	scc_jQuery('#coupon_code_error').html('')
	scc_jQuery('#coupon_start_date_error').html('')
	scc_jQuery('#coupon_end_date_error').html('')
	scc_jQuery('#coupon_discountpercentage_error').html('')
	scc_jQuery('#coupon_discountvalue_error').html('')
	scc_jQuery('#coupon_minspend_error').html('')
	scc_jQuery('#coupon_maxspend_error').html('')
	if(scc_jQuery('#coupon_name').val() < 2){
		scc_jQuery('#coupon_name_error').html('Invalid name')
		ok = false
	}
	if(scc_jQuery('#coupon_code').val() < 4){
		scc_jQuery('#coupon_code_error').html('Invalid coupon code. Please, 4 characters at least.')
		ok = false
	}
	if(scc_jQuery('#coupon_start_date').val().length != 10){
		scc_jQuery('#coupon_start_date_error').html('Invalid start date. Please, use the datepicker to add the date.')
		ok = false
	}
	if(scc_jQuery('#coupon_end_date').val().length != 10){
		scc_jQuery('#coupon_end_date_error').html('Invalid end date. Please, use the datepicker to add the date.')
		ok = false
	}
	if(scc_jQuery('#coupon_discountpercentage').val() < 0 || scc_jQuery('#coupon_discountpercentage').val() >100){
		scc_jQuery('#coupon_discountpercentage_error').html('Discount percentage has to be between 0 and 100.')
		ok = false
	}
	if(scc_jQuery('#coupon_discountvalue').val() < 0 ){
		scc_jQuery('#coupon_discountvalue_error').html('Discount value has to be more than 0.')
		ok = false
	}
	if((typeof Number(scc_jQuery('#coupon_discountpercentage').val()) === 'number'
		&& typeof Number(scc_jQuery('#coupon_discountvalue').val()) === 'number')
		&&  Number(scc_jQuery('#coupon_discountpercentage').val()) > 0
		&&  Number(scc_jQuery('#coupon_discountvalue').val()) > 0){
		scc_jQuery('#coupon_discountpercentage_error').html('Please, Add only one type of discount. (delete value to remove the discount type)')
	scc_jQuery('#coupon_discountvalue_error').html('Please, Add only one type of discount. (delete value to remove the discount type)')
	ok = false
}
if(( (scc_jQuery('#coupon_discountpercentage').val() === 0 || scc_jQuery('#coupon_discountpercentage').val() === "0") && (scc_jQuery('#coupon_discountvalue').val() === 0 && scc_jQuery('#coupon_discountvalue').val() === "0"))
	|| (scc_jQuery('#coupon_discountpercentage').val() === '' && scc_jQuery('#coupon_discountvalue').val() === '')){
	scc_jQuery('#coupon_discountpercentage_error').html('Please add one type of discount.')
scc_jQuery('#coupon_discountvalue_error').html('Please add one type of discount.')
ok = false
}if(Number(scc_jQuery('#coupon_minspend').val()) > Number(scc_jQuery('#coupon_maxspend').val())){
	scc_jQuery('#coupon_minspend_error').html('Minimum spend can not be equal or higher than maximum spend.')
	scc_jQuery('#coupon_maxspend_error').html('Minimum spend can not be equal or higher than maximum spend.')
	ok = false
}
if(scc_jQuery('#coupon_discountvalue').val().indexOf('e') != -1){
	scc_jQuery('#coupon_discountvalue_error').html('Invalid numeric value.')
	ok = false
}
if(scc_jQuery('#coupon_discountpercentage').val().indexOf('e') != -1){
	scc_jQuery('#coupon_discountpercentage_error').html('Invalid numeric value.')
	ok = false
}
if(scc_jQuery('#coupon_minspend').val().indexOf('e') != -1){
	scc_jQuery('#coupon_minspend_error').html('Invalid numeric value.')
	ok = false
}
if(scc_jQuery('#coupon_maxspend').val().indexOf('e') != -1){
	scc_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>'
	scc_jQuery('#delete_coupon_modal_container').html(code)
	scc_jQuery('#delete_coupon_modal').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')
		}
	};
	scc_jQuery.ajax( $coupon_form_delete );
}
/* Number Input styling */
(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(scc_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');
    		}
    	}
    }
}
})();
scc_inputNumber(scc_jQuery('.scc_wrapper .number_box_2_text '));
(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');
  })
	}
}(scc_jQuery));