/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Commercial License and is not open source.
 * Each license that you purchased is only available for 1 website only.
 * You can't distribute, modify or sell this code.
 * If you want to use this file on more websites, you need to purchase additional licenses.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file.
 * If you need help please contact <attechteams@gmail.com>
 *
 * @author    Alpha Tech <attechteams@gmail.com>
 * @copyright 2022 Alpha Tech
 * @license   opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
 */


;(function(root, factory) {

    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.NProgress = factory();
    }

})(this, function() {
    var NProgress = {};

    NProgress.version = '0.2.0';

    var Settings = NProgress.settings = {
        minimum: 0.08,
        easing: 'ease',
        positionUsing: '',
        speed: 200,
        trickle: true,
        trickleRate: 0.02,
        trickleSpeed: 800,
        showSpinner: true,
        barSelector: '[role="bar"]',
        spinnerSelector: '[role="spinner"]',
        parent: 'body',
        template: '<div class="bar" role="bar"><div class="peg"></div></div><div class="spinner" role="spinner"><div class="spinner-icon"></div></div>'
    };

    /**
     * Updates configuration.
     *
     *     NProgress.configure({
     *       minimum: 0.1
     *     });
     */
    NProgress.configure = function(options) {
        var key, value;
        for (key in options) {
            value = options[key];
            if (value !== undefined && options.hasOwnProperty(key)) Settings[key] = value;
        }

        return this;
    };

    /**
     * Last number.
     */

    NProgress.status = null;

    /**
     * Sets the progress bar status, where "n" is a number from "0.0" to "1.0".
     *
     *     NProgress.set(0.4);
     *     NProgress.set(1.0);
     */

    NProgress.set = function(n) {
        var started = NProgress.isStarted();

        n = clamp(n, Settings.minimum, 1);
        NProgress.status = (n === 1 ? null : n);

        var progress = NProgress.render(!started),
            bar      = progress.querySelector(Settings.barSelector),
            speed    = Settings.speed,
            ease     = Settings.easing;

        progress.offsetWidth; /* Repaint */

        queue(function(next) {
            // Set positionUsing if it hasn't already been set
            if (Settings.positionUsing === '') Settings.positionUsing = NProgress.getPositioningCSS();

            // Add transition
            css(bar, barPositionCSS(n, speed, ease));

            if (n === 1) {
                // Fade out
                css(progress, {
                    transition: 'none',
                    opacity: 1
                });
                progress.offsetWidth; /* Repaint */

                setTimeout(function() {
                    css(progress, {
                        transition: 'all ' + speed + 'ms linear',
                        opacity: 0
                    });
                    setTimeout(function() {
                        NProgress.remove();
                        next();
                    }, speed);
                }, speed);
            } else {
                setTimeout(next, speed);
            }
        });

        return this;
    };

    NProgress.isStarted = function() {
        return typeof NProgress.status === 'number';
    };

    /**
     * Shows the progress bar.
     * This is the same as setting the status to 0%, except that it doesn't go backwards.
     *
     *     NProgress.start();
     *
     */
    NProgress.start = function() {
        if (!NProgress.status) NProgress.set(0);

        var work = function() {
            setTimeout(function() {
                if (!NProgress.status) return;
                NProgress.trickle();
                work();
            }, Settings.trickleSpeed);
        };

        if (Settings.trickle) work();

        return this;
    };

    /**
     * Hides the progress bar.
     * This is the *sort of* the same as setting the status to 100%, with the
     * difference being "done()" makes some placebo effect of some realistic motion.
     *
     *     NProgress.done();
     *
     * If "true" is passed, it will show the progress bar even if its hidden.
     *
     *     NProgress.done(true);
     */

    NProgress.done = function(force) {
        if (!force && !NProgress.status) return this;

        return NProgress.inc(0.3 + 0.5 * Math.random()).set(1);
    };

    /**
     * Increments by a random amount.
     */

    NProgress.inc = function(amount) {
        var n = NProgress.status;

        if (!n) {
            return NProgress.start();
        } else {
            if (typeof amount !== 'number') {
                amount = (1 - n) * clamp(Math.random() * n, 0.1, 0.95);
            }

            n = clamp(n + amount, 0, 0.994);
            return NProgress.set(n);
        }
    };

    NProgress.trickle = function() {
        return NProgress.inc(Math.random() * Settings.trickleRate);
    };

    /**
     * Waits for all supplied jQuery promises and
     * increases the progress as the promises resolve.
     *
     * @param $promise jQUery Promise
     */
    (function() {
        var initial = 0, current = 0;

        NProgress.promise = function($promise) {
            if (!$promise || $promise.state() === "resolved") {
                return this;
            }

            if (current === 0) {
                NProgress.start();
            }

            initial++;
            current++;

            $promise.always(function() {
                current--;
                if (current === 0) {
                    initial = 0;
                    NProgress.done();
                } else {
                    NProgress.set((initial - current) / initial);
                }
            });

            return this;
        };

    })();

    /**
     * (Internal) renders the progress bar markup based on the "template"
     * setting.
     */

    NProgress.render = function(fromStart) {
        if (NProgress.isRendered()) return document.getElementById('nprogress');

        addClass(document.documentElement, 'nprogress-busy');

        var progress = document.createElement('div');
        progress.id = 'nprogress';
        progress.innerHTML = Settings.template;

        var bar      = progress.querySelector(Settings.barSelector),
            perc     = fromStart ? '-100' : toBarPerc(NProgress.status || 0),
            parent   = document.querySelector(Settings.parent),
            spinner;

        css(bar, {
            transition: 'all 0 linear',
            transform: 'translate3d(' + perc + '%,0,0)'
        });

        if (!Settings.showSpinner) {
            spinner = progress.querySelector(Settings.spinnerSelector);
            spinner && removeElement(spinner);
        }

        if (parent != document.body) {
            addClass(parent, 'nprogress-custom-parent');
        }

        parent.appendChild(progress);
        return progress;
    };

    /**
     * Removes the element. Opposite of render().
     */

    NProgress.remove = function() {
        removeClass(document.documentElement, 'nprogress-busy');
        removeClass(document.querySelector(Settings.parent), 'nprogress-custom-parent');
        var progress = document.getElementById('nprogress');
        progress && removeElement(progress);
    };

    /**
     * Checks if the progress bar is rendered.
     */

    NProgress.isRendered = function() {
        return !!document.getElementById('nprogress');
    };

    /**
     * Determine which positioning CSS rule to use.
     */

    NProgress.getPositioningCSS = function() {
        // Sniff on document.body.style
        var bodyStyle = document.body.style;

        // Sniff prefixes
        var vendorPrefix = ('WebkitTransform' in bodyStyle) ? 'Webkit' :
            ('MozTransform' in bodyStyle) ? 'Moz' :
                ('msTransform' in bodyStyle) ? 'ms' :
                    ('OTransform' in bodyStyle) ? 'O' : '';

        if (vendorPrefix + 'Perspective' in bodyStyle) {
            // Modern browsers with 3D support, e.g. Webkit, IE10
            return 'translate3d';
        } else if (vendorPrefix + 'Transform' in bodyStyle) {
            // Browsers without 3D support, e.g. IE9
            return 'translate';
        } else {
            // Browsers without translate() support, e.g. IE7-8
            return 'margin';
        }
    };

    /**
     * Helpers
     */

    function clamp(n, min, max) {
        if (n < min) return min;
        if (n > max) return max;
        return n;
    }

    /**
     * (Internal) converts a percentage ("0..1") to a bar translateX
     * percentage ("-100%..0%").
     */

    function toBarPerc(n) {
        return (-1 + n) * 100;
    }


    /**
     * (Internal) returns the correct CSS for changing the bar's
     * position given an n percentage, and speed and ease from Settings
     */

    function barPositionCSS(n, speed, ease) {
        var barCSS;

        if (Settings.positionUsing === 'translate3d') {
            barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };
        } else if (Settings.positionUsing === 'translate') {
            barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };
        } else {
            barCSS = { 'margin-left': toBarPerc(n)+'%' };
        }

        barCSS.transition = 'all '+speed+'ms '+ease;

        return barCSS;
    }

    /**
     * (Internal) Queues a function to be executed.
     */

    var queue = (function() {
        var pending = [];

        function next() {
            var fn = pending.shift();
            if (fn) {
                fn(next);
            }
        }

        return function(fn) {
            pending.push(fn);
            if (pending.length == 1) next();
        };
    })();

    /**
     * (Internal) Applies css properties to an element, similar to the jQuery
     * css method.
     *
     * While this helper does assist with vendor prefixed property names, it
     * does not perform any manipulation of values prior to setting styles.
     */

    var css = (function() {
        var cssPrefixes = [ 'Webkit', 'O', 'Moz', 'ms' ],
            cssProps    = {};

        function camelCase(string) {
            return string.replace(/^-ms-/, 'ms-').replace(/-([\da-z])/gi, function(match, letter) {
                return letter.toUpperCase();
            });
        }

        function getVendorProp(name) {
            var style = document.body.style;
            if (name in style) return name;

            var i = cssPrefixes.length,
                capName = name.charAt(0).toUpperCase() + name.slice(1),
                vendorName;
            while (i--) {
                vendorName = cssPrefixes[i] + capName;
                if (vendorName in style) return vendorName;
            }

            return name;
        }

        function getStyleProp(name) {
            name = camelCase(name);
            return cssProps[name] || (cssProps[name] = getVendorProp(name));
        }

        function applyCss(element, prop, value) {
            prop = getStyleProp(prop);
            element.style[prop] = value;
        }

        return function(element, properties) {
            var args = arguments,
                prop,
                value;

            if (args.length == 2) {
                for (prop in properties) {
                    value = properties[prop];
                    if (value !== undefined && properties.hasOwnProperty(prop)) applyCss(element, prop, value);
                }
            } else {
                applyCss(element, args[1], args[2]);
            }
        }
    })();

    /**
     * (Internal) Determines if an element or space separated list of class names contains a class name.
     */

    function hasClass(element, name) {
        var list = typeof element == 'string' ? element : classList(element);
        return list.indexOf(' ' + name + ' ') >= 0;
    }

    /**
     * (Internal) Adds a class to an element.
     */

    function addClass(element, name) {
        var oldList = classList(element),
            newList = oldList + name;

        if (hasClass(oldList, name)) return;

        // Trim the opening space.
        element.className = newList.substring(1);
    }

    /**
     * (Internal) Removes a class from an element.
     */

    function removeClass(element, name) {
        var oldList = classList(element),
            newList;

        if (!hasClass(element, name)) return;

        // Replace the class name.
        newList = oldList.replace(' ' + name + ' ', ' ');

        // Trim the opening and closing spaces.
        element.className = newList.substring(1, newList.length - 1);
    }

    /**
     * (Internal) Gets a space separated list of the class names on the element.
     * The list is wrapped with a single space on each end to facilitate finding
     * matches within the list.
     */

    function classList(element) {
        return (' ' + (element.className || '') + ' ').replace(/\s+/gi, ' ');
    }

    /**
     * (Internal) Removes an element from the DOM.
     */

    function removeElement(element) {
        element && element.parentNode && element.parentNode.removeChild(element);
    }

    return NProgress;
});




function __(key) {
    return Client.translate[Client.name_module][key] || key;
}

var AP = new function __AP() {
	this.key={enter: 13, tab: 9, backspace: 8, escape: 27, prev: 37, next: 39, left: 37, right: 39, up: 38, down: 40};
	this.keycode=function(e, str){
		return (e.keycode==this.key[str]);
	};

	window.onbeforeunload = null;

	this.EVENTS={PAGE_UNLOAD: 'page.unload',
		PAGE:{
			INIT: 'page.init',
			UNLOAD: 'page.unload',
			RELOAD: 'page.reload',
			AFTERLOAD: 'page.afterload'
	}};

	this.ajaxTranslate = function() {
	    AP.post(Client.link_module, {_a: 'ajaxTranslate'}, function (code) {
            if (!code.good()) {
                AP.toastr.error(code.message);
                return;
            }
            AP.toastr.success(code.message);
        });
    }

    this.add= function(){
        for (var i=0; i<arguments.length; i++){
            var id=arguments[i];
            if (AP.word.prefix(id,'#')){
                id=id.substr(1);
            }
            $(document.body).append("<div id='"+id+"' style='display:none'></div>");
        }
    };

	/**
	 * @desc Setting continuous Request
	 */
	this._continuous=false;
	this._in_continuous_request=false;

	var uuidLists=[];
	this.uuid=function(){
		return '_uuid'+(Math.floor(Math.random()*100000))+"_"+(Math.floor(Math.random()*100000))+"_"+AP.time.timeStamp();
	};

	this.putBaseBlock = function(val, placeholder){
		$(placeholder).replaceWith(val);
	};

	/**
	 * @desc Call user function with parameter
	 */
	this.fn=function(fn, data){
		var __fn=eval(fn);
		__fn(data);
	};

	/**
	 * @desc Call user object function with parameter
	 */
	this.call=function(fn){
		fn();
	};

	this.__ts=[];
	this.__rts=[];

	/**
	 * @desc Temporary timeout (all timeouts are clear in the next page)
	 */
	this.timeout=function(fn, total_time){
		var tx=setTimeout(function(){
			fn();
		}, total_time);

		AP.__ts.push(tx);

		return tx;
	};


	/**
	 * @desc Temporary timeout (all timeouts are clear in the next page)
	 */
	this.rtimeout=function(fn, total_time){
		var intv=setInterval(function(){
			fn.apply(intv);
		}, total_time);

		AP.__rts.push(intv);
		return intv;
	};

	this.__lock=false;

	this.lock=function(){
		this.__lock=true;
	};

	this.post=function(url, data, handler, use_lock){
		data['_r'] = 1;
		var $this=null;

		if (use_lock && use_lock==true){
			if (this.__lock){
				alert("Be patient! Your request is processed right now.");
				return;
			}
			this.lock();
		}

		if (!handler){
			handler=this.hander;
		}

		AP.sys.fire("ajax.pre.update",data);
		this.undone_url=url;
		this.undone_data=data;

		$.post(url, data, function(text){
			AP.__lock=false;
			AP.undone_url="";
			AP.undone_data="";
			handler(parseCode(text));
		}).fail(function(text){
			AP.__lock=false;
			AP.undone_url="";
			AP.undone_data="";
			var c=parseCode(text);
			handler(c);
		});
	};

	this.submit=function(selector, callback, extra_data){
		if (!AP.data.isString(selector)){
			var id;
			if (!$(selector).attr('id')){
				id=AP.uuid();
				$(selector).attr('id', id);
			}else{
				id=$(selector).attr('id');
			}

			elem="#"+id;
		}else{
			elem=selector;
		}

		if (!callback){
			callback=this.handler;
		}
		var form_data = new FormData($(selector)[0]);
		if (extra_data){
			for (var k in extra_data){
				form_data.append(k, extra_data[k]);
			}
		}

		$.ajax({
			url: $(selector).attr("action"),
			method: "POST",
			dataType: 'text',
			data: form_data,
			processData: false,
			contentType: false,
			success: function (response) {
				callback(parseCode(response));
			},
			error: function() {
				UI.ajaxHide();
			}
		});
	};

	this.refresh=function(){
		if (Client.native){
			location.reload();
		}

		return this.redirect(window.location.href);
	};

	this.redirect=function(link){
		if (!link){
			window.location.href=window.location.href;
		}

		window.location.href=link;
	};

	this.xRefresh=function(callback){
        AP.loadURL(window.location.href, {direct_load: true});

		if (callback){
			AP.sys.once(AP.EVENTS.PAGE_UNLOAD, callback);
		}
	};

	this.__urlref=null;
	this.toURL=function(url, callback, ref){
		if (ref){
			this.__urlref=ref;
		}

		if (!AP.word.isURL(url) && this.rewriteRedirect(url)){
			return;
		}

		history.pushState({url: url}, "", url);

		AP.loadURL(url,{direct_load: true});

		if (callback){
			AP.sys.once(AP.EVENTS.PAGE_UNLOAD, callback);
		}
	};

	this.loadURL=function(url, options){
		$("#ajax-load").show();
		$(document.body).addClass("__onload");
		AP.sys.fire("page.pre.transition");

		var data = {};
		var $this = $(this.__urlref);

		if ($this.data('action')) {
			data['_a'] = $this.data('action');
		}

		if (options){
			$.extend(data, options);
		}

		AP.post(url,data, function(code){
			AP.current_url=url;
			$(document.body).removeClass("__onload");

			if (code.good()){
				var rs=code._init;
				var _rs=eval(rs);
				_rs(function(){
					if (!options.keep_page_data){
						AP.pageData={};
						Client.pageData={};
					}

					window.onbeforeunload = null;

					AP.pageConfig.reset();

					AP._in_continuous_request=false;
					AP.gb.clear();

					var called=false;
					if (!called){
						if (code._page_data){
							eval(code._page_data);
						}

						AP.updatePageData();

						AP.fn(code._update, code._html);
						if (code._inpage_js){
							eval(code._inpage_js);
						}
					}
					$("#ajax-load").hide();
					AP.sys.fire(AP.EVENTS.PAGE.AFTERLOAD);
				});
			}else{
				$("#ajax-load").hide();
				AP.sys.fire("page.post.transition");
				AP._in_continuous_request=false;
				AP.alertError(code.message || __('Something error'));
			}
		}, true);
	};

	this.loadInlineURL=function(url, data, canvas, options){
		UI.ajaxShow();
		AP.post(url, data, function(code){
			UI.ajaxHide();
			if (!code.good()){
				if (options.error){
					options.error(code);
				}

				return AP.alertError(code.message);
			}
			if (options.start) options.start();
			AP.blockRediretion=null;

			AP.setTempData(code);
			$(canvas).html(code._html);

			// AP.hotkey.clear();
			if (code._inpage_js){
				eval(code._inpage_js);
			}

			if (options.end) options.end();
		});
	};

	this.updatePageData=function(){
		// Clear all events (notice: static event should be called via AP.sys
		AP.event.clear();
	};

	/**
	 * @desc Check data type.
	 */
	 this.isArray=function(data){
		return $.isArray(data);
	};
	this.isAssocArray=function(data){
		return typeof(data)=='object' && isNaN(data);
	};
	this.isObject=function(data){
		return typeof(data)=='object' && isNaN(data);
	};
	this.isFunction=function(data){
		return $.isFunction(data);
	};
	this.isInt=function(data){
		return !isNaN(data)&&parseInt(data)==data;
	};
	this.isString=function(data){
		return typeof(data)=='string' && isNaN(data);
	};
	this.isEmpty=function(data){
		if (!data || data.length <=0){
			return true;
		}
		return false;
	};

	this._gcs = [];
	this.gc = function(fn){
		this._gcs.push(fn);
	};

	this.resetPageData=function(){
		if (AP.mapData){
			AP.mapData={};
		}

		if (Client){
			Client.tempData={};
		}

		for (var i=0; i<this._gcs.length; i++){
			var _gc = this._gcs[i];
			_gc();
		}


		for (var i=0; i<AP.__ts.length; i++){
			if (AP.__ts[i]){
				clearTimeout(AP.__ts[i]);
			}
		}

		for (var i=0; i<AP.__rts.length; i++){
			if (AP.__rts[i]){
				clearTimeout(AP.__rts[i]);
			}
		}

		AP.__ts=[];
		AP.__rts=[];

		$("#ap-temp iframe.__temp").each(function(){
			$(this).remove();
		});

		$("#ap-temp").children('.__temp').remove();
		$(".__temp").remove();
		$(".__tempx").empty();

		$("#apdialogs").hide();

		$(document).unbind('keydown');

		$(document).unbind('.__temp');
		$(window).unbind('.__temp');

		AP.blockRediretion=null;
	};

	this.initPageData=function(){
		return this.updatePageData();
	};

	this.isset=function(varname){
		return(typeof(window[varname])!='undefined');
	};

    /**
     * @desc Apply a transform function on the array. It is very much
     * similar to array_walk in PHP world.
     */
    this.transform=function(arr, transform_fn){
        var b=[];
        for (var i=0; i<arr.length; i++){
            var temp=transform_fn(arr[i],i);
            if (temp!==null){
                b.push(temp);
            }
        }
        return b;
    };


    this.select=function(arr, transform_fn){
        if (!arr){
            return [];
        }
        return this.transform(arr, transform_fn);
    };

	this.render=function(arr, transform_fn, limit){
		if (!limit){
			limit=0;
		}
		if (!this.isArray(arr) || !arr.length){
			return "";
		}
		var m=arr.length;
		if (limit >0 && limit <m){
			m=limit;
		}
		var text="";
		for (var i=0; i<m; i++){
			text+=transform_fn(arr[i],i, m);
		}
		return text;
	};

	this.fire=function(event, data){
		this.event.trigger(event, data);
		return this;
	};

	this.handler=function(code){
		AP.alertError(code.message);
	};

	this.successHandler=function(code){
		AP.alertSuccess(code.message);
	};

	this.alertError=function(content, extra_messages, callback){
		if (AP.word.empty(content)){
			content = __("The system is temporarily unable to process your request. We are working on it and we'll get it fixed as we can.");
		}

		AP.toastr.error(content);
	};

	this.confirm=function(content, fn, title = "", size = "mini"){
		if (!title) {
			title = __('Confirm');
		}
		AP.dialog("#alert")
		.temp(false)
		.engine(AP.config.alertDialogEngine)
		.style("__apalert core-semantic-fade core-semantic-in")
		.title(title).temp(false)
		.size(size)
		.button(__('No'), function(){
			AP.dialog("#alert").hide();
			$(AP.dialog("#alert").w()).remove();
		},'core-semantic-ui core-semantic-negative core-semantic-button')
		.button(__('Yes'), function(){
			AP.dialog("#alert").hide();
			$(AP.dialog("#alert").w()).remove();
			fn();
		},'core-semantic-ui core-semantic-positive core-semantic-right core-semantic-labeled core-semantic-icon core-semantic-button',
		"<span class='-icon-svg core-semantic-icon -icon-svg-24'>"+(SVG.check)+"</span>")
		.content("<p>"+content+"</p>")
		.show().balance();
	};

	this.setURLParams=function(params, redirect){
		var ps=params;
		if (AP.data.isString(ps)){
			ps=queryStringToArray(params);
		}

		var orgs=shallowClone(ps);

		var checked={};

		var url=window.location.href;

		url=url.replace(/(\&*)([\w\-]+)\=([\w\-\%\(\)\.\@\/]+)/g, function(match, p0, p1, p2){
			checked[p1]=1;
			if (p1 in ps && ps[p1]===null){
				return "";
			}
			if (ps[p1]){
				return p0+p1+"="+ps[p1];
			}
			return p0+p1+"="+p2;
		});

		var extra="";

		for (var key in ps){
			if (!checked[key]){
				if (key in orgs && orgs[key]==null){
					Query.unset(key);
				}else{
					Query.set(key, ps[key]);
					extra+=key+"="+ps[key]+"&";
				}
			}else{
				Query.set(key, ps[key]);
			}
		};

		if (extra.length){
			extra=extra.substr(0, extra.length-1);

			if (url.indexOf("?")==-1){
				url=url+"?"+extra;
			}else{
				url=url+"&"+extra;
			}
		}


		if (url.charAt(url.length-1)=="?"){
			url=url.substr(0, url.length-1);
		}

		if (redirect){
			return AP.toURL(url);
		}else{
			return AP.setURL(url);
		}

	}

	this.__history=false;
	if (history && history.pushState){
		this.__history=true;
	};
	this.setURL=function(url){
		if (this.__history){
			history.pushState({url: url},"",url);
		}
	};

	this.purify=function(txt){
		var temp=txt+"";

		if (!temp || !temp.length){
			return "";
		}

		temp=temp.replace(/<[^>]*>?/gm, '');
		temp=temp.replace(/<>/gm,'');
		temp=temp.replace(/^\s+|\s+$/gm,'');

		return temp;
	};

	this.appData = function(data){
		for (var key in data){
			Client[key]=data[key];
		}
	};
};


AP.rewriteRedirect=function(url){
	for (var i=0; i<AP.rules.length; i++){
		var temp=AP.rules[i];

		if (url.match(RegExp(temp.pattern))){
			var qs={};
			var original_qs=url.split("?");
			if (original_qs.length==2 && temp.qsa){
				qs=queryStringToArray(original_qs[1]);
			}

			var next=url.replace(new RegExp(temp.pattern), temp.replace);
			var fn=temp.callback;
			var paths=next.split("?");

			if (paths.length<2){
				fn.call(AP.__urlref, qs);
				return true;
			}else{
				var new_qs=queryStringToArray(paths[1]);
				for (var key in new_qs){
					qs[key]=new_qs[key];
				}
				fn.call(AP.__urlref, qs);
				return true;
			}
		}

	}

	return null;
};

AP.event=new function __APEvent(){
	this.events={};
	this.__fired={};

	this.clear=function(){
		this.events={};
		this.__fired={};
	};

	this.trigger=function(ev, data){
		if (this.events[ev] && this.events[ev].length){
			for (var i=0; i<this.events[ev].length; i++){
				var fn=this.events[ev][i];
				if (!fn){
					break;
				}

				if (fn._caller){
					fn.apply(fn._caller, data);
				}else{
					if (AP.data.isArray(data)){
						fn.apply(undefined, data);
					}else{
						fn(data);
					}

				}
			}
		}

		this.__fired[ev]=1;
		return this;
	};

	this.release=function(ev){
		if (this.events[ev] && this.events[ev].length){
			while (true){
				var fn=this.events[ev].shift();
				if (!fn){
					break;
				}

				if (fn._caller){
					fn.apply(fn._caller);
				}else{
					fn();
				}
			}
		}

		this.__fired[ev]=1;
		return this;
	};


	this.bind=function(ev, fx, _caller){
		if (!this.events[ev]){
			this.events[ev]=[];
		}

		if (_caller){
			fx._caller=_caller;
		}

		this.events[ev].push(fx);

		return this;
	};


	/**
	 * @desc Reset all current binds and rebind
	 */
	this.rebind=function(ev, fx, _caller){
		this.events[ev]=[];

		if (_caller){
			fx._caller=_caller;
		}

		this.events[ev].push(fx);

		return this;
	};

	this.fired=function(ev){
		if (this.__fired[ev]){
			return true;
		}
		return false;
	};
}


function parseCode(txt){
	if (AP.isObject(txt)){
		return new Code(txt);
	}

	try{
		var tmp = txt.substring(txt.indexOf('{"code"'));
		return new Code(eval("("+tmp+")"));
	}catch(e){
		return new Code({"code":0, "message":'Unknown Error',"data":null, "error":"parse error"});
	}
}



function Code(obj){
	this.code=0;
	this.message='';
	this.data=null;

	if (obj){
		$.extend(this, obj);
		this.code=parseInt(this.code);
	}


	/**
	 * @desc Check if a code is good.
	 */
	this.good=function(){
		if (this.hasCode(1)) return true;
		return false;
	};

	this.notEmpty=function(){
		return !this.empty;
	};

	this.hasCode=function(code){
		if (this.code==code){
			return true;
		}
		return false;
	};


	this.hasMessage=function(message){
		if (this.message==message){
			return true;
		}
		if (AP.isInt(message) && this.message && message==parseInt(this.message)){
			return true;
		}
		return false;
	};
};



Code.init=function(txt){
	try{
		return new Code(eval("("+txt+")"));
	}
	catch(e){
		return new Code({"code":0, "message":'Unknown error',"data":null, "error":"parse_error"});
	}
};


Code.error = function(msg){
	var c=new Code();
	c.message=msg;
	return c;
};

function shallowClone(obj){
	if (!AP.data.isObject(obj)){
		return obj;
	}

	var temp={};
	for (var key in obj){
		temp[key]=obj[key];
	}

	return temp;
};

function queryStringToArray(qs){
	var parts=qs.split("&");
	var r={};
	for (var i=0; i<parts.length; i++){
		var data=parts[i].split("=");
		if (data && data.length==2){
			r[data[0]]=data[1];
		}
	}

	return r;
};

var Query=new function __Query(){
	this.__data={};
	this.init=function(data){
		this.__data=data;
	};

	this.get=function(key){
		if (key in this.__data){
			return this.__data[key];
		}
		return null;
	};

	this.getFlat=function(key){
		var val=this.get(key);
		if (val==null){
			return "";
		}

		return val;
	};

	this.getInt=function(key){
		var val=this.get(key);
		if (!val){
			return 0;
		}
		return parseInt(val);
	};

	this.page=function(){
		var val=this.getInt("page");
		if (!val || val<=0){
			val=1;
		}

		return val;
	};

	this.set=function(key, val){
		this.__data[key]=val;
	};

	this.unset=function(key){
		delete this.__data[key];
	};

	this.setDefault=function(key, val){
		if (key in this.__data){
		}else{
			this.__data[key]=val;
		}
	};

	this.reset=function(){
		this.__data={};
	};

	this.all=function(){
		return this.__data;
	};

	this.release=function(){
		var obj= shallowClone(this.__data);
		delete obj.env;
		return obj;
	};

	this.text=function(){
		var txt="";

		for (var key in this.__data){
			if (key=="env"){
				continue;
			}

			txt+="&"+key+"="+this.__data[key];
		}

		return txt;
	};
};

AP.rules=[];

AP.rewrite=function(pattern, replace, callback, query_string_append){
	AP.rules.push({'pattern': pattern, 'replace': replace, 'callback': callback, 'qsa': query_string_append});
};

AP.config={};

function assoc(data){
	if (AP.data.isArray(data)){
		var obj={};
		for (var i=0; i<data.length; i++){
			obj[data[i].name]=data[i].value;
		}
		return obj;
	}

	var obj={};
	obj[arguments[0]]=arguments[1];
	return obj;
};

function explain(txt, opts){
	if (opts && opts===true){
		opts={icon: false};
	}

	opts=$.extend({direction: 'up', width: 200, icon: true}, opts);


	var align = '';
	if ('align' in opts){
		align = "-align-"+(opts.align)+"";
	}

	if (!opts.icon){
		return "<span class='-infobox -"+opts.direction+" "+align+" -w"+opts.width+"'><span class='-box block normal'>"+txt+"</span></span>";
	}

	return "&nbsp; <span class='core-inline core-relative -infow'> <span class='-icon-svg' data-svgicon='info_circle' >"+SVG.help_with_circle+"</span> <span class='-infobox -"+opts.direction+" "+align+" -w"+opts.width+"'><span class='-box core-block core-normal'>"+txt+"</span></span></span>";
};

function range(from, to, space){
	if (!space || typeof space=="undefined"){
		space=1;
	}

	var r=[];
	if (from<to){
		for (var i=from; i<=to; i=i+space){
			r.push(""+i);
		}
		return r;
	}else{
		for (var i=from; i>=to; i=i-space){
			r.push(""+i);
		}
		return r;
	}

};

function inline(content, max_length, append_dots){
	if (!max_length){
		max_length=255;
	}

	if (content === null || typeof content == "undefined"){
		return '';
	}

	var _content = content.replace(/<\/p>\s*<p>/g, '</p> &#8628; </p>').replace(/<\/div>\s*<div>/g, '</div> &#8628; </div>').replace(/<br\/*>/g, ' &#8628; ');
	var extra = " ";
	if (append_dots){
		extra = " ...";
	}

	return AP.word.shorten(AP.purify(_content),max_length, extra);
};

function safe(txt){
	return AP.purify(txt);
};

function purifyStrict(str, sep){
	if (!sep){
		sep = "";
	}
	var s=purify(str);
	s=s.replace(/[\W_\s]+/g, sep);
	return s.toLowerCase();
};

function purify(txt){
	var str=safe(txt);
	var defaultDiacriticsRemovalMap = [
			{'core':'A', 'letters':/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g},
			{'core':'AA','letters':/[\uA732]/g},
			{'core':'AE','letters':/[\u00C6\u01FC\u01E2]/g},
			{'core':'AO','letters':/[\uA734]/g},
			{'core':'AU','letters':/[\uA736]/g},
			{'core':'AV','letters':/[\uA738\uA73A]/g},
			{'core':'AY','letters':/[\uA73C]/g},
			{'core':'B', 'letters':/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g},
			{'core':'C', 'letters':/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g},
			{'core':'D', 'letters':/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g},
			{'core':'DZ','letters':/[\u01F1\u01C4]/g},
			{'core':'Dz','letters':/[\u01F2\u01C5]/g},
			{'core':'E', 'letters':/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g},
			{'core':'F', 'letters':/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g},
			{'core':'G', 'letters':/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g},
			{'core':'H', 'letters':/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g},
			{'core':'I', 'letters':/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g},
			{'core':'J', 'letters':/[\u004A\u24BF\uFF2A\u0134\u0248]/g},
			{'core':'K', 'letters':/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g},
			{'core':'L', 'letters':/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g},
			{'core':'LJ','letters':/[\u01C7]/g},
			{'core':'Lj','letters':/[\u01C8]/g},
			{'core':'M', 'letters':/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g},
			{'core':'N', 'letters':/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g},
			{'core':'NJ','letters':/[\u01CA]/g},
			{'core':'Nj','letters':/[\u01CB]/g},
			{'core':'O', 'letters':/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g},
			{'core':'OI','letters':/[\u01A2]/g},
			{'core':'OO','letters':/[\uA74E]/g},
			{'core':'OU','letters':/[\u0222]/g},
			{'core':'P', 'letters':/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g},
			{'core':'Q', 'letters':/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g},
			{'core':'R', 'letters':/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g},
			{'core':'S', 'letters':/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g},
			{'core':'T', 'letters':/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g},
			{'core':'TZ','letters':/[\uA728]/g},
			{'core':'U', 'letters':/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g},
			{'core':'V', 'letters':/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g},
			{'core':'VY','letters':/[\uA760]/g},
			{'core':'W', 'letters':/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g},
			{'core':'X', 'letters':/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g},
			{'core':'Y', 'letters':/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g},
			{'core':'Z', 'letters':/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g},
			{'core':'a', 'letters':/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g},
			{'core':'aa','letters':/[\uA733]/g},
			{'core':'ae','letters':/[\u00E6\u01FD\u01E3]/g},
			{'core':'ao','letters':/[\uA735]/g},
			{'core':'au','letters':/[\uA737]/g},
			{'core':'av','letters':/[\uA739\uA73B]/g},
			{'core':'ay','letters':/[\uA73D]/g},
			{'core':'b', 'letters':/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g},
			{'core':'c', 'letters':/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g},
			{'core':'d', 'letters':/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g},
			{'core':'dz','letters':/[\u01F3\u01C6]/g},
			{'core':'e', 'letters':/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g},
			{'core':'f', 'letters':/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g},
			{'core':'g', 'letters':/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g},
			{'core':'h', 'letters':/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g},
			{'core':'hv','letters':/[\u0195]/g},
			{'core':'i', 'letters':/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g},
			{'core':'j', 'letters':/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g},
			{'core':'k', 'letters':/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g},
			{'core':'l', 'letters':/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g},
			{'core':'lj','letters':/[\u01C9]/g},
			{'core':'m', 'letters':/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g},
			{'core':'n', 'letters':/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g},
			{'core':'nj','letters':/[\u01CC]/g},
			{'core':'o', 'letters':/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g},
			{'core':'oi','letters':/[\u01A3]/g},
			{'core':'ou','letters':/[\u0223]/g},
			{'core':'oo','letters':/[\uA74F]/g},
			{'core':'p','letters':/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g},
			{'core':'q','letters':/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g},
			{'core':'r','letters':/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g},
			{'core':'s','letters':/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g},
			{'core':'t','letters':/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g},
			{'core':'tz','letters':/[\uA729]/g},
			{'core':'u','letters':/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g},
			{'core':'v','letters':/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g},
			{'core':'vy','letters':/[\uA761]/g},
			{'core':'w','letters':/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g},
			{'core':'x','letters':/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g},
			{'core':'y','letters':/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g},
			{'core':'z','letters':/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g}
		  ];

	for (var i=0; i<defaultDiacriticsRemovalMap.length; i++) {
		str = str.replace(defaultDiacriticsRemovalMap[i].letters, defaultDiacriticsRemovalMap[i].core);
	}

	str=str.replace(/[\W_]+/g," ");
	str=$.trim(str);
	return str.toLowerCase();
};

AP._locales={};

AP.locale=new function __APLocale(){
	this.get=function(key, df){
		if (AP._locales[key]){
			return AP._locales[key];
		}
		if (df){
			return df;
		}

		return null;
	}

	this.set=function(key, val){
		AP._locales[key]=val;
	};

};


AP.json = new function __APJSON(){
	this.parse = function(str){
		try {
			var a = JSON.parse(str);
			return a;
		} catch(e) {
			return null;
		}
	};
};


AP.array={
    fromObject: function(obj){
        var r=[];
        for (var key in obj){
            r[key]=obj[key];
        }

        return r;
    },

    groupDate: function(data, key_sort = 'since', fn = null) {
        var group = {};
        data = AP.array.sortObj(data, key_sort, -1);
        for (var i = 0; i < data.length; i++) {
            var act = data[i];
            var key_date = act.since;

            if (AP.isFunction(fn)) {
                key_date = fn(act);
            }

            var key = AP.time.time("%V, %d/%m/%Y", key_date);

            if (typeof group[key] === 'undefined') {
                group[key] = [];
            }

            group[key].push(act);
        }

        if (key_sort == 'transaction_date') {
            for (var time in group) {
                group[time] = AP.array.sortObj(group[time], 'since', -1);
            }
        }
        return group;
    },

    within: function(element, arr, compare_fn){
        if (!arr || arr.length==0) return false;
        for (var i=0; i<arr.length; i++){
            if (compare_fn && typeof compare_fn!="undefined"){
                if (compare_fn(arr[i], element)){
                    return true;
                }
            }else{
                if (arr[i]==element) return true;
                if (AP.data.isInt(arr[i]) && AP.data.isInt(element)){
                    if (parseInt(arr[i]) === parseInt(element)){
                        return true;
                    }
                }
            }

        }
        return false;
    },

    updateObjects:function(arr, obj){
        for (var i=0; i<arr.length; i++){
            if (!AP.data.isInt(arr[i]) && !AP.data.isInt(obj.id)){
                if (arr[i].id == obj.id){
                    arr[i]=obj;
                    return arr;
                }
            }else{
                if (parseInt(arr[i].id)==parseInt(obj.id)){
                    arr[i]=obj;
                    return arr;
                }
            }

        }

        arr.push(obj);

        return arr;
    },

    updateFieldsByID: function(arr, obj, transform){
        for (var i=0; i<arr.length; i++){
            if (idEquals(arr[i].id, obj.id)){
                transform(arr[i], obj);
            }
        }
    },

    join: function(array, joiner, fn){
        return AP.render(array, function(e, i){
            if (i == array.length - 1) {
                joiner = '';
            }
            if (fn){
                return fn(e)+joiner;
            }
            return e+joiner;
        });
    },

    contain: function(arr, element, compare_fn){
        return AP.array.within(element, arr, compare_fn);
    },

    sum: function(arr, fn){
        var t=0;
        if (!arr || !arr.length){
            return 0;
        }
        for (var i=0; i<arr.length; i++){
            if (!fn){
                if (AP.data.isInt(arr[i])){
                    t+=parseInt(arr[i]);
                }else{
                    t+=parseFloat(arr[i]);
                }
            }else{
                t+=fn(arr[i]);
            }
        }

        return t;
    },

    selectObj: function(obj, fn){
        var na=[];
        var i=0;
        for (var key in obj){
            var e=fn(obj[key], i, key);
            if (e!==null){
                i++;
                na.push(e);
            }
        }
        return na;
    },

    loop: function(arr, fn){
        for (var i=0; i<arr.length; i++){
            fn(arr[i], i, arr.length);
        }
    },

    avg: function(arr, fn){
        var count = arr.length;
        if (!count){
            return 0;
        }

        var total = this.count(arr, fn);
        return total/count;
    },

    clone: function(arr){
        return arr.slice(0);
    },

    unique: function(arr, compare_fn){
        if (!compare_fn){
            compare_fn=function(e, f){
                return (parseInt(e)==parseInt(f));
            };
        }
        var r=[];
        for (var i=0; i<arr.length; i++){
            if (AP.array.contain(r, arr[i], function(e1, e2){
                return compare_fn(e1, e2);
            })){}else{
                r.push(arr[i]);
            }
        }

        return r;
    },

    extract: function(arr, key){
        return ARR.select(arr, function(e){
            if (key in e){
                return e[key];
            }

            return null;
        });
    },

    find: function(arr, id){
        if (!arr || !arr.length){
            return false;
        }

        if (typeof id =="function"){
            for (var i=0; i<arr.length; i++){
                if (id(arr[i])){
                    return arr[i];
                }
            }

            return null;
        }


        for (var i=0; i<arr.length; i++){
            if (se(arr[i], id)){
                return arr[i];
            }
        }
        return null;
    },

    single: function(arr, filter){
        return this.find(arr, filter);
    },

    exist: function(arr, elem){
        if ($.isFunction(elem)){
            var obj=this.find(arr, elem);
            if (obj){
                return true;
            }
            return false;
        }else{
            var obj= AP.array.find(arr, function(e){
                return e==elem;
            });

            if (!obj){
                return false;
            }

            return true;
        }
    },

    indexOf: function(arr, elem, cmp){
        for (var i=0; i<arr.length; i++){
            if (cmp(arr[i], elem)){
                return i;
            }
        }

        return -1;
    },


    findObj: function(arr, id){
        if (!arr){
            return null;
        }

        for (var i=0; i<arr.length; i++){
            if (parseInt(arr[i].id)==parseInt(id)){
                return arr[i];
            }

            if (arr[i].id===id){
                return arr[i];
            }
        }
        return null;
    },

    sort: function(arr, sorter){
        for (var i=0; i<arr.length; i++){
            arr[i].__fs=sorter(arr[i], i);
        }

        return this.usort(arr, function(e, f){
            return e.__fs - f.__fs;
        })
    },

    usort: function(arr, sorter){
        for (var i=0; i<arr.length-1; i++){
            for (var j=i+1; j<arr.length; j++){
                if (sorter(arr[i], arr[j])>0){
                    var x=arr[i];
                    arr[i]=arr[j];
                    arr[j]=x;
                }
            }
        }
        return arr;
    },

    sortObj: function(arr, field, multiplier){
        if (!multiplier){
            multiplier=1;
        }

        return this.usort(arr, function(e1, e2){
            return multiplier*(parseInt(e1[field]) - parseInt(e2[field]));
        })
    },

    move: function(arr, elem, dir){
        for (var i=0; i<arr.length; i++){
            if (arr[i].id==elem.id){
                if (dir=="up" && i>0){
                    var temp=arr[i-1];
                    arr[i-1]=arr[i];
                    arr[i]=temp;
                }else if (dir=="down" && i< arr.length-1){
                    var temp=arr[i+1];
                    arr[i+1]=arr[i];
                    arr[i]=temp;
                }

                return;
            }
        }
    },

    /**
     * @desc Remove an element from an array
     */
    remove: function(arr, elem, cmp_fn){
        var na=[];
        for (var i=0; i<arr.length; i++){
            if (AP.isFunction(elem)){
                if (elem(arr[i])){
                }else{
                    na.push(arr[i]);
                }
            }else{
                if (cmp_fn){
                    if (!cmp_fn(arr[i],elem)){
                        na.push(arr[i]);
                    }
                }else{
                    if (!AP.data.equal(arr[i],elem)){
                        na.push(arr[i]);
                    }
                }
            }
        }
        return na;
    },

    removeByID: function(arr, id){
        return this.filter(arr, function(e){
            if (!AP.data.isInt(e.id) && !AP.data.isInt(id)){
                if (e.id === id){
                    return false;
                }

                return true;
            }


            if (parseInt(e.id)==parseInt(id)){
                return false;
            }

            return true;
        });
    },

    filter: function(arr, filter){
        var na=[];
        for (var i=0; i<arr.length; i++){
            if (filter(arr[i], i, arr.length)){
                na.push(arr[i]);
            }
        }
        return na;
    },

    unserialize: function(str){
        var r={};
        var parts=str.split('&');
        for (var i=0; i<parts.length; i++){
            var x=parts[i].split("=");
            if (x.length==2){
                r[x[0]]=x[1];
            }
        }
        return r;
    },

    select: function(arr, fn){
        var na=[];
        if (!arr || !arr.length){
            return na;
        }

        for (var i=0; i<arr.length; i++){
            var e=fn(arr[i], i, arr.length);
            if (e!==null){
                na.push(e);
            }
        }
        return na;
    },

    merge: function(){
        var r=[];
        for (var i=0; i<arguments.length; i++){
            if (AP.data.isObject(arguments[i]) && !AP.data.isArray(arguments[i])){
                r.push(arguments[i]);
            }else{
                for (var j=0; j<arguments[i].length; j++){
                    r.push(arguments[i][j]);
                }
            }
        }

        return r;
    },

    update: function(arr, fn){
        for (var i=0; i<arr.length; i++){
            arr[i] = fn(arr[i]);
        }
        return arr;
    },

    updateByKey: function(arr, obj, key) {
        if (!arr) {
            arr = [];
        }
        var item_exist = null;
        arr = this.update(arr, function(item) {
            if (se(item[key], obj[key])) {
                item = obj;
                item_exist = item;
            }
            return item;
        });
        if (!item_exist) {
            arr.push(obj);
        }
        return arr;
    },

    updateByID: function(arr, obj){
        return this.updateObjects(arr, obj);
    },
};

var ARR = AP.array;



AP.time = {
    months:[__('January'), __('February'), __('March'), __('April'),
        __('May'), __('June'), __('July'), __('August'), __('September'), __('October'), __('November'), __('December')],
	sMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],
	days:[__('Monday'), __('Tuesday'), __("Wednesday"), __('Thursday'), __('Friday'), __('Saturday'), __('Sunday')],
	sDays:["Mon","Tue", "Wed", "Thu","Fri","Sat","Sun"],
	tDays:["T2", "T3", "T4", "T5", "T6", "T7", "CN"],

    mktime: function(ts){
		if (!ts){
			t = new Date();
		}else{
			t = new Date(parseInt(ts)*1000);
		}

		return t;
	},

    /**
	 * @desc Handler time function.
	 */
	time:function(pattern, time_stamp){
		var t = this.mktime(time_stamp);

		var _year = t.getFullYear();
		var _month= t.getMonth()+1;

		var month=_month;
		if (_month<10){
			month="0"+_month;
		}

		var _day=(t.getDay()||7)-1;

		var _date=t.getDate();

		var date=_date;
		if (_date<10){
			date="0"+_date;
		}

		var _hour=t.getHours();
		var _hour12=(_hour%12);
		var hour=_hour;
		if (_hour<10){
			hour="0"+_hour;
		}

		var _minute=t.getMinutes();
		var _second=t.getSeconds();


		var r=pattern;
		var tday=AP.time.tDays[_day];
		var vday=AP.time.days[_day];

		// Day & Date
		r=r.replace("%d", date);
		r=r.replace("%D", AP.time.sDays[_day]);
		r=r.replace("%j", _date);
		r=r.replace("%l", AP.time.days[_day]);
		r=r.replace("%N", _day+1);
		r=r.replace("%w", _day);
		r=r.replace("%T", tday);
		r=r.replace("%v", tday);
		r=r.replace("%V", vday);

		// Month
		r=r.replace("%F", AP.time.months[_month-1]);
		r=r.replace("%m", month);
		r=r.replace("%M", AP.time.sMonths[_month-1]);
		r=r.replace("%n", _month);
		r=r.replace("%t", new Date(_year, _month, 0).getDate());

		// Year
		r=r.replace("%L", (new Date(_year, 1,29).getMonth()==1));
		r=r.replace("%o", _year);
		r=r.replace("%Y", _year);
		r=r.replace("%y", _year.toString().substr(2));

		// Hour & Minute & Second
		r=r.replace("%a", (_hour<12)?"am":"pm");
		r=r.replace("%A", (_hour<12)?"AM":"PM");
		r=r.replace("%g", _hour12);
		r=r.replace("%G", _hour);
		r=r.replace("%h", (_hour12<10)?("0"+_hour12):_hour12);
		r=r.replace("%H", (_hour<10)?("0"+_hour):_hour);
		r=r.replace("%i", (_minute<10)?("0"+_minute):_minute);
		r=r.replace("%s", (_second<10)?("0"+_second):_second);
		r=r.replace("%u", t.getMilliseconds()*1000);

		// Timezone
		r=r.replace("%Z", -t.getTimezoneOffset()*60);

		return r;
	},

    hm: function(time){
		var h=AP.data.zeroPrefix(Math.floor(time/3600));
		var m=AP.data.zeroPrefix(Math.floor((time-h*3600)/60));
		return h+":"+m;
	},

	beginOfDay: function(time_stamp){
		var t = this.mktime(time_stamp);
		return AP.time.timeStamp(new Date(t.getFullYear(), t.getMonth(), t.getDate()));
	},

	beginOfMonth: function(time_stamp){
		var t = this.mktime(time_stamp);
		return AP.time.timeStamp(new Date(t.getFullYear(), t.getMonth(), 1));
	},

	endOfMonth: function(time_stamp){
		var t = this.mktime(time_stamp);
		return AP.time.timeStamp(new Date(t.getFullYear(), t.getMonth()+1, 0));
	},

    beginOfWeek: function(time_stamp){
		return AP.time.firstDayOfWeek(time_stamp);
	},

	endOfWeek: function(time_stamp){
		return AP.time.firstDayOfWeek(time_stamp)+6*24*3600;
	},

	sameDay: function(ts1, ts2){
		return AP.time.beginOfDay(parseInt(ts1))==AP.time.beginOfDay(parseInt(ts2));
	},

	sameYear: function(ts1, ts2){
		return AP.time.time("%Y",ts1)==AP.time.time("%Y",ts2);
	},
	sameMonth: function(ts1, ts2){
		return AP.time.time("%m%Y",ts1)==AP.time.time("%m%Y",ts2);
	},
	sameWeek: function(ts1, ts2){
		return AP.time.firstDayOfWeek(parseInt(ts1))==AP.time.firstDayOfWeek(parseInt(ts2));
	},

    /**
	 * @desc Get the previous Monday
	 * @param time_stamp
	 * @returns
	 */
	firstDayOfWeek: function(time_stamp){
		var t = this.mktime(time_stamp);

		// Get the first day of week [Return timestamp]
		var day=(t.getDay() || 7)-1;

		t.setHours(-24 * day);
		t.setSeconds(0);
		t.setMinutes(0);
		t.setHours(0);

		return AP.time.timeStamp(t);
	},

    /**
	 * @desc Get the first day of the current month
	 * @param time_stamp
	 * @returns
	 */
	firstDayOfMonth: function(time_stamp){
		var t = this.mktime(time_stamp);

		t.setDate(1);
		t.setSeconds(0);
		t.setMinutes(0);
		t.setHours(0);

		return AP.time.timeStamp(t);
	},



	timeStamp:function(d){
		if (!d){
			d=new Date();
		}
		return Math.floor(d.getTime()/1000);
	},

	now: function(){
		return Math.floor((new Date()).getTime()/1000);
	},

	date: function(time_stamp){
		return this.mktime(time_stamp);
	},

	ago: function(time_stamp){
		time_stamp=parseInt(time_stamp);
		var t = this.timeStamp();
		var diff=t-time_stamp;

		if (diff<5){
			return __('-- few seconds ago');
		}
		if (diff<60){
			return diff+" "+ __('-- seconds ago');
		}
		if (diff<3600){
			return Math.floor(diff/60)+" "+ __('-- minutes ago');
		}
		if (diff<3600*24){
			return Math.floor(diff/3600)+" "+ __('-- hours ago');
		}
		return Math.floor(diff/86400)+" "+__('-- days ago');
	},


	late: function(actual_time, deadline){
		if (!deadline){
			deadline=0;
		}

		var diff=parseInt(actual_time)-parseInt(deadline);
		if (diff<0){
			return "---";
		}

		if (diff<5){
			return lang("few seconds");
		}
		if (diff<60){
			return diff+" "+lang('seconds');
		}

		if (diff<3600){
			return Math.floor(diff/60)+"m";
		}

		if (diff<3600*24){
			var h=Math.floor(diff/3600);
			var min=Math.floor((diff-h*3600)/60);
			return h+"h"+min+"m";
		}

		var h=Math.floor(diff/86400);

		if (h==1){
			return h+" "+lang('day');
		}

		return h+" "+lang('days');
	},

    diff: function(from, to){
		from = parseInt(from);
		to = parseInt(to);

		if (to<=from){
			return {year: 0, day: 0, day_counts: 0};
		}


		from = this.beginOfDay(from);
		to = this.beginOfDay(to);

		var df = new Date(from * 1000);
		var dt = new Date(to * 1000);

		var r = {year: dt.getFullYear() - df.getFullYear(), day: 0, day_counts: Math.floor((to-from)/(24*3600))};

		var same_year = new Date(from*1000);
		same_year.setFullYear(dt.getFullYear());
		var sy_ts = this.timeStamp(same_year);

		if (sy_ts <= to){
			r.day = Math.floor((to - sy_ts)/(24*3600));
		}else{
			r.year = r.year-1;
			same_year.setFullYear(dt.getFullYear()-1);
			sy_ts = this.timeStamp(same_year);
			r.day = Math.floor((to - sy_ts)/(24*3600));
		}

		return r;
	}
}



AP.data = new function __APData() {
    this.isArray=function(data){
		return $.isArray(data);
	};
	this.isAssocArray=function(data){
		return typeof(data)=='object' && isNaN(data);
	};
	this.isObject=function(data){
		return typeof(data)=='object' && isNaN(data);
	};
	this.isFunction=function(data){
		return $.isFunction(data);
	};
	this.isInt=function(data){
		return !isNaN(data)&&parseInt(data)==data;
	};
	this.isNumber=function(data){
		return !isNaN(data)&& !isNaN(parseFloat(data));
	};
	this.isString=function(data){
		return typeof(data)=='string' && isNaN(data);
	};
	this.isEmpty=function(data){
		if (!data || data.length <=0){
			return true;
		}
		return false;
	};
	this.int=function(val){
		return parseInt(val);
	};

    this.randomInteger=function(min, max){
		return Math.floor(Math.random() * (max - min)) + min;
	};

	this.randomNumber=this.randomInteger;

    this.numberFormat=function(ival){
		var parts=ival.toString().split(".");
		return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1].substr(0,2) : "");
	};

	this.zeroIndex=function(ival){
		ival=parseInt(ival);
		if (ival === 0){
			return "0";
		}

		if (ival<10){
			ival="0"+ival;
		}
		return ival;
	}

	this.zeroPrefix=function(ival){
		return this.zeroIndex(ival);
	}

    this.equal=function(x, y){
		if (AP.data.isInt(x)){
			x=x.toString();
		}
		if (AP.data.isInt(y)){
			y=y.toString();
		}

		if (AP.data.isAssocArray(x) && AP.data.isAssocArray(y)){
			return (JSON.stringify(x)==JSON.stringify(y));
		}

		if (AP.data.isArray(x) && AP.data.isArray(y)){
			if (x.length!=y.length){
				return false;
			}
			for (var i=0; i<x.length; i++){
				if (!AP.data.equal(x[i], y[i])){
					return false;
				}
			}
			return true;
		}

		return (x==y);
	};
}

function safeEquals(x, y){
    return AP.data.equal(x, y);
};
var se = safeEquals;



AP.word={
	empty: function(data){ 
		if (typeof data=='undefined'){
			return true;
		}
		if (data===false) return true;
		if (data==="") return true;
		if (data===null) return true;
		if (data.length==0) return true;
		return false;
	},

	good: function(data){
		return typeof(data)=='string' && isNaN(data);
	},

	prefix:function(origin, pre){
		if (!pre || !origin){
			return false;
		}
		if (origin.substring(0, pre.length)==pre){
			return true;
		}
		return false;
	},
	
	suffix:function(origin, suf){
		if (!suf || !origin || origin.length<suf.length){
			return false;
		}
		
		if (origin.substr(origin.length-suf.length, suf.length)==suf){
			return true;
		}
		return false;
	},
	
	isURL:function(url){
		if (this.prefix(url, 'http:') || this.prefix(url, 'https:')){
			return true;
		}
		return false;
	},

	upper: function(data){
		return data.toUpperCase();
	},

	replace: function(str, search, replace){
		return str.replace(new RegExp(search, 'g'),replace);
	},
	
	replaceAll:function(search, replace, str){
		return str.split(search).join(replace);
	},

	join: function(arr, joiner, fn){
		var html="";
		for (var i=0; i<arr.length; i++){
			if (i<arr.length-1){
				html+=fn?fn(arr[i]):arr[i];
				html+=joiner;
			}else{
				html+=fn?fn(arr[i]):arr[i];
			}
		}
		return html;
	},

	split: function(splitter, str, no_spaces){
		if (!no_spaces){
			no_spaces=false;
		}
		var parts=str.split(splitter);
		var results=[];
		for (var i=0; i<parts.length; i++){
			 var s=parts[i];
			 if (no_spaces){
				 s=$.trim(parts[i]);
			 }
			 if (s && s.length>=1){
				 results.push(s);
			 }
		}
		return results;
	},

	match: function(word, pattern){
		return word.match(pattern);
	},

	quickMatch: function(w, q){
		return w.toLowerCase().indexOf(q.toLowerCase())!=-1;
	},

	random: function(len){
		return AP.random.word(len);
	},
	
	compare: function(w1, w2){
		if (!w1){
			return 0;
		}
		
		return w1.localeCompare(w2)	
	},

	shorten: function(word, max_length, tail){
		word=safe(word);
		
		if (!tail){
			tail='...';
		}
		if (word.length <max_length){
			return word;
		}
		return word.substr(0, max_length-1)+tail;
	},

	fulltextMatch: function(w, q){
		var haystack=purify(w.toLowerCase()).replace(/\s/g,'');
		var neddle=purify(q.toLowerCase()).replace(/\s/g,'');
		
		return haystack.indexOf(neddle)!=-1;
	},

	safeSplit: function(splitter, str){
		return this.split(splitter, str, true);
	},
}


AP.gb = new function __APGB(){
	var __callbacks=[];
	
	this.clear = function(){
		while (true){
			if (!__callbacks || !__callbacks.length){
				break;
			}
			
			var fn = __callbacks.shift();
			if (fn && AP.data.isFunction(fn)){
				fn();
			}
		}
	};
	
	
	this.register = function(fn){
		__callbacks.push(fn);
	};
	
	
};


var Rewrite = new function __Rewrite(){
    this.on = function(pattern, callback){
		var actions=[];
		
		var str=pattern.replace(/\{([a-z]+)\}/g, function(ms, m){
			actions.push(m);
			
			if (m=="id" || m=="int"){
				return '([0-9]+)'
			}
			
			return '([a-zA-Z0-9\\.\\-]+)';
		});
		
		var actions_url = AP.render(actions, function(e, index){
			if (index==0){
				return ""+(e)+"=$"+(index+1)+"";
			}
			
			return "&"+(e)+"=$"+(index+1)+"";
		});
		
		actions_url="action?"+actions_url;
		
		AP.rewrite(str, actions_url, function(qs){
			callback.apply(this, [qs]);
		}, true);
	};
};


AP.dialog=function(id, engine){
	if (!engine){
		var _engine = $(id).data("_engine");

		if (_engine){
			return new APDialog(id, _engine);
		}

		engine=AP.config.dialog.engine;
	}

	return new APDialog(id, engine);
};

AP.dialog.get=function(ref){
	if ($(ref).closest(".__apdialog")){
		var id = $(ref).closest(".__apdialog").attr("id");
		return AP.dialog("#"+id);
	}

	return AP.dialog(ref);
};


AP.dialog.close=function(ref){
	return AP.closeDialog(ref);
};

AP.closeDialog=function(ref){
	if ($(ref).closest(".__dialog").hasClass("__fdialog")){
		if (AP.isset('Form')){
			var rt = Form.protection.runtime();
			if (!rt){
				return false;
			}
		}
	}

	var dx=$(ref).closest('.__dialog').find(".__apdialog").attr("id");
	$("#"+dx).html("").empty();
	AP.dialog("#"+dx).hide();

	AP.fire("dialog-close-"+dx);

	var $w=$(ref).closest('.__dialog');
	var events=$w.data("apevents");
	if (events && events.close){
		events.close.apply($w);
	}
};

AP.destroyDialog=function(id){
	var $dx=$("#__apdialog_"+id.substr(1));
	if (!$dx.length){
		return;
	}

	var events=$dx.data("apevents");
	if (events && events.close){
		events.close.apply($w);
	}

	if ($(id).length){
		AP.dialog(id.substr(1)).hide();
	}

	$dx.html("").empty();

	$dx.remove();
};

function APDialog(id, engine){
	this._rendered=false;
	this._temp=true;
	this._buttons={};
	this._bs={};
	this._title="Untitled";
	this._content="";
	this._classes=[];
	this._css={};
	this._data={};
	this._config={};
	this._icon=null;
	this._closable=false;
	this._close_button=true;
	this._size = "mini";

	this._engine=engine;
	if (AP.word.prefix(id,"#")){
		id=id.substr(1);
	}

	if (!AP.html.exist("#"+id)){
		$(document.body).append("<div id='"+id+"'></div>");
	}else{
		var title=$("#"+id).attr('title');
		if (title){
			this._title=title;
		}
	}

	if (engine){
		$("#"+id).data("__engine", engine);
	}else{
		engine=$("#"+id).data("__engine");
		this._engine=engine;
	}

	if ($("#"+id).data("icon")){
		this._icon=$("#"+id).data("icon");
	}

	this._id=id;


	this.data=function(key, value){
		if (typeof value=="undefined"){
			if (key in this._data){
				return this._data[key];
			}
			return null;
		}else{
			this._data[key]=value;
			return this;
		}
	};


	this.setData=function(data){
		this._data=data;
	};

	this.closable=function(flag){
		this._closable=flag;
		return this;
	};

	this.closeButton=function(flag){
		this._close_button=flag;
		return this;
	};

	this.size = function(size) {
		this._size = size;
		return this;
	}

	this.temp=function(flag){
		this._temp=flag;
		return this;
	};

	this.style=function(css_style){
		if (css_style){
			this._classes.push(css_style);
		}
		return this;
	};



	this.addClass=function(css_style){
		return this.style(css_style);
	};

	this.css=function(key, value){
		this._css[key]=value;
		return this;
	};

	this.icon=function(icon_class){
		this._icon=icon_class;
	}

	this.engine=function(engine){
		this._engine=engine;
		return this;
	};


	this.config=function(config){
		this._config=$.extend({}, this._config, config);
		return this;
	};

	this.balance=function(timeout){
		if (!timeout){
			this._engine.balance(this);
		}else{
			var $this=this;
			setTimeout(function(){
				$this._engine.balance($this);
			},timeout);
		}
		return this;
	};

	this.button=function(label, fn, style, content = ''){
		var counter=0;
		for (button in this._buttons){
			counter++;
		}
		if (counter==0){
			this.find("buttons").cleanUp();
		}
		var ec='__default';
		if (style){
			ec=style;
		}


		this._buttons[label]=fn;
		this._bs[label]={'style':ec,'fn':fn, 'content': content};

		if (this.initialized()){
			$("<div class='core-form-button "+ec+"'>"+label+content+"</div>").bind('click',{fn: fn},function(event){
				event.data.fn();
			}).appendTo(this.find("buttons"));
		}
		return this;
	};

	this.title=function(title){
		if (title==undefined){
			title=this._title;
		}
		this._title=title;
		if (this.initialized()){
			if (this._icon){
				title="<span class='dialog-icon ap-f14 "+this._icon+"'></span>&nbsp; "+title;
			}
			this.fix('title', title);
		}
		return this;
	};

	this.content=function(content){
		if (content != undefined){
			this._content=content;
		}

		if (this.initialized() && !AP.isEmpty(this._content)){
			$(this.id()).children().empty();
			$(this.id()).html(this._content);
		}
		return this;
	};


	this.append=function(id){
		$(id).appendTo($(this.id()));
		return this;
	};

	this.width=function(width){
		if (Client.native || Client.mobile){
			return this;
		}

		if (AP.data.isInt(width)){
			if (Client.native || Client.mobile){
			}else{
				$(this.id()).css("width", width+"px");
			}
		}else{
			$(this.id()).css("width", width);
		}
		return this;
	};

	this.id=function(){
		return "#"+this._id;
	};

	this.w=function(omit){
		if (omit){
			return "__apdialog_"+this._id;
		}
		return "#__apdialog_"+this._id;
	};

	this.canvas=function(){
		return this._engine.canvas();
	};

	this.initialized=function(){
		if (!AP.html.exist(this.id()) || !$(this.id()).hasClass('__apdialog')){
			return false;
		}
		return true;
	};

	this.render=function(){
		if (!this.initialized()){
			this._engine.render(this);
			$(this.id()).data("config", this._config);
			$(this.id()).data("_engine", this._engine);
			$(this.id()).show().addClass('__apdialog').appendTo($(this.find('content'))).attr("title","");

			var classes=this._classes.join(" ");
			if (classes){
				$(this.w()).addClass(classes);
			}

			for (var k in this._css){
				$(this.id()).css(k, this._css[k]);
			}

			if (this._temp){
				$(this.w()).addClass("__temp");
			}
			$(this.w()).addClass("__dialog");
		}

		this._rendered=true;
		this.title();
		this.content();
		this.buttons();

		var $this=this;
		AP.html.resize(function(){
			$this.balance();
		}, true);

		return this;
	};

	this.buttons=function(buttons){
		if (buttons && typeof buttons!=undefined){
			if (AP.data.isArray(buttons)){
				for (var i=0; i<buttons.length; i++){
					if (!buttons[i].style){
						buttons[i].style='__ap_default_button';
					}

					this.button(buttons[i].label, buttons[i].action, buttons[i].style);
				}
			}else{
				for (var button in buttons){
					this.button(button, buttons[button],'__ap_default_button');
				}
			}
		}

		if (!this._rendered){
			this.find("buttons").cleanUp();
		}

		for (var button in this._buttons){
			this.button(button, this._bs[button].fn, this._bs[button].style,  this._bs[button].content);
		}
		return this;
	};

	this.find=function(comp){
		var c=this.w()+" .__dialog"+comp;
		return $(c).first();
	};


	this.cond=function(cond, fn){
		if (cond){
			fn.apply(this);
		}

		return this;
	};

	this.show=function(){
		if (!this.initialized()){
			this.render();
		}


		$(this.canvas()).show();
		$(this.canvas()).children().each(function(){
			$(this).removeClass('__dialog_ontop');
		});

		$(".__ontop").removeClass("__ontop");
		$(this.w()).show().addClass('__dialog_ontop').appendTo($(this.canvas()));

		if (AP.config.disableParentScrolling && AP.sys.isTablet()){
			$("html, body").addClass("xo");
		}else if (this._config.disableParentScrolling){
			$("html, body").addClass("xo");
		}


		if (this._closable && !$(this.w()).hasClass("__canvas_closable")){
			$(this.w()).addClass("__canvas_closable");
			$("<div class='__closable'></div>").prependTo($(this.w())).click(function(){
				var id=$(this).closest(".__dialog").find(".__apdialog");
				AP.dialog("#"+id.attr("id")).hide();
			});
		}
		return this;
	};


	this.on=function(events){
		$(this.w()).data("apevents", events);
	};

	this.hide=function(){
		$(this.w()).hide();
		var config=$(this.id()).data("config");
		var counter=0;
		$(this.canvas()).children().each(function(){
			if ($(this).is(":visible")){
				counter++;
				return;
			}
		});
		if (counter==0){
			$(this.canvas()).hide();
		}

		if (AP.config.disableParentScrolling && AP.sys.isTablet()){
			$("html, body").removeClass("xo");
		}else if (config && config.disableParentScrolling){
			$("html, body").removeClass("xo");
		}

		return this;
	};

	this.close = function(){
		this.hide();
		AP.destroyDialog(this.id());
	};



	this.formatForm=function(){
		$(this.id()+' input[type=file]').selectFiles({label:"Select File"});
		$(this.id()+' textarea').disableTab();
		return this;
	};

	this.rerender=function(){
		this._rendered=false;
	};

	this.fix=function(key, val){
		this.find(key).html(val);
	};
};



AP.scrollBar=function __APScrollBar(selector, callback = false){
	return new APScrollBar($(selector), callback);
};

function APScrollBar($obj, callback = false){
	this.$obj=$obj;

	this.init=function(temp){
		temp=false;
		if (temp){
			temp=true;
		}

		if (this.$obj.hasClass('__apscrollbar_target')){
			plugin_scrollbar_onscroll(this.$obj);
			return this;
		}

		var id=this.$obj.attr('id');
		if (!id){
			id=AP.uuid();
			this.$obj.attr('id', id);
		}

		this.$obj.addClass('__apscrollbar_target');
		if (this.$obj.parent().data('autoscroll')){
			this.$obj.addClass('__scrolled');
		}


		if (this.$obj.parent().hasClass('__apscrollbar_parent')){
			return this;
		}

		this.$obj.parent().addClass('__apscrollbar_parent');


		if (this.$obj.parent().data("autohide")){
			this.$obj.parent().addClass("__autohide");
			this.$obj.wrapInner("<div class='__apscrollbar_wrap __autohide' style='padding-right:0px'></div>");
		}else{
			this.$obj.addClass("__regular").wrapInner("<div class='__apscrollbar_wrap'></div>");
		}

		$("<div id='"+id+"__apscrollbar' class='__apscrollbar'> <div class='scroller'>" +
					"<div class='sinner'></div> "+
				"</div> </div>").appendTo(this.$obj.parent());

        var page = 1;
        var prevent_page_loader = false;
        var origin_scrollable = this.$obj.closest(".core-scrollable");
		this.$obj.on("scroll", function(){
			if ($(this).hasClass('__scrollprevented')){
				return;
			}
            if(AP.data.isFunction(callback) && !prevent_page_loader
                && ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight)) {
                UI.ajaxShow();
                AP.post(origin_scrollable.data('path'), {_a: origin_scrollable.data('action'), page: page + 1}, function(code) {
                    UI.ajaxHide();
                    if (!code.good()) {
                        return AP.toastr.error(code.message);
                    }
                    callback(origin_scrollable.find(".__apscrollbar_wrap"), code.data);
                    if (code.data.length == 0 || code.data.length < Number(origin_scrollable.data('limit'))) {
                        return prevent_page_loader = true;
                    }
                    page++;
                });
            }
			return plugin_scrollbar_onscroll($(this));
		});

		plugin_scrollbar_update($('#'+id+'__apscrollbar .scroller'));

		setTimeout(function(){
			plugin_scrollbar_update($('#'+id+'__apscrollbar .scroller'));
		},1000);

		setTimeout(function(){
			plugin_scrollbar_update($('#'+id+'__apscrollbar .scroller'));
		},5000);

		return this;
	};


	/**
	 * @desc ScrollTo a specific pixel height
	 */
	this.scrollTo=function(num){
		// var h=this.$obj.height();
		// var maxh=this.$target[0].scrollHeight;

		this.$obj.scrollTop(num);
	};


	this.update=function(){
		if (AP.sys.isTablet() || AP.sys.isMobile() || AP.__printing || Client.mobile){
			return this;
		}

		plugin_scrollbar_update($("#"+this.$obj.attr('id')+"__apscrollbar .scroller"));
		return this;
	};
};

function plugin_scrollbar_update($obj){
	var offset=$obj.position();

	var $scroller=$obj.parent();
	var $scroller_rec=$obj;

	var $target=$scroller.prevAll('.__apscrollbar_target');
	if (!$target || !$target.length){
		return;
	}

	var h=$target.height();
	var maxh=$target[0].scrollHeight;

	var auto=$obj.closest('.__apscrollbar_parent').data('autoscroll');


	if (maxh<=h){
		if (!auto){
			$scroller.hide();
			$target.scrollTop(0);
			$target.scrollLeft(0);
			$target.removeClass('__scrolled');
			$scroller.hide();
			return;
		}else{
			$scroller_rec.hide();
			$target.addClass('__scrolled');
			return;
		}
	}

	$scroller.show();
	$scroller_rec.show();

	if (maxh<10 || h<10){
		/**
		 * @todo Finish this weird case
		 */
		return;
	}

	var sh=$scroller.height();

	if (sh<=$obj.height()){
		$target.scrollTop(maxh-h);
		return;
	}

	var scale=$scroller.parent().data("scale");
	if (!scale){
		scale=1.0;
	}else{
		scale=parseFloat(scale);
	}

	scale=1.0;

	var ttop=(maxh-h)*offset.top*1.0/(sh-$obj.height());
	ttop=Math.floor(ttop);

	$target.scrollTop(ttop);
	$target.scrollLeft(0);
};

function plugin_scrollbar_onscroll($obj){
	var alwayshown=$obj.parent().data('autoscroll');
	var autohide=$obj.parent().data('autohide');

	if (!$obj.is(':visible')){
		return;
	}

	// $obj.scrollLeft(0);
	// return;

	var t=$obj.scrollTop();
	var h=$obj.height();

	if (!('scrollHeight' in $obj[0])){
		return;
	}



	var maxh=$obj[0].scrollHeight;
	var $scroller=$("#"+$obj.attr('id')+"__apscrollbar");

	if (maxh<h || maxh<10){
		if (!alwayshown){
			$obj.removeClass('__scrolled');
			$scroller.hide();
		}
		return;
	}


	if (maxh==h){
		if (!alwayshown){
			$obj.removeClass('__scrolled');
			$scroller.hide();
		}
		return;
	}


	if (!$obj.hasClass('__scrolled')){
		$obj.addClass('__scrolled');
	}


	$scroller.show();

	if (h<0){
		return;
	}



	var sh=$scroller.height();
	var scale=$scroller.parent().data("scale");

	if (!scale || typeof scale=="undefined"){
		scale=1.0;
	}else{
		scale=parseFloat(scale);
	}

	var scroller={};
	scroller.height=Math.floor((h*1.0/maxh)*(h*1.0/maxh) *sh)*scale;
	if (autohide){
		scroller.height=Math.floor((h*1.0/maxh)*sh)*scale;
	}

	if (scroller.height<50){
		scroller.height=50;
	}

	scroller.top=Math.floor(Math.min(t*1.0/(maxh-h), 1) * (sh-scroller.height));


	$scroller.children('.scroller').css({'top': scroller.top, 'height': scroller.height}).addClass('active').show();
	$scroller.find('.sinner').css('height',scroller.height-1);
};



AP.i18n=new function __APi18n(){
	this.confs={date_format: "dmy", time_format:"hm"};
	
	this.get=function(key){
		var confs=$.extend(this.confs, Client.i18n);
		return confs[key];
	};
	
	this.dateFormat=function(){
		var format=this.get("date_format");
		if (format=="dmy"){
			return "%d/%m/%Y";
		}else if (format=="full"){
			return "%l, %F %d, %Y";
		}else{
			return "%m/%d/%Y";
		}
	};
	
	this.date=function(ts){
		return AP.time.time(this.dateFormat(), ts);
	};
	
	this.safeDate=function(ts){
		if (!ts || !parseInt(ts)){
			return '<span>---</span>';
		}
		
		return this.date(ts);
	};
	
	this.datetime=function(ts){
		return AP.time.time("%H:%i "+this.dateFormat(), ts);
	};
	
	this.time=function(ts){
		return AP.time.time("%H:%i", ts);
	};
	
	this.readDate=function(str){
		var data=str.split("/");
		if (data.length!=3){
			return 0;
		}
		
		var day=parseInt(data[0]);
		var month=parseInt(data[1])-1;
		var year=parseInt(data[2]);
		
		var ts=new Date(year, month, day, 0, 0, 0, 0);
		return Math.floor(ts.getTime()/1000);
	};
	
	this.dateRange=function(stime, etime){
		stime=parseInt(stime);
		etime=parseInt(etime);
		
		if (etime){
			if (AP.time.sameYear(stime, etime)){
				return AP.time.time("%d/%m", stime)+" - " + AP.time.time("%d/%m/%y", etime);
			}else{
				return AP.time.time("%d/%m/%y", stime)+" - " + AP.time.time("%d/%m/%y", etime);
			}
		}else{
			if (parseInt(stime)){
				return AP.time.time("%d/%m/%y", stime)+" &#8702; ... ";
			}else{
				return "... "+" &#8702; ... ";	
			}
		}
	};
	
	
	this.timeRange=function(stime, etime){
		stime=parseInt(stime);
		etime=parseInt(etime);
		
		if (etime){
			if (AP.time.sameYear(stime, etime)){
				return AP.time.time("%H:%i %d/%m", stime)+" - " + AP.time.time("%H:%i %d/%m", etime);
			}else{
				return AP.time.time("%H:%i %d/%m", stime)+" - " + AP.time.time("%H:%i %d/%m", etime);
			}
		}else{
			return AP.time.time("%H:%i %d/%m/%y", stime)+" &#8702; ... ";
		}
	};
	
	this.range=this.dateRange;
	

	this.range2=function(stime, etime){
		stime=parseInt(stime);
		etime=parseInt(etime);
		
		if (etime){
			if (AP.time.sameYear(stime, etime)){
				return AP.time.time("%d/%m", stime)+" - " + AP.time.time("%d/%m/%Y", etime);
			}else{
				return AP.time.time("%d/%m/%Y", stime)+" - " + AP.time.time("%d/%m/%Y", etime);
			}
		}else{
			if (parseInt(stime)){
				return AP.time.time("%d/%m/%Y", stime)+" &#8702; ... ";
			}else{
				return "... "+" &#8702; ... ";	
			}
		}
	};
	
	
	
	this.duration=function(total_seconds, compact){
		if (compact){
			return this.durationCompact(total_seconds);
			
		}
		
		var s=parseInt(total_seconds);
		if (s<3600){
			var m=Math.floor(s/60);
			return "<em>"+(m)+"</em>m";
		}
		
		if (s<48*3600){
			var h=Math.floor(s/3600);
			var m=Math.floor((s-h*3600)/60);
			return "<em>"+(h)+"</em>h<em>"+(m)+"</em>m";
		}
		
		var d=Math.floor(s/(24*3600));
		var h=Math.floor((s-d*24*3600)/3600);
		var m=Math.floor((s-d*24*3600-h*3600)/60);
		return "<em>"+(AP.data.numberFormat(d))+"</em>d<em> "+(AP.data.numberFormat(h))+"</em>h<em> "+(AP.data.numberFormat(m))+"</em>m";
	};
	
	
	this.durationCompact=function(total_seconds){
		var s=parseInt(total_seconds);
		if (s<3600){
			var m=parseFloat(s/60).toFixed(1);
			return "<em>"+(m)+"</em>m";
		}
		
		if (s<48*3600){
			var h=parseFloat(s/3600).toFixed(1);
			return "<em>"+(h)+"</em>h";
		}
		
		var d=parseFloat(s/(24*3600)).toFixed(1);
		return "<em>"+(d)+"</em>d";
	};
	
	
	
	function getTimezones(){
		var opts = range(-12, 12);
		var r = [];
		
		for (var i=0; i<opts.length; i++){
			var sign ='+';
			if (opts[i]<0){
				sign = '';
			}
			
			r.push({value: opts[i], label: "{{GMT ~timezone}}"+(sign)+""+(opts[i])+""})
		}
		
		return r;
	};
	
	
	function getMonths(){
		var opts = range(1, 12);
		var r = [];
		for (var i=0; i< opts.length; i++){
			r.push({value: opts[i], label: AP.time.months[opts[i]-1]})
		}
		
		return r;
	};
	
	
	this.options = {
		timezones: getTimezones(),
		monthes: getMonths(),
	}
	
};


var Textarea=new function __TextArea(){
	this.simple=function(str){
		if (!str){
			return "";
		}
		
		return AP.word.replaceAll("<br>","\n", str);
	};
	
	this.clean=function(_str){
		if (!_str){
			return "";
		}
		
		if (!AP.data.isString(_str)){
			return _str;
		}
		
		var str = (' '+_str).slice(1);
		
		var regex = /<br\s*[\/]?>/gi;
		str = str.replace(regex, "\n").replace(/&#8220;/g, "\"").replace(/&#8221;/g, "\"").replace(/&#8216;/g, "'").replace(/&#8217;/g, "'");
		str = str.replace(/{{@[a-zA-Z][a-zA-Z]+}}/g, function(m){
			return m.substr(2, m.length-4);
		});
		
		return str;
	};
	
	
	this.raw=function(str){
		if (!AP.data.isString(str)){
			return str;
		}
		
		var temp=this.clean(str);
		return temp.replace(/\&#126;/g, '~').replace(/\&gt;/g, '>').replace(/\&lt;/g, '<');
	};
	
	
	this.editor = function(val){
		var str = (' '+val).slice(1);
		
		str = str.replace(/{{@[a-zA-Z][a-zA-Z]+}}/g, function(m){
			return m.substr(2, m.length-4);
		});
		
		return str;
	};
};



(function($){
    var _scrollbarWidth=0;
	$.sbWidth=function(){
		if (!_scrollbarWidth){
			_scrollbarWidth=getScrollbarWidth();
		}
		return _scrollbarWidth;
	};

    $.fn.lock=function(){
		var data=$(this).data("__b_lock");
		if (!data || data===0){
			$(this).data("__b_lock", 1);
			return true;
		}
		return false;
	};

	$.fn.cleanUp=function(){
		$(this).children().remove();
		$(this).empty();
		return $(this);
	};

	$.fn.enter=function(action){
		var $this=$(this);
		$this.data("enter", action);
		$this.addClass("__ap_enter_binded");
		
		$(this).keydown(function(e){
			var key=e.keyCode? e.keyCode:e.which;
			if (key == AP.key.enter && !e.shiftKey){
				var id=$this.attr('id');
				if (id){
					var $tid=$("#__tag_"+id);
					if ($tid.length && $tid.is(":visible")){
						return;
					}
				}
				
				e.preventDefault();
				action.apply(this);
			}
		});
		
		return $this;
	};

	var delay_timer=null;
	$.fn.quickFilter=function(selectors, filter_fn){
		$(this).on("input change", function(){
			var $this = $(this);
			clearTimeout(delay_timer);
			
			delay_timer = setTimeout(function(){
				var val=$this.val();
				if (!val || !val.length){
					return $(selectors).show();
				}
				
				val=val.toLowerCase();
				
				$(selectors).each(function(){
					if (filter_fn($(this), val)){
						$(this).show();
					}else{
						$(this).hide();
					}
				});
			}, 300);
		});
		
		var q =$(this).data("query");
		if (q && q.length && Query.get(q)){
			$(this).val(Query.get(q)).trigger("change");
		}
	};

	$.fn.setCursorPosition = function(pos) {
		if ($(this).get(0).setSelectionRange) {
			$(this).get(0).setSelectionRange(pos, pos);
		}else if ($(this).get(0).createTextRange) {
			var range = $(this).get(0).createTextRange();
			range.collapse(true);
			range.moveEnd('character', pos);
			range.moveStart('character', pos);
			range.select();
		}
	};

	$.fn.screencopy=function(url, success, __data){
		if (!__data){
			__data={};
		}
		
		$(this).bind("paste", function(ev){
			var $this = $(this);
			var original =  ev.originalEvent;
			if (!original.clipboardData || !original.clipboardData.items || !original.clipboardData.items.length){
				return;
			}
			var raw=original.clipboardData.items[0];
			if (typeof raw !='object'){
				return;
			}
			
			var file =  raw.getAsFile();
			if (!file || !file.size || !file.type){
				return;
			}
			
			var reader = new FileReader();
			
			reader.onload = function (evt) {
				var result = evt.target.result; 
				var arr = result.split(",");
				var data = arr[1]; // raw base64
				var contentType = arr[0].split(";")[0].split(":")[1];
				
				var temp=__data;
				temp.contentType=contentType;
				temp.data=data;
				temp.__ss=1;
				
				$this.parent().ajaxShow();
				AP.post(url, temp, function(code){
					$this.parent().ajaxHide();
					
					if (!code.good()){
						return AP.alertError(code.message);
					}
					
					success(code, $this);
				});
			};
			
			reader.readAsDataURL(file);
		});
		
		return this;
	};

	$.fn.setActiveURL=function(url){
		if (AP.data.isFunction(url)){
			var fn=url;
			$(this).each(function(){
				var curl=$(this).data("url");
				if (!curl || !curl.length){
					curl=$(this).data("xurl");
				}
				if (!curl){
					curl="";
				}
				
				var data={};
				var parts=curl.split("?");
				if (parts.length==2){
					data=queryStringToArray(parts[1]);
				}
				
				if (fn.apply(this, [curl, data])){
					$(this).addClass("core-active");
				}else{
					$(this).removeClass("core-active");
				}
			});
			return;
		}
		
		var base="";
		var fallback=null;
		if (AP.data.isObject(url) && url.base){
			base=url.base+"/";
		}
		
		if (AP.data.isObject(url) && url.fallback){
			fallback=url.fallback;
		}
		
		var maxscore=-1;
		var set=0;
		if (url && url.length && !AP.data.isObject(url)){
			
			$(this).each(function(){
				var curl=$(this).data("url");
				if (!curl || !curl.length){
					curl=$(this).data("xurl");
					curl=base+curl;
				}
				
				if (curl==url){
					// set = 1;
					$(this).addClass("core-active");
				}else{
					$(this).removeClass("core-active");
				}
			});
		
			return;
		}
		$(this).each(function(){
			var turl=$(this).data("url");
			if (!turl){
				turl=base+$(this).data("xurl");
			}
			
			var score=computeURLSimilarity(turl);
			// console.log(turl);
			// console.log(score);
			$(this).data("active-score", score);
			if (score>maxscore){
				maxscore=score;
			}
		});
		$(this).each(function(){
			if (set){
				// return;
			}
			if ($(this).data("active-score")== maxscore && maxscore>0){
				set=1;
				$(this).addClass('core-active');
			}else{
				$(this).removeClass('core-active');
			}
		});
		
		if (!set && fallback){
			
			if (fallback==":first"){
				$(this).first().addClass("core-active");
				return;
			}
			
			$(this).each(function(){
				var turl=$(this).data("url");
				if (!turl){
					turl=$(this).data("xurl");
				}
				
				if (turl==fallback){
					$(this).addClass('core-active');
				}else{
					$(this).removeClass('core-active');
				}
			});	
		}
	};

	$.fn.setActive=function(chosen){
		if (AP.isInt(chosen)){
			$(this).each(function(index){
				$(this).removeClass('core-active');
				if (index==chosen){
					$(this).addClass('core-active');
				}
			});
		}else{
			if (chosen == ":first"){
				$(this).first().addClass("core-active");
				return;
			}
			
			if (chosen == ":last"){
				$(this).last().addClass("core-active");
				return;
			}
			
			$(this).each(function(){
				$(this).removeClass('core-active');
				if ($(this).is(chosen)){
					$(this).addClass('core-active');
				}
			});
		}
	};

	$.fn.selectDate=function($format){
		var val=$(this).val();
		if (!val || val=="0"){
			$(this).val("");
		}
		
		if ($(this).data("ts")){
			var ts=$(this).data("ts");
			if (ts && ts!="0"){
				$(this).val(AP.time.time(AP.i18n.dateFormat(),ts));	
			}
		}
		
		AP.UI.dateSelect(this, $format);
		return this;
	};

	$.fn.selectTime=function(options){
		AP.UI.timeSelect(this, options);
		return this;
	};

	/**
	 * @desc Trigger an action when click outside.
	 */
	$.fn.clickOut=function(callback, canvas){
		var $elem=$(this);
		if (canvas){
			$(canvas).on('click',function(event){
				if (!$(event.target).closest($elem).length){
					callback.apply($elem, event);
				}
			});

			return;
		}

		$(document.body).on('click.__temp',function(event){
			if (!$(event.target).closest($elem).length){
				callback.apply($elem, [event]);
			}
		});
	};

	$.fn.selectYear=function(){
		$(this).autocomplete({source: range(2010, 1900)});
	};
	
	$.fn.setActiveURLParam=function(param, df){
		var _df=df;
		
		if (AP.data.isObject(df)){
			if ("fallback" in df){
				_df=df.fallback;
			}
			
			if ("df" in df){
				_df=df.df;
			}
		}
		
		var found=0;
		$(this).each(function(){
			var curl=$(this).data('url');
			if (!curl || !curl.length){
				curl=$(this).data("xurl");
			}
			
			if (!curl || !curl.length){
				curl=$(this).data("updateurl");
			}
			
			if (!curl && $(this).data("urlparam")==param){
				curl=param+"="+$(this).data("value");
			}
			
			
			if (!curl){
				$(this).removeClass('core-active');
				return;
			}
			
			var cq=Query.get(param);
			if (typeof(cq) == 'undefined' || cq===null){
				if (AP.data.isObject(df)){
					cq= df.value;
				}
			}
			
			
			var reg=new RegExp(param+"="+cq+"$"); 
			var reg2=new RegExp(param+"="+cq+"[\&\?]");
			
			var df_reg1=null;
			var df_reg2=null;
			
			if (df && AP.data.isString(df)){
				df_reg1=new RegExp(param+"="+_df+"$"); 
				df_reg2=new RegExp(param+"="+_df+"[\&\?]");	
			}
			
			if (curl.match(reg) || curl.match(reg2)){
				found=1;
				$(this).addClass('core-active');
			}else if (df_reg1 && df_reg2 && curl.match(df_reg1) || curl.match(df_reg2)){
				found=1;
				$(this).addClass('core-active');
			}else{
				$(this).removeClass('core-active');
			}
		});
		
		if (!found){
			if (_df==""){
				$(this).each(function(){
					if ($(this).data("value")=="" || typeof $(this).data("value") == "undefined"){
						$(this).addClass("core-active");
					}
				});
			}else{
				$(this).setActive(_df);	
			}
			
			
		}

		
		return this;
	};
	
	
	
	$.fn.setActiveURLQuery=function(param, defaults){
		var maxscore=-1;
		var set=0;
		
		if (param && defaults){
			$(this).each(function(){
				var curl=$(this).data("url");
				if (!curl || !curl.length){
					curl=$(this).data("xurl");
				}
				if (!curl || !curl.length){
					curl=$(this).data("updateurl");
				}
				
				var qs=Query.get(param);
				if (!qs){
					qs=defaults;
				}
				
				qs=param+"="+qs;
				
				if (curl.indexOf(qs)!=-1){
					$(this).addClass('core-active');
				}else{
					$(this).removeClass('core-active');
				}
			});
			return;
		}
	};

	$.fn.shortlist=function(opts){
		if (AP.data.isInt(opts)){
			opts = {max: opts};
		}
		
		$.extend({max: 10}, opts);
		
		if ($(this).children().length <= opts.max){
			return;
		}
		
		var rem=$(this).children().length-opts.max;
		
		$(this).data("max", opts.max).after("<div class='core-js-show-more core-show-more core-is-more'><span>"+(__('Show more'))+" ("+(rem)+")</span></div>");
		$(this).children().each(function(index){
			if (index<opts.max){
			}else{
				$(this).addClass("core-hidden");
			}
		});
		
		$(this).next().click(function(){
			var $prev=$(this).prev();
			$prev.children().each(function(index){
				if (index<$prev.data("max")){
				}else{
					$(this).toggleClass("core-hidden");
				}
			});
			
			if ($(this).hasClass("core-is-more")){
				$(this).removeClass("core-is-more");
				$(this).find("span").html(""+(__('Show less'))+"");
			}else{
				var rem=$prev.children().length-$prev.data("max");
				$(this).addClass("core-is-more");
				$(this).find("span").html(""+__('Show more')+" ("+rem+")"); 
			}
		});
	};
})(jQuery);

function getScrollbarWidth(){
	var jTest = $('<div style="display:none;height:50px;overflow: scroll"><div style="height:100px;"></div></div>');
    $('body').append(jTest);
    var w = jTest.innerWidth();
    jTest.css({
        overflow: 'auto',
        height: '200px'
    });
    var w2 = jTest.innerWidth();
    var c= w-w2;

	return (c > 0) ? c : 15; // fix invisible scrollbar on MacOSX
};

function plugin_get_caret_position(id){	
	var el = $(id)[0];
	var pos = 0;
	if ('selectionStart' in el){
		el.focus();
		pos = el.selectionStart;
	} else if ('selection' in document) {
		el.focus();
		var Sel = document.selection.createRange();
		var SelLength = document.selection.createRange().text.length;
		Sel.moveStart('character', -el.value.length);
		pos = Sel.text.length - SelLength;
	}
	return pos;
};

function computeURLSimilarity(url){
	if (!url){
		return 0;
	}
	
	if (!AP.data.isString(url)){
		url=""+url;
	}
	
	var data={};
	var parts=url.split("?");
	if (parts.length==2){
		data=queryStringToArray(parts[1]);
	}
	var current= document.URL;
	var base=0;
	
	if (parts.length==1){
		if (parts[0]==current){
			return 2;
		}
		
		var cindex = current.indexOf(parts[0]);
		
		if (cindex!=-1){
			if (parts[0].length){
				return 1+(1.0*parts[0].length/(parts[0].length+1))*(1/(cindex+1));
			}
			return 1;
		}
	}else{
		if (url==current){
			return 3;
		}
	}
	
	var score=0;
	if (parts[0]==location.protocol + '//' + location.host + location.pathname){
		score=1;
	}

	var same=true;
	for (var key in data){
		if (key == "controller" || key == "token" || key == "controllerUri") {
			continue
		}

		if (data[key]!=Query.get(key)){
			same=false;
			break;
		}
	}
	
	if (!same){
		return 0;
	}
	
	for (var key in Query.all()){
		if (data[key] && data[key]===Query.get(key)){
			score++;
		}
	}

	if (current.includes(url)) {
		score++;
	}
	
	return score;
};








AP.sys={
    initAjax: function(){
		jQuery.ajaxSetup({async:false});
	},
			
	back: function(){
		return history.back();
	},	
	ie: function(){
		return $.browser.msie;
	},
	
	isTablet: function(){
		var ua = navigator.userAgent.toLowerCase();
		var isAndroid = ua.indexOf("android") > -1;
		var isiPad = ua.indexOf("ipad")>-1;
		return (isAndroid || isiPad);
	},

    isMobile:function(){
		if ('ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/)){
			return true;
		}

		return (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
	},

    isTouch: function(){
		return !!('ontouchstart' in window) ? 1 : 0;
	},

    /**
	 * @desc Create an event listener
	 */
	on :function(event, fx, $this){
		AP.sysEvent.bind(event, fx, $this);
		return this;
	},

    off: function(event){
		AP.sysEvent.off(event);
		return this;
	},
	
	
	/**
	 * @desc Create an event listener
	 */
	once :function(event, fx, $this){
		AP.sysEvent.bindOnce(event, fx, $this);
		return this;
	},

    /**
	 * @desc Trigger an event 
	 */
	fire: function(event, data){
		AP.sysEvent.trigger(event, data);
		return this;
	},
	
	
	/**
	 * @desc Trigger an event 
	 */
	trigger: function(event, data){
		return AP.sys.fire(event, data);
	},
	
	
	/**
	 * @desc Trigger an event (and dequeue)
	 */
	release: function(event){
		AP.sysEvent.release(event);
		return this;
	}
}

AP.sysEvent=new function __APSysEvent(){
    this.events={};
	this.__fired={};

    this.clear=function(){
		this.events={}
	};
	
	
	this.trigger=function(ev, data){
		if (this.events[ev] && this.events[ev].length){
			for (var i=0; i<this.events[ev].length; i++){
				var fn=this.events[ev][i];
				if (!fn){
					break;
				}

				
				if (fn._once){
					// Remove fn from event queues
					this.events[ev].splice(i, 1);
				}
				
				if (fn._caller){
					fn.apply(fn._caller, data);
				}else{
					if (AP.data.isArray(data)){
						fn.apply(undefined, data);
					}else{
						fn(data);	
					}
				}
			}
		}
		
		return this;
	};
	
	
	this.bind=function(ev, fx, _caller){
		if (!this.events[ev]){
			this.events[ev]=[];
		}
		
		if (_caller){
			fx._caller=_caller;
		}
		
		this.events[ev].push(fx);
		
		return this;
	};
	
	
	this.off=function(ev){
		if (!this.events[ev]){
			this.events[ev]=[];
		}
		
		this.events[ev]=[];
		return this;
	};
	
	this.bindOnce=function(ev, fx, _caller){
		if (!this.events[ev]){
			this.events[ev]=[];
		}
		
		if (_caller){
			fx._caller=_caller;
		}
		
		fx._once=1;
		
		this.events[ev].push(fx);
		
		return this;
	};
	
	this.release=function(ev){
		if (this.events[ev] && this.events[ev].length){
			while (true){
				var fn=this.events[ev].shift();
				if (!fn){
					break;
				}
				
				if (fn._caller){
					fn.apply(fn._caller);
				}else{
					fn();
				}
			}
		}
		
		this.__fired[ev]=1;
		return this;
	};
}


AP.pageConfig=new function __APPageConfig(){
	this.data={};
	this.__data={};
	
	this.init=function(data){
		this.__data=shallowClone(data);
		this.data=data;
	};
	
	this.reset=function(){
		this.data=shallowClone(this.__data);
		if (!this.data){
			this.data={};
		}
	};
	
	this.set=function(key, val){
		if (typeof val=="undefined"){
			val=1;
		}
		
		this.data[key]=val;
	};
	
	this.get=function(key){
		if (key in this.data){
			return this.data[key];
		}
		
		return null;
	};
};




AP.html={	
    data:{},

	contain:function(selector){
		if ($(selector).length>=1){
			return true;
		}
		return false;
	},
	
	exist:function(selector){
		return this.contain(selector);
	},

	save: function(key, selector){
		this.data[key]=$(selector).html();
	},
	
	update: function(key, selector){
		$(selector).html(this.data[key]);
	},
	
	title:function(str){
		document.title = str;
	},

	focus: function(selector){
		$(selector).focus();
		this.scrollTo(selector);
	},

	scrollTo: function(selector, base, data){
		if (!data){
			data={};
		}
		var xoffset=0;
		data=$.extend({},{offset:0, time: 400},data);
		if (!base){
			base=ap_getScrollElement(document.body, 'html','body');
		}
		
		
		var targetOffset=$(selector).position().top+xoffset+data.offset;
		if (targetOffset<=0){
			targetOffset=0;
		}
		
		$(base).animate({scrollTop: targetOffset}, data.time, function() {});
	},

	bind:function(selector,_key, action){
		$(selector).keydown(function (e){			
			key=0;
			if (e && e.which) key=e.which;
			else if (e && e.keyCode) key=e.keyCode;
			if (key == _key){
				action();
			}
		});
	},

	resize: function(action, persistent){		
		action();
		
		if (persistent){
			$(window).resize(function(){
				action();
			});
		}else{
			$(window).bind('resize.__temp',function(){
				action();
			});
		}
	},

	resizeEnd: function(action, timer, persistent){
		var doit;
		action();
		
		if (persistent){
			window.onresize = function(){
				clearTimeout(doit);
				doit = setTimeout(action, timer);
			};
		}else{
			window.on("resize.__temp", function(){
				clearTimeout(doit);
				doit = setTimeout(action, timer);
			});
		}
	},
}


AP.pageData={};
AP.localData={};
// Client.tempData={};

AP.lc=new function __APLC(){
	
	this._check=false;
	this._enable=false;
	this.enable=function(){
		if (Client.native){
			return true;
		}
		
		if (!this._check){
			this.check=true;
			if (typeof localStorage !== "undefined" && AP.isset('localStorage')){
				localStorage.setItem('__apc', '__apc');
				if (localStorage.getItem('__apc') == '__apc'){
					this._enable=true;
					return true;
				}else{
					return false;
				}
			}
			
			return false;
		}
		
		return this._enable;
	};
	
	
	this.set=function(key, data){
		if (!this.enable()){
			return false;
		}
		
		localStorage.setItem(key, data);
	};
	
	
	this.get=function(key){
		if (!this.enable()){
			return null;
		}
		
		return localStorage.getItem(key);
	};
	
	
	this.clear=function(key){
		if (!this.enable()){
			return false;
		}
		
		return localStorage.removeItem(key);
	};
};


AP.setTempData=function(code){
	if (!Client.tempData) {
		Client.tempData={};
	}
	for (var key in code){
		if (["code", "message", "data", "good", "notEmpty", "hasCode", "_html", "hasMessage", "_init", "_inpage_js", "_page_data", "_update"].includes(key)) {
			continue;
		}
		
		Client.tempData[key]=code[key];
	}
};



AP.toastr = new function __APToastr() {
    this.error = function(message) {
        toastr.error(Render.helper.escape(message));
        this.resetSetting();
    }

    this.success = function(message) {
        toastr.success(Render.helper.escape(message));
        this.resetSetting();
    }

    this.info = function(message) {
        toastr.info(Render.helper.escape(message));
        this.resetSetting();
    }

    this.warning = function(message) {
        toastr.warning(Render.helper.escape(message));
        this.resetSetting();
    }

    this.setCloseButton = function() {
        toastr.options.closeButton = true;
        toastr.options.timeOut = 100000;
        return this;
    }

    this.resetSetting = function () {
        toastr.options = {
            "closeButton": false,
            "debug": false,
            "newestOnTop": false,
            "progressBar": false,
            "positionClass": "toast-top-right",
            "preventDuplicates": false,
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }
    }
}



AP.UI= new function _UI(){
    this.dateSelect = function(selector, format){
		if (!format){
			format=AP.locale.get("date-format-jquery","DD, MM d, yy");
		}
		
		$(selector).each(function(){
			$(this).datepicker({"dateFormat": format, firstDay: 1});
		});
	};

	/**
	 * @desc Create a time selector
	 */
	this.timeSelect = function(selector, options){
		if (!options){
			options={};
		}


		$(selector).each(function(){
			$(this).data("ts", options).addClass("__timeselect");
			if (!$(this).data('__timeselect')){
				$(this).data('__timeselect',1);
				var p=$(this).position();

				var val=$(this).val();
				var hh=0;
				var mm=0;
				if (val && val.length){
					var hm=getCurrentHM(this);
					hh=hm[0];
					mm=hm[1];
				}else{
					var now=options.value;
					if (!now){
						now=$(this).data("value");
					}

					if (!now){
						now=AP.time.now();
					}

					if (now){
						$(this).val(AP.time.time("%H:%i", now));
					}

					hh=AP.time.time("%H", now);
					mm=AP.time.time("%i", now);
				}


				var hhtml="<div class='-tsbox -first' data-name='hour'> <div class='-tsn -up'>"+(SVG.chevron_up)+"</div> <div class='-tsn -down'>"+(SVG.chevron_down)+"</div> <div class='-tslabel'><div class='-tsinput -hour'>"+(hh)+"</div></div> </div>";

				var msrc=range(0,59,5);

				var mhtml="<div class='-tsbox -second' data-name='min'> <div class='-tsn -up'>"+(SVG.chevron_up)+"</div> <div class='-tsn -down'>"+(SVG.chevron_down)+"</div> <div class='-tslabel'><div class='-tsinput -min'>'+mm+'</div></div> </div>";
				var html="<div class='-tstitle'>Select time <span class='-tsclose'><span class='-ap icon-close'></span></span></div>"+hhtml + mhtml + "<div class='-tsr'>:</div> <div class='clear'></div>";


				var pos="top: "+p.top+"px; left: "+p.left+"px'";
				if (options && options.align=='bottom'){
					pos="bottom:38px; left: "+p.left+"px'";
				}

				$(this).parent().addClass('__timeselectw').append("<div class='__hiddenselect' style='position:absolute; "+pos+">"+html+"</div>");


				var $canvas=$(this).parent().find('.__hiddenselect');
				$canvas.find("input").on("input focus", function(){
					$canvas.find(".-tsbox").removeClass("active");
					$(this).closest(".-tsbox").addClass("active");
				});

				$(this).parent().clickOut(function(){
					$(this).find('.__hiddenselect').hide();
				});

				$canvas.find(".-tsclose").click(function(){
					$(this).closest('.__hiddenselect').hide();
				});

				$canvas.find(".-tsbox").each(function(){
					$(this).on("mousewheel", function(e){
						e.stopPropagation();
						if (e.originalEvent.wheelDelta / 120 > 0){
							moveTSUp(this);
						}else{
							moveTSDown(this);
						}
					});

					$(this).find(".-tsn.-up").click(function(){
						moveTSUp(this);
					});

					$(this).find(".-tsn.-down").click(function(){
						moveTSDown(this);
					});
				});
			}

			// AP.UI.timeSelectFocus(this);

			$(this).on("input focus", function(){
				var options=$(this).data("ts");
				if (!options){
					options={};
				}

				if (options.align && options.align=='bottom'){
					$(this).parent().find('.__hiddenselect').css('bottom', 38).show();
				}else{
					var p=$(this).position();
					$(this).parent().find('.__hiddenselect').css('top', p.top).css('left', p.left).show();
				}

				$(this).parent().find('.__hiddenselect .-first .-tslabel input').focus();

				// AP.UI.timeSelectFocus(this);

				var hm=getCurrentHM(this);
				var $box=$canvas=$(this).parent().find('.__hiddenselect');
				$box.find(".-tsinput.-hour").html(hm[0]);
				$box.find(".-tsinput.-min").html(hm[1]);

			}).blur(function(){
				$(this).find('.__hiddenselect').hide();

				var hm=getCurrentHM(this);
				$(this).val(hm[0] + ":" + hm[1]);
			});


		});



		function moveTSUp(ref){
			var type=$(ref).closest(".-tsbox").data("name");
			if (type=="hour"){
				var hour=getCurrentTS(ref, 'hour');
				hour++;
				if (hour>=24){
					hour=23;
				}

				setCurrentTS(ref, 'hour', hour);
			}else{
				var min=getCurrentTS(ref, 'min');
				min=min+5;
				if (min>=60){
					min=min-5;
				}

				setCurrentTS(ref, 'min', min);
			}
		};

		function moveTSDown(ref){
			var type=$(ref).closest(".-tsbox").data("name");
			if (type=="hour"){
				var hour=getCurrentTS(ref, 'hour');
				hour--;
				if (hour<0){
					hour=0;
				}

				setCurrentTS(ref, 'hour', hour);
			}else{
				var min=getCurrentTS(ref, 'min');
				min=min-5;
				if (min<0){
					min=min=5;
				}

				setCurrentTS(ref, 'min', min);
			}
		};


		function getCurrentTS(ref, type){
			var $input=$(ref).closest(".__hiddenselect").prev("input");
			if (!$input.length){
				return 0;
			}

			var val=$input.val();
			if (!val){
				val="00:00";
			}


			var hm=val.split(":");
			if (hm.length!=2){
				return 0;
			}

			if (type=='hour'){
				return parseInt(hm[0]);
			}else{
				return parseInt(hm[1]);
			}
		};


		function setCurrentTS(ref, type, val){
			var $box=$(ref).closest(".__hiddenselect");
			$box.find(".-tsinput.-"+type).html(AP.data.zeroPrefix(val));


			var hh=0;
			var mm=0;

			var $input=$(ref).closest(".__hiddenselect").prev("input");
			var ip="00:00";
			if (!$input.length){
			}else{
				ip=$input.val();
				if (!ip){
					ip="00:00";
				}
			}

			var hm=ip.split(":");
			if (hm.length!=2){
			}else{
				hh=hm[0];
				mm=hm[1];

				if (type=='hour'){
					hh=val;
				}else{
					mm=val;
				}
			}

			hh=parseInt(hh);
			mm=parseInt(mm);

			$input.val(safeNum(hh) + ":" + safeNum(mm));
		};


		function getCurrentHM(ref){
			var hh=0;
			var mm=0;

			var ip=$(ref).val();

			if (!ip || !ip.length){
				ip="00:00";
			}

			var hm=ip.split(":");
			if (hm.length!=2){

			}else{
				hh=parseInt(hm[0]);
				mm=parseInt(hm[1]);
			}

			return [safeNum(hh), safeNum(mm)];
		};

		function  safeNum(num){
			if (AP.data.isInt(num)){
				if (parseInt(num) === 0) {
					return "00";
				}
				return AP.data.zeroPrefix(num);
			}

			return "00";
		};
	};
}



function urlClick(ref) {
    if ((AP.time.diff(Client.use_module_since, AP.time.now()).day > 30
        || typeof Client.shop !== 'undefined') && !se(Client.is_demo, 1)) {
        return;
    }
    var $this=$(ref);

    var url=null;

	if ($this.data("urlparam")){
		var p=$this.data("urlparam");
		var v=$this.data("value");

		var px={};

		if (v && v!=""){
			px[p]=v;
		}else{
			px[p]=null;
		}

		AP.setURLParams(px, true);
	}

	if ($this.data('xurl')){
		var url=$this.data('xurl');
		if (Client.pageData.context){
			url=Client.pageData.context.path+"/"+url;
		}
	}else{
		var url=$this.data('url');
		if (url==':self'){
			return __selfcall(ref);
		}
	}

	if (url==":file"){
		var ext_url=$(ref).data("file");
		Core.file.preview(ext_url);
		return;
	}

	if (url==":active"){
		$this.toggleClass("core-active");
		return;
	}

	if (url == ":user/support") {
        $(".core-support-popup").toggle();
		return;
	}

	if (url == ":user/apps") {
        $("#core-apps").toggle();
		return;
	}

	if (url == ":user/videos") {
		$("#core-video").toggle();
		return;
	}

    if (url==":refresh"){
		AP.refresh();
		return;
	}

	if (url==":xrefresh" || url==':current'){
		AP.xRefresh();
		return;
	}

	if (url==":collapse"){
		$this.toggleClass("-collapsed");
		return;
	}

	if (url==":zoom"){
		UI.previewImage($(ref).data("image"));
		return;
	}

	if (url==":active:parent" || url==":parent-active" || url==':parent:active'){
		$this.parent().toggleClass("core-active");
		return;
	}

	if (url && url.match(/^:collapse\/([0-9]+)/)){
		var ckey = $(ref).data("ckey") || $(ref).data("cache-key") || $(ref).data("cache");

		var parts = url.split("/");
		var depth = parseInt(parts[1]);
		var $p=$this;

		for (var i=0; i<depth; i++){
			$p=$p.parent();
		}

		$p.toggleClass("-collapsed");
		if (ckey){
			if ($p.hasClass("-collapsed")){
				Core.pref().set(ckey, 1);
			}else{
				Core.pref().set(ckey, 0);
			}
		}
		return;
	}

    if (url==":back"){
		AP.back();
		return;
	}

    if (!url){
		return;
	}
	coreTrueClick($this, ref, url);
}

function coreTrueClick($this, ref, url){
	if ($this.data("blank")=="1"){
		return window.open(url);
	}
	AP.toURL(url, null, ref);
}

function parseNum(val) {
    if (val === "" || val == null){
        return false;
    }

    val = val.replace(/,/g, '');
    val = parseFloat(val);
    return val;
}

function coreBase64Encode(str) {
    if ("function" == typeof btoa) {
        return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
            function toSolidBytes(match, p1) {
                return String.fromCharCode('0x' + p1);
            }));
    }
    if ("undefined" != typeof Buffer) return Buffer.from(str, "utf8").toString("base64");
    throw new Error("Can not find window.btoa or Buffer");
}



AP.blankDialog=function(id){
	return AP.customDialog("<div id='"+id+"'></div>", {id: id+"-dx"}).addClass("-full-canvas -full-blank").closable(false).show();
};

AP.fsDialog=function(id){
	var opts=$.extend({}, {id: id+"-fs-dialog", padding: true, close_button: false}, opts);

	var dialog= AP.dialog(opts.id)
	.engine(FullscreenDialogEngine)
	.style("core-semantic-transition core-semantic-fade core-semantic-in")
	.closeButton(false)
	.closable(true)
	.content("<div id='"+(id)+"'></div>");

	dialog.addClass("-full-canvas -full-blank").closable(false).show();
	return dialog;
};

AP.fileExt = function(fname) {
	var regEx = /(?:\.([^.]+))?$/;
	return regEx.exec(fname)[1];
};

AP.emptyDialog=function(html, opts){
	var opts=$.extend({}, {id: "custom-dialog", padding: true, close_button: false}, opts);

	var dialog= AP.dialog(opts.id)
	.engine(EmptyDialogEngine)
	.closeButton(false)
	.closable(true)
	.content(html);

	dialog.addClass("-full-canvas -full-blank").closable(false).show();
	return dialog;
};

AP.balanceDialog=function(id){
	AP.dialog(id).balance();
};

AP.customDialog=function(text, options){
	if (AP.data.isObject(text) && !options){
		return AP.customDialogV2(text);
	}

	var id="";
	if (!options){
		options={};
		id="custom-dialog";
	}else if (AP.data.isString(options)){
		id=options;
		options={};
	}

	if (id[0]=="#"){
		id=id.substr(1);
	}

	var opts=$.extend({}, {id: id, padding: true, close_button: false, closable: true}, options);

	var dialog= AP.dialog(opts.id)
	.engine(CustomDialogEngine)
	.closeButton(opts.close_button)
	.closable(opts.closable)
	.content(text);

	if (options.fs){
		dialog.data("full", 1);
	}

	return dialog;
};

AP.customDialogV2=function(opts){
	opts=$.extend({
		id: "custom-dialog",
		width: 800,
		height: "auto",
		html: "",
		closable: false,
		close_button:true,
		title: "Custom dialog",
		padding: false
	}, opts);

	var dialog= AP.dialog(opts.id)
	.engine(CustomDialogEngine)
	.closeButton(opts.close_button)
	.closable(opts.closable)
	.width(opts.width)
	.title(opts.title)
	.content(opts.html);

	 if (!dialog.padding){
	 	dialog.addClass("-full");
	 }

	dialog.show();
	return dialog;
};

AP.bindSearch=function(input){
	var qname=$(input).data("query");
	if (!qname){
		qname="q";
	}


	$(input).enter(function(){
		var val=$(this).val();
		var qname=$(this).data("query");
		if (!qname){
			qname="q";
		}

		var params = {page: null};


		if (val=="" || !val.length){
			params[qname] = null;
		}else{
			params[qname] = val;
		}


		AP.setURLParams(params, true);
	}).val(Query.get(qname));

	return $(input);
};

AP.hideCustomDialog=function(id, destroy_instance){
	if (!id){
		id="#custom-dialog";
	}

	if ($(id).closest(".__dialog").data("refresh")){
		return AP.xRefresh();
	}

	AP.dialog(id).hide();
	if (destroy_instance){
		$(id).closest(".__dialog").remove();
	}
};

AP.uploadable=function(canvas, data, callback, $this){
    if (!data){
        data={};
    }

    data=$.extend({}, {name: 'file', format: 0, preview: 0, 'data': {}, multi: false}, data);
    if ($(canvas).hasClass('uploadable')){
        return;
    }

    $(canvas).addClass('uploadable');
    var id=AP.uuid();
    var fid=AP.uuid();
    var upload_icon="";

    if ($(canvas).data('format')){
        upload_icon="<span class='upload-icon icm icon-upload2'></span>"
    }

    var name=$(canvas).data("name");
    if (!name){
        name=data.name;
    }

    if (!name){
        name="file";
    }

    var show_preview=0;

    var action=$(canvas).data('action');
    if (!action){
        action=data.action;
    }

    var image_required=0;
    if ($(canvas).data('image')==1 || $(canvas).data('image')=='1' || data.image == 1){
        image_required=1;
    }

    if ($(canvas).data('preview')==1 || $(canvas).data('preview')=='1' || data.preview==1){
        show_preview=1;
    }

    var placeholder="";
    if (data.placeholder){
        placeholder="<div class='upload-placeholder'>"+data.placeholder+"</div>";
    }



    if (!action || !action.length){
        var preview_image="<div class='upload-preview'></div>";
        if (data.preview_image && data.preview_image.length){
            preview_image="<div class='upload-preview'><img src='"+data.preview_image+"'/></div>";
        }

        $("<div class='core-upload-form'>" +
            placeholder +
            upload_icon +
            preview_image+
            "<input type='file' name='"+name+"' id='"+fid+"'/>" +
            "</div><div class='upload-fn'></div>").appendTo(canvas);


        $("#"+fid).change(function(){
            if ('FileReader' in window && this.files.length && image_required){

                if (!this.files[0].type.match('image.*')) {
                    return AP.alertError("Please select an image");
                }
            }

            var fname=getUploadFN($(this).val());
            $(canvas).addClass("-selected").find(".upload-fn").html("<span class='ap-xdot'>"+fname+"</span>");

            if (show_preview){
                if ('FileReader' in window && this.files.length){
                    if (!this.files[0].type.match('image.*')) {
                        return;
                    }

                    var reader=new FileReader;
                    reader.onload=function(e){
                        $(canvas).find(".upload-preview").html("<img src=''/>");
                        $(canvas).find(".upload-preview img")[0].src=e.target.result;
                    };
                    reader.readAsDataURL(this.files[0]);
                }
            }

        });
        return;
    }


    var multi="";
    if (data.multi){
        multi=" multiple";
        $("<div class='core-upload-form'><form method='post' id='"+id+"' action='"+action+"'>" +
            "<input type='hidden' name='__multi' value='1'/>" +
            upload_icon+
            placeholder+
            "<input type='file' name='"+name+"[]' id='"+fid+"'"+multi+"/>" +
            "</form></div>").appendTo(canvas);
    }else{
        $("<div class='core-upload-form'><form method='post' id='"+id+"' action='"+action+"'>" +
            upload_icon+
            placeholder+
            "<input type='file' name='"+name+"' id='"+fid+"'/>" +
            "</form></div>").appendTo(canvas);
    }


    $("#"+fid).change(function(){
        var cid=$(this).closest('form').attr('id');

        AP.ajaxShow();
        AP.submit("#"+cid, function(code){
            AP.ajaxHide();

            $("#"+fid).val('');

            if (!code.good()){
                return AP.alertError(code.message);
            }

            if ($this){
                callback.apply($this, [code]);
            }else{
                callback(code);
            }

        }, data.data);
    });
};



AP.locale.set("date-format-jquery", "dd/mm/yy");
AP.locale.set("date-format", "DD/MM/YYYY");


var Core = new function __Core() {
    this.__active=1;

    this.initURLClick=function(){
		$(document.body).on("click", ".core-url", function(e){
			e.stopPropagation();
			urlClick(this);
		});

		$(document.body).on("mousedown", ".core-url", function(e){
			e.stopPropagation();
			if (event.which === 2 && AP.word.prefix($(this).data('url'), 'http')) {
				window.open($(this).data('url'));
			}
		});
	};

    /**
	 * @desc Check if the current tab is active
	 */
	this.tabActive=function(){
		return (Core.__active==1);
	};

	this.setObjectURL = function(key, id) {
		if (key===null){
			AP.setURLParams({show: null, id: null});
			return;
		}

		AP.setURLParams({show: key, id: id});
	}

	this.initLayout = function(){
		this.applist.init();
		this.videolist.init();
		if ($(".core-master-header").length == 0) {
			$("#page").css("top", 0);
		}
	};

	this.close=function(){
		var spaces=["#core-apps", "#core-video"];
		for (var i=0; i<spaces.length; i++){
			$(spaces[i]).hide();
		}
	};
}

Core.load = function(opts){
	if (!opts.url && opts.action){
		opts.url = opts.action;
	}

	function prepareFSLayout(id){
		if ($("#core-master-fs").length){
			AP.destroyDialog("#core-master-fs-fs-dialog");
		}

		// Init custom dialog
		AP.fsDialog("core-master-fs");
		$("#core-master-fs .fs-closable").click(function(){
			Core.load.closeFS();
		});

		if (!$("#"+id).length){
			var html="<div class='bfs-dx-layout js-bfs' id='"+(id)+"'></div>";
			$(html).appendTo("#core-master-fs");
		}

		$("#core-master-fs").show().addClass("__ontop");
	};

	function coreLoadFinalRender(opts){
		Layout.scrollable("#"+(opts.id)+" .scrollable");

		if (opts.fs){
			return;
		}

		// Automatic tabbing
		$("#"+opts.id+" .sections").each(function(){
			var tabs=[];
			$(this).find(".section").each(function(){
				var ref=AP.uuid();
				var tab=$(this).data("tab");
				if (!tab){
					tab = $(this).find(".header").text();
				}
				$(this).addClass("js-"+ref);
				tabs.push({ref: ref, tab: tab});
			});

			$(this).wrapInner("<div class='sections-body'></div>");
			var tabs_html = AP.render(tabs, function(t){
				return "<div class='tab' data-ref='"+(t.ref)+"'>"+(t.tab)+"</div>";
			});

			$(this).prepend("<div class='tabs'>"+(tabs_html)+"</div>");
			$(this).find(".tabs .tab").on("click", function(){
				$(this).siblings().removeClass("active");
				$(this).addClass("active");
				$(this).closest(".sections").find(".sections-body .section").setActive(".js-"+$(this).data("ref"));
			});

			$(this).find('.tabs .tab:first').click();
		});

	};

	opts = $.extend({id: "core-dialog", closable: false, height: 400, width: 800, data: {}}, opts);
	var header='';
	if (opts.header){
		header = "<div class='bl-header'> <div class='bl-title inline'>"+(opts.header)+"</div> <div class='bl-close' onclick='AP.dialog.close(this);'><span><i class='icon-remove'></i></span></div> </div>";
	}

	var html="<div class='core-load-wrapper' style='min-height:"+(opts.height)+"px'>"+(header)+"<div id='"+(opts.id)+"' class='core-display'></div></div>";

	if (opts.fs || opts.width=="fullscreen"){
		// Prepare for fullscreen layout
		prepareFSLayout(opts.id);
	}else{
		AP.customDialog(html, opts.id+"-dialog").width(opts.width).style("-full -dx-obj-v2 core-semantic-transition core-semantic-fade core-semantic-in").closable(opts.closable).show();
	}

	if (!opts.url){
		$("#"+opts.id).html(opts.html);
		if (opts.render){
			opts.render();
		}
		coreLoadFinalRender(opts);
		Render.finish();
		AP.dialog(opts.id+"-dialog").balance();
		return;
	}

	AP.loadInlineURL(opts.url, opts.data, "#"+opts.id, {
		start: function(){
		}, end: function(){
			AP.dialog(opts.id+"-dialog").balance();
			coreLoadFinalRender(opts);

			if (opts.render){
				return opts.render(opts);
			}
		}, error: function(code){
			AP.dialog.close("#"+opts.id);
			Core.load.close();

			if (opts.render){
				return opts.render(opts);
			}
		}
	});
};

Core.load.close=function(){
	if (Query.get("show")){
		AP.setURLParams({show: null, id: null});
	}
};
Core.load.closeFS = function(){
	AP.destroyDialog("#core-master-fs-fs-dialog");
	Core.load.close();
};


var SVG=new function __SVG(){
    this._edge_icons = {};
	this._groups = {};

	this.extends=function(obj){
		for (var key in obj){
			this[key]=obj[key];
		}
	};

	this.group = function(group_name, objs){
		this.extends(objs);

		for (var key in objs){
			if (!this._groups[group_name]){
				this._groups[group_name] = [];
			}

			this._groups[group_name].push(key);
		}
	};

	this.getGroups = function(){
		var __used = {};
		var r = [
			{name: "Default", items: []}
		];

		for (var key in this._groups){
			for (var i=0; i< this._groups[key].length; i++){
				__used[this._groups[key][i]] = 1;
			}

			r.push({
				name: key,
				items: this._groups[key]
			});
		}


		for (var key in this){
			if (this[key] && AP.data.isString(this[key])){
				if (!__used[key]){
					r[0].items.push(key);
				}
			}
		}

		if (this._edge_icons){
			r.push({
				name: "Edges",
				items: Object.keys(this._edge_icons),
				edge: 1
			});
		}


		return r;
	};

	this.add=function(obj){
		for (var key in obj){
			this[key]=obj[key];
		}
	};

	this.fa=function(icon){
		return "<span class='ficon-"+(icon)+" ap-f14'></span>";
	};

	this.ap=function(icon){
		return "<span class='-ap icon-"+(icon)+" ap-f16'></span>";
	};
};

SVG.extends({
	help_with_circle:'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM5.496 6.033h.825c.138 0 .248-.113.266-.25.09-.656.54-1.134 1.342-1.134.686 0 1.314.343 1.314 1.168 0 .635-.374.927-.965 1.371-.673.489-1.206 1.06-1.168 1.987l.003.217a.25.25 0 0 0 .25.246h.811a.25.25 0 0 0 .25-.25v-.105c0-.718.273-.927 1.01-1.486.609-.463 1.244-.977 1.244-2.056 0-1.511-1.276-2.241-2.673-2.241-1.267 0-2.655.59-2.75 2.286a.237.237 0 0 0 .241.247zm2.325 6.443c.61 0 1.029-.394 1.029-.927 0-.552-.42-.94-1.029-.94-.584 0-1.009.388-1.009.94 0 .533.425.927 1.01.927z"/></svg>',
	check: '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M12.736 3.97a.733.733 0 0 1 1.047 0c.286.289.29.756.01 1.05L7.88 12.01a.733.733 0 0 1-1.065.02L3.217 8.384a.757.757 0 0 1 0-1.06.733.733 0 0 1 1.047 0l3.052 3.093 5.4-6.425a.247.247 0 0 1 .02-.022Z"/></svg>',
	ui_filter: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><path d='M6 12h4v-2H6v2zM2 4v2h12V4H2zm2 5h8V7H4v2z'></path></svg>",
	form_edit: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24px' height='24px'><path d='M 18 2 L 15.585938 4.4140625 L 19.585938 8.4140625 L 22 6 L 18 2 z M 14.076172 5.9238281 L 3 17 L 3 21 L 7 21 L 18.076172 9.9238281 L 14.076172 5.9238281 z'/></svg>",
	caret_down_fill: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/></svg>",
    lock: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M8 1a2 2 0 0 1 2 2v4H6V3a2 2 0 0 1 2-2zm3 6V3a3 3 0 0 0-6 0v4a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2z'/></svg>",
	filter: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M1.5 1.5A.5.5 0 0 1 2 1h12a.5.5 0 0 1 .5.5v2a.5.5 0 0 1-.128.334L10 8.692V13.5a.5.5 0 0 1-.342.474l-3 1A.5.5 0 0 1 6 14.5V8.692L1.628 3.834A.5.5 0 0 1 1.5 3.5v-2z'/></svg>",
	close: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path fill-rule='evenodd' d='M13.854 2.146a.5.5 0 0 1 0 .708l-11 11a.5.5 0 0 1-.708-.708l11-11a.5.5 0 0 1 .708 0Z'/><path fill-rule='evenodd' d='M2.146 2.146a.5.5 0 0 0 0 .708l11 11a.5.5 0 0 0 .708-.708l-11-11a.5.5 0 0 0-.708 0Z'/></svg>",
	form_color: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24px' height='24px'><path d='M 7.8886719 2.0898438 A 1.0001 1.0001 0 0 0 7.1933594 3.8066406 L 9.5761719 6.1894531 L 3.7988281 11.787109 L 3.7929688 11.792969 C 2.6394154 12.946522 2.6394154 14.854259 3.7929688 16.007812 L 8.8925781 21.107422 C 10.046132 22.260975 11.903752 22.311091 13.007812 21.207031 L 18.107422 16.107422 C 19.260975 14.953868 19.260975 13.046132 18.107422 11.892578 L 16.164062 9.9511719 A 1.0001 1.0001 0 0 0 16.107422 9.8925781 L 8.6074219 2.3925781 A 1.0001 1.0001 0 0 0 7.8886719 2.0898438 z M 10.988281 7.6035156 L 14.693359 11.306641 L 16.693359 13.306641 C 16.916583 13.529864 17.027344 13.764932 17.027344 14 L 4.8964844 14 C 4.8603635 13.731888 4.9521709 13.461892 5.2070312 13.207031 L 10.988281 7.6035156 z M 20 16.400391 C 19.8415 16.400391 19.682938 16.476906 19.585938 16.628906 C 18.999938 17.544906 18 19.222 18 20 C 18 21.1 18.9 22 20 22 C 21.1 22 22 21.1 22 20 C 22 19.222 21.000063 17.544906 20.414062 16.628906 C 20.317062 16.476906 20.1585 16.400391 20 16.400391 z'/></svg>",
	chevron_left: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path fill-rule='evenodd' d='M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z'/></svg>",
	chevron_right: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path fill-rule='evenodd' d='M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z'/></svg>",
	chevron_up: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-chevron-up' viewBox='0 0 16 16'>   <path fill-rule='evenodd' d='M7.646 4.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1-.708.708L8 5.707l-5.646 5.647a.5.5 0 0 1-.708-.708l6-6z'/> </svg>",
	chevron_down:"<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-chevron-down' viewBox='0 0 16 16'>   <path fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/> </svg>",
	support: "<svg width='24' height='24' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'><path fill-rule='evenodd' clip-rule='evenodd' d='M17.5137 5.35069C14.0784 2.10219 8.63278 2.23733 5.36479 5.6522C2.0968 9.06706 2.23276 14.4802 5.66811 17.7287L6.03435 18.075L3.94395 20.2593C9.13434 21.9218 14.6814 20.7037 17.817 17.4271C21.085 14.0123 20.9491 8.59919 17.5137 5.35069ZM12.0905 17.2272H10.4541V15.5908H12.0905V17.2272ZM10.4545 14.3636H12.0909C12.0909 13.4674 12.6727 12.959 13.2697 12.4373C13.8991 11.8873 14.5455 11.3224 14.5455 10.2727C14.5455 8.46455 13.0809 7 11.2727 7C9.46455 7 8 8.46455 8 10.2727H9.63636C9.63636 9.37273 10.3727 8.63636 11.2727 8.63636C12.1727 8.63636 12.9091 9.37273 12.9091 10.2727C12.9091 10.9921 12.4347 11.3557 11.9031 11.7632C11.2254 12.2827 10.4545 12.8735 10.4545 14.3636Z'></path></svg>",
	document: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><path d='M9 1H4a2 2 0 00-2 2v10a2 2 0 002 2h5v-1H4a1 1 0 01-1-1V3a1 1 0 011-1h5v2.5A1.5 1.5 0 0010.5 6H13v2h1V6L9 1z'></path><path fill-rule='evenodd' d='M15.854 10.146a.5.5 0 010 .708l-3 3a.5.5 0 01-.708 0l-1.5-1.5a.5.5 0 01.708-.708l1.146 1.147 2.646-2.647a.5.5 0 01.708 0z'></path></svg>",
	excel: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 481.882 481.882' style='enable-background:new 0 0 481.882 481.882;' xml:space='preserve'><path style='fill:#26A69A;' d='M60.235,28.913C60.235,12.943,73.178,0,89.148,0h212.028l120.471,101.195v351.774 c0,15.97-12.943,28.913-28.913,28.913H89.148c-15.97,0-28.913-12.943-28.913-28.913V28.913z'/><path style='fill:#00897B;' d='M301.176,0v72.282c0,15.97,12.943,28.913,28.913,28.913h91.558'/><g><path style='fill:#FFFFFF;' d='M107.821,235.799h27.264l14.908,32.542h0.602l15.812-32.542h26.511l-28.017,47.91l30.577,56.471 h-27.264l-17.92-38.709h-0.602l-17.476,38.709h-26.654l29.523-55.424L107.821,235.799z'/><path style='fill:#FFFFFF;' d='M209.626,340.179v-104.38h25.005v84.661h45.184l-2.568,19.72H209.626z'/><path style='fill:#FFFFFF;' d='M329.502,342.739c-18.982,0-33.129-6.618-41.72-15.059l12.649-13.997 c7.688,6.776,17.032,10.541,28.175,10.541c10.232,0,17.16-4.676,17.16-12.664c0-7.529-4.367-10.835-18.824-15.368 c-23.951-7.529-33.129-17.016-33.129-32.685c0-19.283,17.762-30.426,39.454-30.426c15.827,0,28.16,4.969,37.203,13.553 l-11.753,13.56c-7.078-5.865-15.368-8.734-23.499-8.734c-9.336,0-15.526,3.471-15.526,10.089c0,6.626,4.676,9.186,20.638,14.298 c19.885,6.475,31.48,14.607,31.48,33.739C371.825,329.178,355.87,342.739,329.502,342.739z'/></g></svg>",
	pdf: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 481.882 481.882' style='enable-background:new 0 0 481.882 481.882;' xml:space='preserve'><path style='fill:#EF5350;' d='M60.235,28.913C60.235,12.943,73.178,0,89.148,0h212.028l120.471,101.195v351.774 c0,15.97-12.943,28.913-28.913,28.913H89.148c-15.97,0-28.913-12.943-28.913-28.913V28.913z'/><path style='fill:#D32F2F;' d='M301.176,0v72.282c0,15.97,12.943,28.913,28.913,28.913h91.558'/><g><path style='fill:#FFFFFF;' d='M150.904,305.536H139.61v34.643h-25.005v-104.38h32.986c28.469,0,44.732,11.144,44.732,34.04 C192.316,294.4,175.601,305.536,150.904,305.536z M147.893,253.568h-8.282v33.89h9.186c11.294,0,17.769-5.429,17.769-17.626 C166.566,258.846,160.392,253.568,147.893,253.568z'/><path style='fill:#FFFFFF;' d='M231.77,340.179h-28.318v-104.38h26.511c26.82,0,52.412,8.584,52.412,51.674 C282.376,329.924,257.822,340.179,231.77,340.179z M233.57,253.869h-5.12v68.239h5.12c13.704,0,22.889-7.379,22.889-34.65 C256.474,259.607,246.679,253.869,233.57,253.869z'/><path style='fill:#FFFFFF;' d='M325.888,253.568v27.422h36.45v17.92h-36.45v41.269h-25.156v-104.38h68.834l-2.56,17.769 L325.888,253.568L325.888,253.568z'/></g></svg>",
	word: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 481.882 481.882' style='enable-background:new 0 0 481.882 481.882;' xml:space='preserve'><path style='fill:#42A5F5;' d='M60.235,28.913C60.235,12.943,73.178,0,89.148,0h212.028l120.471,101.195v351.774 c0,15.97-12.943,28.913-28.913,28.913H89.148c-15.97,0-28.913-12.943-28.913-28.913V28.913z'/><path style='fill:#1E88E5;' d='M301.176,0v72.282c0,15.97,12.943,28.913,28.913,28.913h91.558'/><g><path style='fill:#FFFFFF;' d='M141.41,340.179h-28.318v-104.38h26.511c26.812,0,52.42,8.584,52.42,51.674 C192.023,329.924,167.469,340.179,141.41,340.179z M143.217,253.869h-5.12v68.239h5.12c13.704,0,22.889-7.379,22.889-34.65 C166.114,259.607,156.326,253.869,143.217,253.869z'/><path style='fill:#FFFFFF;' d='M240.956,342.739c-27.415,0-41.879-20.924-41.879-54.814c0-33.137,14.464-54.829,41.879-54.829 s41.871,20.939,41.871,54.829C282.827,321.047,268.371,342.739,240.956,342.739z M240.956,251.309 c-11.603,0-16.264,11-16.264,36.608c0,25.592,4.819,36.593,16.264,36.593c11.896,0,16.264-11.294,16.264-36.593 C257.22,262.31,252.544,251.309,240.956,251.309z'/><path style='fill:#FFFFFF;' d='M361.427,259.147c-5.722-4.668-11.753-7.537-19.727-7.537c-14.298,0-24.553,10.699-24.553,36.156 c0,25.005,9.645,35.689,23.959,35.689c10.232,0,16.723-4.224,22.588-8.734l11.294,14.456c-7.68,7.379-18.982,13.56-35.546,13.56 c-28.762,0-48.354-19.132-48.354-54.98c0-34.952,20.939-54.679,48.806-54.679c15.059,0,24.99,4.525,33.724,11.603L361.427,259.147z '/></g></svg>",
	image: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 481.882 481.882' style='enable-background:new 0 0 481.882 481.882;' xml:space='preserve'><path style='fill:#FFFFFF;' d='M60.235,28.913C60.235,12.943,73.178,0,89.148,0h212.028l120.471,101.195v351.774 c0,15.97-12.951,28.913-28.92,28.913H89.148c-15.97,0-28.913-12.943-28.913-28.913V28.913z'/><path style='fill:#E0E0E0;' d='M301.176,0v72.282c0,15.97,12.943,28.913,28.913,28.913h91.558'/><g><rect x='105.412' y='361.412' style='fill:#DCDCDC;' width='271.059' height='15.059'/><rect x='105.412' y='308.706' style='fill:#DCDCDC;' width='97.882' height='15.059'/><rect x='105.412' y='256' style='fill:#DCDCDC;' width='97.882' height='15.059'/><rect x='105.412' y='203.294' style='fill:#DCDCDC;' width='97.882' height='15.059'/><rect x='105.412' y='150.588' style='fill:#DCDCDC;' width='97.882' height='15.059'/><rect x='105.412' y='406.588' style='fill:#DCDCDC;' width='271.059' height='15.059'/></g><rect x='233.412' y='150.588' style='fill:#64B5F6;' width='143.059' height='173.176'/><polygon style='fill:#00897B;' points='257.25,323.765 376.471,323.765 316.86,212.503 '/><circle style='fill:#FFEE58;' cx='275.87' cy='198.483' r='19.87'/></svg>",
	ppt: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 481.882 481.882' style='enable-background:new 0 0 481.882 481.882;' xml:space='preserve'><path style='fill:#FBC02D;' d='M60.235,28.913C60.235,12.943,73.178,0,89.148,0h212.028l120.471,101.195v351.774 c0,15.97-12.943,28.913-28.913,28.913H89.148c-15.97,0-28.913-12.943-28.913-28.913V28.913z'/><path style='fill:#FB8C00;' d='M301.176,0v72.282c0,15.97,12.943,28.913,28.913,28.913h91.558'/><g><path style='fill:#FFFFFF;' d='M150.904,305.536H139.61v34.643h-25.005v-104.38h32.986c28.469,0,44.732,11.144,44.732,34.04 C192.316,294.4,175.601,305.536,150.904,305.536z M147.893,253.568h-8.282v33.89h9.186c11.294,0,17.769-5.429,17.769-17.626 C166.566,258.846,160.392,253.568,147.893,253.568z'/><path style='fill:#FFFFFF;' d='M241.257,305.536h-11.294v34.643h-25.005v-104.38h32.986c28.469,0,44.732,11.144,44.732,34.04 C282.669,294.4,265.954,305.536,241.257,305.536z M238.246,253.568h-8.282v33.89h9.186c11.294,0,17.769-5.429,17.769-17.626 C256.919,258.846,250.744,253.568,238.246,253.568z'/><path style='fill:#FFFFFF;' d='M343.665,254.923v85.256h-25.02v-85.256h-29.222v-19.132h84.661l-2.575,19.132H343.665z'/></g></svg>",
	apps: "<svg viewBox='0 0 24 24' preserveAspectRatio='xMidYMid meet' focusable='false' style='pointer-events: none; display: block; width: 100%; height: 100%;'><g ><path d='M16,4v4h4V4H16z M19,7h-2V5h2V7z M16,10v4h4v-4H16z M19,13h-2v-2h2V13z M10,4v4h4V4H10z M13,7h-2V5h2V7z M10,10v4h4v-4H10z M13,13h-2v-2h2V13z M16,16v4h4v-4H16z M19,19h-2v-2h2V19z M10,16v4h4v-4H10z M13,19h-2v-2h2V19z M4,4v4h4V4H4z M7,7H5V5h2V7z M4,10 v4h4v-4H4z M7,13H5v-2h2V13z M4,16v4h4v-4H4z M7,19H5v-2h2V19z' ></path></g></svg>",
	guild: "<svg viewBox='0 0 24 24' preserveAspectRatio='xMidYMid meet' focusable='false' style='pointer-events: none; display: block; width: 100%; height: 100%;'><g ><path d='M9.8,9.8l-3.83,8.23l8.23-3.83l3.83-8.23L9.8,9.8z M13.08,12.77c-0.21,0.29-0.51,0.48-0.86,0.54 c-0.07,0.01-0.15,0.02-0.22,0.02c-0.28,0-0.54-0.08-0.77-0.25c-0.29-0.21-0.48-0.51-0.54-0.86c-0.06-0.35,0.02-0.71,0.23-0.99 c0.21-0.29,0.51-0.48,0.86-0.54c0.35-0.06,0.7,0.02,0.99,0.23c0.29,0.21,0.48,0.51,0.54,0.86C13.37,12.13,13.29,12.48,13.08,12.77z M12,3c4.96,0,9,4.04,9,9s-4.04,9-9,9s-9-4.04-9-9S7.04,3,12,3 M12,2C6.48,2,2,6.48,2,12s4.48,10,10,10s10-4.48,10-10S17.52,2,12,2 L12,2z' ></path></g></svg>",
	youtube: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M8.051 1.999h.089c.822.003 4.987.033 6.11.335a2.01 2.01 0 0 1 1.415 1.42c.101.38.172.883.22 1.402l.01.104.022.26.008.104c.065.914.073 1.77.074 1.957v.075c-.001.194-.01 1.108-.082 2.06l-.008.105-.009.104c-.05.572-.124 1.14-.235 1.558a2.007 2.007 0 0 1-1.415 1.42c-1.16.312-5.569.334-6.18.335h-.142c-.309 0-1.587-.006-2.927-.052l-.17-.006-.087-.004-.171-.007-.171-.007c-1.11-.049-2.167-.128-2.654-.26a2.007 2.007 0 0 1-1.415-1.419c-.111-.417-.185-.986-.235-1.558L.09 9.82l-.008-.104A31.4 31.4 0 0 1 0 7.68v-.123c.002-.215.01-.958.064-1.778l.007-.103.003-.052.008-.104.022-.26.01-.104c.048-.519.119-1.023.22-1.402a2.007 2.007 0 0 1 1.415-1.42c.487-.13 1.544-.21 2.654-.26l.17-.007.172-.006.086-.003.171-.007A99.788 99.788 0 0 1 7.858 2h.193zM6.4 5.209v4.818l4.157-2.408L6.4 5.209z'/></svg>",
	three_dots: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z'/></svg>",
	share: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M13.5 1a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zM11 2.5a2.5 2.5 0 1 1 .603 1.628l-6.718 3.12a2.499 2.499 0 0 1 0 1.504l6.718 3.12a2.5 2.5 0 1 1-.488.876l-6.718-3.12a2.5 2.5 0 1 1 0-3.256l6.718-3.12A2.5 2.5 0 0 1 11 2.5zm-8.5 4a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zm11 5.5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3z'/></svg>",
    info: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z'/><path d='m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465-.598l.088-.416c-.2.176-.492.246-.686.246-.275 0-.375-.193-.304-.533L8.93 6.588zM9 4.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0z'/></svg>",
    star: "<?xml version='1.0' encoding='UTF-8'?><svg width='24px' height='24px' viewBox='0 0 24 24' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><title>star_line</title><g id='页面-1' stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'><g id='Shape' transform='translate(-240.000000, 0.000000)'><g id='star_line' transform='translate(240.000000, 0.000000)'><path d='M24,0 L24,24 L0,24 L0,0 L24,0 Z M12.5934901,23.257841 L12.5819402,23.2595131 L12.5108777,23.2950439 L12.4918791,23.2987469 L12.4918791,23.2987469 L12.4767152,23.2950439 L12.4056548,23.2595131 C12.3958229,23.2563662 12.3870493,23.2590235 12.3821421,23.2649074 L12.3780323,23.275831 L12.360941,23.7031097 L12.3658947,23.7234994 L12.3769048,23.7357139 L12.4804777,23.8096931 L12.4953491,23.8136134 L12.4953491,23.8136134 L12.5071152,23.8096931 L12.6106902,23.7357139 L12.6232938,23.7196733 L12.6232938,23.7196733 L12.6266527,23.7031097 L12.609561,23.275831 C12.6075724,23.2657013 12.6010112,23.2592993 12.5934901,23.257841 L12.5934901,23.257841 Z M12.8583906,23.1452862 L12.8445485,23.1473072 L12.6598443,23.2396597 L12.6498822,23.2499052 L12.6498822,23.2499052 L12.6471943,23.2611114 L12.6650943,23.6906389 L12.6699349,23.7034178 L12.6699349,23.7034178 L12.678386,23.7104931 L12.8793402,23.8032389 C12.8914285,23.8068999 12.9022333,23.8029875 12.9078286,23.7952264 L12.9118235,23.7811639 L12.8776777,23.1665331 C12.8752882,23.1545897 12.8674102,23.1470016 12.8583906,23.1452862 L12.8583906,23.1452862 Z M12.1430473,23.1473072 C12.1332178,23.1423925 12.1221763,23.1452606 12.1156365,23.1525954 L12.1099173,23.1665331 L12.0757714,23.7811639 C12.0751323,23.7926639 12.0828099,23.8018602 12.0926481,23.8045676 L12.108256,23.8032389 L12.3092106,23.7104931 L12.3186497,23.7024347 L12.3186497,23.7024347 L12.3225043,23.6906389 L12.340401,23.2611114 L12.337245,23.2485176 L12.337245,23.2485176 L12.3277531,23.2396597 L12.1430473,23.1473072 Z' id='MingCute' fill-rule='nonzero'></path><path d='M10.9198,2.8677 C11.402,2.03987 12.598,2.03987 13.0801,2.8677 L15.8751,7.66643 L21.3027,8.84175 C22.239,9.0445 22.6086,10.1819 21.9703,10.8963 L18.2701,15.0374 L18.8295,20.5625 C18.926,21.5156 17.9585,22.2186 17.0818,21.8323 L12,19.5929 L6.91816,21.8323 C6.04149,22.2186 5.07395,21.5156 5.17046,20.5625 L5.72987,15.0374 L2.02972,10.8963 C1.3914,10.1819 1.76097,9.0445 2.69728,8.84175 L8.12484,7.66643 L10.9198,2.8677 Z M12,4.98699 L9.68673,8.95861 C9.5101,9.26187 9.21413,9.4769 8.87114,9.55117 L4.37906,10.5239 L7.44146,13.9513 C7.67529,14.2129 7.78834,14.5609 7.75299,14.91 L7.29,19.4828 L11.4959,17.6294 C11.8171,17.4879 12.1829,17.4879 12.504,17.6294 L16.71,19.4828 L16.247,14.91 C16.2116,14.5609 16.3247,14.2129 16.5585,13.9513 L19.6209,10.5239 L15.1288,9.55117 C14.7858,9.4769 14.4899,9.26186 14.3132,8.95861 L12,4.98699 Z' id='形状' fill='#FDAD15FF'></path></g></g></g></svg>",
    field: "<svg width='16' height='16' viewBox='0 0 16 16' xmlns='http://www.w3.org/2000/svg'><rect width='12' height='1' rx='0.5' x='2' y='3'></rect><rect x='2' y='7' width='12' height='1' rx='0.5'></rect><rect x='2' y='11' width='8' height='1' rx='0.5'></rect></svg>",
	collapse: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-chevron-double-left' viewBox='0 0 16 16'>   <path fill-rule='evenodd' d='M8.354 1.646a.5.5 0 0 1 0 .708L2.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z'/>   <path fill-rule='evenodd' d='M12.354 1.646a.5.5 0 0 1 0 .708L6.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z'/> </svg>",
});



Core.icon = new function __CoreIcon() {

}

SVG.group("for picker", {
	icon_pie: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' width='16px' height='16px'><path d='M 8 2 C 4.6922138 2 2 4.6922138 2 8 C 2 11.307786 4.6922138 14 8 14 C 11.307786 14 14 11.307786 14 8 C 14 4.6922138 11.307786 2 8 2 z M 8 3 L 8 8 L 3 8 C 3 5.2326539 5.2326539 3 8 3 z'/></svg>",
	icon_grid: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' width='16px' height='16px'><path d='M 2.5 1 C 1.675781 1 1 1.675781 1 2.5 L 1 12.5 C 1 13.324219 1.675781 14 2.5 14 L 12.5 14 C 13.324219 14 14 13.324219 14 12.5 L 14 2.5 C 14 1.675781 13.324219 1 12.5 1 Z M 5 2 L 7 2 L 7 4 L 5 4 Z M 8 2 L 10 2 L 10 4 L 8 4 Z M 11 2 L 12.5 2 C 12.78125 2 13 2.21875 13 2.5 L 13 4 L 11 4 Z M 2 5 L 4 5 L 4 7 L 2 7 Z M 8 5 L 10 5 L 10 7 L 8 7 Z M 11 5 L 13 5 L 13 7 L 11 7 Z M 2 8 L 4 8 L 4 10 L 2 10 Z M 5 8 L 7 8 L 7 10 L 5 10 Z M 11 8 L 13 8 L 13 10 L 11 10 Z M 2 11 L 4 11 L 4 13 L 2.5 13 C 2.21875 13 2 12.78125 2 12.5 Z M 5 11 L 7 11 L 7 13 L 5 13 Z M 8 11 L 10 11 L 10 13 L 8 13 Z'/></svg>",
	icon_grid2: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M3.5 15a2.5 2.5 0 100-5 2.5 2.5 0 000 5zm9-9a2.5 2.5 0 100-5 2.5 2.5 0 000 5zm0 9a2.5 2.5 0 110-5 2.5 2.5 0 010 5zM16 3.5a3.5 3.5 0 11-7 0 3.5 3.5 0 017 0zm-9 9a3.5 3.5 0 11-7 0 3.5 3.5 0 017 0zm5.5 3.5a3.5 3.5 0 100-7 3.5 3.5 0 000 7zm-9-11a1.5 1.5 0 110-3 1.5 1.5 0 010 3zm0 2a3.5 3.5 0 100-7 3.5 3.5 0 000 7z'></path></svg>",
	icon_enum: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' width='16px' height='16px'><path d='M 3 1 C 3 1.5625 2.6875 2 2 2 L 2 3 C 2.378906 3 2.710938 2.894531 3 2.726563 L 3 6 L 4 6 L 4 1 Z M 7 3 L 7 4 L 14 4 L 14 3 Z M 3 8 C 2.359375 8 1.824219 8.277344 1.492188 8.664063 C 1.15625 9.054688 1 9.539063 1 10 L 2 10 C 2 9.773438 2.085938 9.503906 2.25 9.316406 C 2.410156 9.128906 2.625 9 3 9 C 3.417969 9 4 9.351563 4 10 C 4 10.023438 3.921875 10.222656 3.683594 10.453125 C 3.445313 10.683594 3.09375 10.933594 2.738281 11.15625 C 2.023438 11.59375 1.296875 11.917969 1.296875 11.917969 L 1 12.046875 L 1 13 L 5 13 L 5 12 L 3.269531 12 C 3.660156 11.757813 4.058594 11.484375 4.378906 11.171875 C 4.703125 10.859375 5 10.5 5 10 C 5 8.773438 3.960938 8 3 8 Z M 7 10 L 7 11 L 14 11 L 14 10 Z'/></svg>",
	icon_list: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path fill-rule='evenodd' d='M2.5 12a.5.5 0 01.5-.5h10a.5.5 0 010 1H3a.5.5 0 01-.5-.5zm0-4a.5.5 0 01.5-.5h10a.5.5 0 010 1H3a.5.5 0 01-.5-.5zm0-4a.5.5 0 01.5-.5h10a.5.5 0 010 1H3a.5.5 0 01-.5-.5z'></path></svg>",
	icon_list_star: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24px' height='24px'><path d='M 3 3 L 3 5 L 21 5 L 21 3 L 3 3 z M 3 9 L 3 11 L 21 11 L 21 9 L 3 9 z M 17.5 13 L 15.941406 16.453125 L 12 16.818359 L 14.933594 19.273438 L 14.107422 23 L 17.5 21 L 20.982422 23 L 19.974609 19.273438 L 23 16.818359 L 19.058594 16.455078 L 17.5 13 z M 3 15 L 3 17 L 10.025391 17 C 10.071391 16.302 10.211547 15.633 10.435547 15 L 3 15 z'/></svg>",
	icon_stack: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M3 0h10a2 2 0 012 2v3a2 2 0 01-2 2H3a2 2 0 01-2-2V2a2 2 0 012-2zm0 1a1 1 0 00-1 1v3a1 1 0 001 1h10a1 1 0 001-1V2a1 1 0 00-1-1H3zm0 8h10a2 2 0 012 2v3a2 2 0 01-2 2H3a2 2 0 01-2-2v-3a2 2 0 012-2zm0 1a1 1 0 00-1 1v3a1 1 0 001 1h10a1 1 0 001-1v-3a1 1 0 00-1-1H3z'></path></svg>",
	icon_trophy: "<svg xmlns='http://www.w3.org/2000/svg' fill='currentColor' class='bi bi-trophy' viewBox='0 0 16 16' id='trophy'><path d='M2.5.5A.5.5 0 013 0h10a.5.5 0 01.5.5c0 .538-.012 1.05-.034 1.536a3 3 0 11-1.133 5.89c-.79 1.865-1.878 2.777-2.833 3.011v2.173l1.425.356c.194.048.377.135.537.255L13.3 15.1a.5.5 0 01-.3.9H3a.5.5 0 01-.3-.9l1.838-1.379c.16-.12.343-.207.537-.255L6.5 13.11v-2.173c-.955-.234-2.043-1.146-2.833-3.012a3 3 0 11-1.132-5.89A33.076 33.076 0 012.5.5zm.099 2.54a2 2 0 00.72 3.935c-.333-1.05-.588-2.346-.72-3.935zm10.083 3.935a2 2 0 00.72-3.935c-.133 1.59-.388 2.885-.72 3.935zM3.504 1c.007.517.026 1.006.056 1.469.13 2.028.457 3.546.87 4.667C5.294 9.48 6.484 10 7 10a.5.5 0 01.5.5v2.61a1 1 0 01-.757.97l-1.426.356a.5.5 0 00-.179.085L4.5 15h7l-.638-.479a.501.501 0 00-.18-.085l-1.425-.356a1 1 0 01-.757-.97V10.5A.5.5 0 019 10c.516 0 1.706-.52 2.57-2.864.413-1.12.74-2.64.87-4.667.03-.463.049-.952.056-1.469H3.504z'></path></svg>",
	icon_shield: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M5.338 1.59a61.44 61.44 0 00-2.837.856.481.481 0 00-.328.39c-.554 4.157.726 7.19 2.253 9.188a10.725 10.725 0 002.287 2.233c.346.244.652.42.893.533.12.057.218.095.293.118a.55.55 0 00.101.025.615.615 0 00.1-.025c.076-.023.174-.061.294-.118.24-.113.547-.29.893-.533a10.726 10.726 0 002.287-2.233c1.527-1.997 2.807-5.031 2.253-9.188a.48.48 0 00-.328-.39c-.651-.213-1.75-.56-2.837-.855C9.552 1.29 8.531 1.067 8 1.067c-.53 0-1.552.223-2.662.524zM5.072.56C6.157.265 7.31 0 8 0s1.843.265 2.928.56c1.11.3 2.229.655 2.887.87a1.54 1.54 0 011.044 1.262c.596 4.477-.787 7.795-2.465 9.99a11.775 11.775 0 01-2.517 2.453 7.159 7.159 0 01-1.048.625c-.28.132-.581.24-.829.24s-.548-.108-.829-.24a7.158 7.158 0 01-1.048-.625 11.777 11.777 0 01-2.517-2.453C1.928 10.487.545 7.169 1.141 2.692A1.54 1.54 0 012.185 1.43 62.456 62.456 0 015.072.56z'></path></svg>",
	icon_contrast: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M8 15A7 7 0 108 1v14zm0 1A8 8 0 118 0a8 8 0 010 16z'></path></svg>",
	icon_edit: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M15.502 1.94a.5.5 0 010 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 01.707 0l1.293 1.293zm-1.75 2.456l-2-2L4.939 9.21a.5.5 0 00-.121.196l-.805 2.414a.25.25 0 00.316.316l2.414-.805a.5.5 0 00.196-.12l6.813-6.814z'></path><path fill-rule='evenodd' d='M1 13.5A1.5 1.5 0 002.5 15h11a1.5 1.5 0 001.5-1.5v-6a.5.5 0 00-1 0v6a.5.5 0 01-.5.5h-11a.5.5 0 01-.5-.5v-11a.5.5 0 01.5-.5H9a.5.5 0 000-1H2.5A1.5 1.5 0 001 2.5v11z'></path></svg>",
	icon_pentagon: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='m8 1.288 6.842 5.56L12.267 15H8V1.288zM16 6.5 8 0 0 6.5 3 16h10l3-9.5z'></path></svg>",
	icon_moon: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M6 .278a.768.768 0 01.08.858 7.208 7.208 0 00-.878 3.46c0 4.021 3.278 7.277 7.318 7.277.527 0 1.04-.055 1.533-.16a.787.787 0 01.81.316.733.733 0 01-.031.893A8.349 8.349 0 018.344 16C3.734 16 0 12.286 0 7.71 0 4.266 2.114 1.312 5.124.06A.752.752 0 016 .278zM4.858 1.311A7.269 7.269 0 001.025 7.71c0 4.02 3.279 7.276 7.319 7.276a7.316 7.316 0 005.205-2.162c-.337.042-.68.063-1.029.063-4.61 0-8.343-3.714-8.343-8.29 0-1.167.242-2.278.681-3.286z'></path></svg>",
	icon_book: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M0 3a2 2 0 012-2h12a2 2 0 012 2v10a2 2 0 01-2 2H2a2 2 0 01-2-2V3zm8.5-1v12H14a1 1 0 001-1V3a1 1 0 00-1-1H8.5zm-1 0H2a1 1 0 00-1 1v10a1 1 0 001 1h5.5V2z'></path></svg>",
	icon_layer: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M8.235 1.559a.5.5 0 00-.47 0l-7.5 4a.5.5 0 000 .882L3.188 8 .264 9.559a.5.5 0 000 .882l7.5 4a.5.5 0 00.47 0l7.5-4a.5.5 0 000-.882L12.813 8l2.922-1.559a.5.5 0 000-.882l-7.5-4zm3.515 7.008L14.438 10 8 13.433 1.562 10 4.25 8.567l3.515 1.874a.5.5 0 00.47 0l3.515-1.874zM8 9.433L1.562 6 8 2.567 14.438 6 8 9.433z'></path></svg>",
	icon_gem: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M3.1.7a.5.5 0 0 1 .4-.2h9a.5.5 0 0 1 .4.2l2.976 3.974c.149.185.156.45.01.644L8.4 15.3a.5.5 0 0 1-.8 0L.1 5.3a.5.5 0 0 1 0-.6l3-4zm11.386 3.785-1.806-2.41-.776 2.413 2.582-.003zm-3.633.004.961-2.989H4.186l.963 2.995 5.704-.006zM5.47 5.495 8 13.366l2.532-7.876-5.062.005zm-1.371-.999-.78-2.422-1.818 2.425 2.598-.003zM1.499 5.5l5.113 6.817-2.192-6.82L1.5 5.5zm7.889 6.817 5.123-6.83-2.928.002-2.195 6.828z'></path></svg>",
	icon_close: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24px' height='24px'><path d='M 4.7070312 3.2929688 L 3.2929688 4.7070312 L 10.585938 12 L 3.2929688 19.292969 L 4.7070312 20.707031 L 12 13.414062 L 19.292969 20.707031 L 20.707031 19.292969 L 13.414062 12 L 20.707031 4.7070312 L 19.292969 3.2929688 L 12 10.585938 L 4.7070312 3.2929688 z'/></svg>",
	icon_ok: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64' width='64px' height='64px'><path d='M27 55L6 33 9 29 26 41 55 12 59 16z'/></svg>",
	icon_bookmark: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M7.84 4.1a.178.178 0 0 1 .32 0l.634 1.285a.178.178 0 0 0 .134.098l1.42.206c.145.021.204.2.098.303L9.42 6.993a.178.178 0 0 0-.051.158l.242 1.414a.178.178 0 0 1-.258.187l-1.27-.668a.178.178 0 0 0-.165 0l-1.27.668a.178.178 0 0 1-.257-.187l.242-1.414a.178.178 0 0 0-.05-.158l-1.03-1.001a.178.178 0 0 1 .098-.303l1.42-.206a.178.178 0 0 0 .134-.098L7.84 4.1z'></path><path d='M2 2a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v13.5a.5.5 0 0 1-.777.416L8 13.101l-5.223 2.815A.5.5 0 0 1 2 15.5V2zm2-1a1 1 0 0 0-1 1v12.566l4.723-2.482a.5.5 0 0 1 .554 0L13 14.566V2a1 1 0 0 0-1-1H4z'></path></svg>",
	
	icon_fill_light: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><path d='M11.251.068a.5.5 0 01.227.58L9.677 6.5H13a.5.5 0 01.364.843l-8 8.5a.5.5 0 01-.842-.49L6.323 9.5H3a.5.5 0 01-.364-.843l8-8.5a.5.5 0 01.615-.09z'></path></svg>",
	icon_fill_bulb: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M2 6a6 6 0 1110.174 4.31c-.203.196-.359.4-.453.619l-.762 1.769A.5.5 0 0110.5 13h-5a.5.5 0 01-.46-.302l-.761-1.77a1.964 1.964 0 00-.453-.618A5.984 5.984 0 012 6zm3 8.5a.5.5 0 01.5-.5h5a.5.5 0 010 1l-.224.447a1 1 0 01-.894.553H6.618a1 1 0 01-.894-.553L5.5 15a.5.5 0 01-.5-.5z'></path></svg>",
	icon_fill_mask: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M6.225 1.227A7.5 7.5 0 0110.5 8a7.5 7.5 0 01-4.275 6.773 7 7 0 100-13.546zM4.187.966a8 8 0 117.627 14.069A8 8 0 014.186.964z'></path></svg>",
	icon_fill_moon: "<svg xmlns='http://www.w3.org/2000/svg' fill='currentColor' class='bi bi-moon-stars-fill' viewBox='0 0 16 16' id='moon-stars-fill'><path d='M6 .278a.768.768 0 01.08.858 7.208 7.208 0 00-.878 3.46c0 4.021 3.278 7.277 7.318 7.277.527 0 1.04-.055 1.533-.16a.787.787 0 01.81.316.733.733 0 01-.031.893A8.349 8.349 0 018.344 16C3.734 16 0 12.286 0 7.71 0 4.266 2.114 1.312 5.124.06A.752.752 0 016 .278z'></path><path d='M10.794 3.148a.217.217 0 01.412 0l.387 1.162c.173.518.579.924 1.097 1.097l1.162.387a.217.217 0 010 .412l-1.162.387a1.734 1.734 0 00-1.097 1.097l-.387 1.162a.217.217 0 01-.412 0l-.387-1.162A1.734 1.734 0 009.31 6.593l-1.162-.387a.217.217 0 010-.412l1.162-.387a1.734 1.734 0 001.097-1.097l.387-1.162zM13.863.099a.145.145 0 01.274 0l.258.774c.115.346.386.617.732.732l.774.258a.145.145 0 010 .274l-.774.258a1.156 1.156 0 00-.732.732l-.258.774a.145.145 0 01-.274 0l-.258-.774a1.156 1.156 0 00-.732-.732l-.774-.258a.145.145 0 010-.274l.774-.258c.346-.115.617-.386.732-.732L13.863.1z'></path></svg>",
	icon_fill_pin: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M9.828.722a.5.5 0 01.354.146l4.95 4.95a.5.5 0 010 .707c-.48.48-1.072.588-1.503.588-.177 0-.335-.018-.46-.039l-3.134 3.134a5.927 5.927 0 01.16 1.013c.046.702-.032 1.687-.72 2.375a.5.5 0 01-.707 0l-2.829-2.828-3.182 3.182c-.195.195-1.219.902-1.414.707-.195-.195.512-1.22.707-1.414l3.182-3.182-2.828-2.829a.5.5 0 010-.707c.688-.688 1.673-.767 2.375-.72a5.922 5.922 0 011.013.16l3.134-3.133a2.772 2.772 0 01-.04-.461c0-.43.108-1.022.589-1.503a.5.5 0 01.353-.146z'></path></svg>",
	icon_fill_record: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M16 8A8 8 0 110 8a8 8 0 0116 0zm-8 3a3 3 0 100-6 3 3 0 000 6z'></path></svg>",
	icon_fill_shield: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M5.072.56C6.157.265 7.31 0 8 0s1.843.265 2.928.56c1.11.3 2.229.655 2.887.87a1.54 1.54 0 011.044 1.262c.596 4.477-.787 7.795-2.465 9.99a11.775 11.775 0 01-2.517 2.453 7.159 7.159 0 01-1.048.625c-.28.132-.581.24-.829.24s-.548-.108-.829-.24a7.158 7.158 0 01-1.048-.625 11.777 11.777 0 01-2.517-2.453C1.928 10.487.545 7.169 1.141 2.692A1.54 1.54 0 012.185 1.43 62.456 62.456 0 015.072.56z'></path></svg>",
	icon_fill_pentagon: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M8 0l8 6.5-3 9.5H3L0 6.5 8 0z'></path></svg>",
	icon_fill_star: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M3.612 15.443c-.386.198-.824-.149-.746-.592l.83-4.73L.173 6.765c-.329-.314-.158-.888.283-.95l4.898-.696L7.538.792c.197-.39.73-.39.927 0l2.184 4.327 4.898.696c.441.062.612.636.282.95l-3.522 3.356.83 4.73c.078.443-.36.79-.746.592L8 13.187l-4.389 2.256z'></path></svg>",
	icon_fill_sun: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M8 12a4 4 0 100-8 4 4 0 000 8zM8 0a.5.5 0 01.5.5v2a.5.5 0 01-1 0v-2A.5.5 0 018 0zm0 13a.5.5 0 01.5.5v2a.5.5 0 01-1 0v-2A.5.5 0 018 13zm8-5a.5.5 0 01-.5.5h-2a.5.5 0 010-1h2a.5.5 0 01.5.5zM3 8a.5.5 0 01-.5.5h-2a.5.5 0 010-1h2A.5.5 0 013 8zm10.657-5.657a.5.5 0 010 .707l-1.414 1.415a.5.5 0 11-.707-.708l1.414-1.414a.5.5 0 01.707 0zm-9.193 9.193a.5.5 0 010 .707L3.05 13.657a.5.5 0 01-.707-.707l1.414-1.414a.5.5 0 01.707 0zm9.193 2.121a.5.5 0 01-.707 0l-1.414-1.414a.5.5 0 01.707-.707l1.414 1.414a.5.5 0 010 .707zM4.464 4.465a.5.5 0 01-.707 0L2.343 3.05a.5.5 0 11.707-.707l1.414 1.414a.5.5 0 010 .708z'></path></svg>",
	icon_fill_stack: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M14.12 10.163l1.715.858c.22.11.22.424 0 .534L8.267 15.34a.598.598 0 01-.534 0L.165 11.555a.299.299 0 010-.534l1.716-.858 5.317 2.659c.505.252 1.1.252 1.604 0l5.317-2.66zM7.733.063a.598.598 0 01.534 0l7.568 3.784a.3.3 0 010 .535L8.267 8.165a.598.598 0 01-.534 0L.165 4.382a.299.299 0 010-.535L7.733.063z'></path><path d='M14.12 6.576l1.715.858c.22.11.22.424 0 .534l-7.568 3.784a.598.598 0 01-.534 0L.165 7.968a.299.299 0 010-.534l1.716-.858 5.317 2.659c.505.252 1.1.252 1.604 0l5.317-2.659z'></path></svg>",
	icon_fill_bell: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' width='16px' height='16px'><path d='M 8 1 C 7.453125 1 7 1.453125 7 2 L 7 3.140625 C 5.28125 3.589844 4 5.140625 4 7 L 4 10.984375 C 3.996094 11.089844 3.945313 12 3 12 L 3 13 L 13 13 L 13 12 C 12.074219 12 12 11.234375 12 11 L 12 7 C 12 5.140625 10.71875 3.589844 9 3.140625 L 9 2 C 9 1.453125 8.546875 1 8 1 Z M 8 13 C 7.449219 13 7 13.449219 7 14 C 7 14.550781 7.449219 15 8 15 C 8.550781 15 9 14.550781 9 14 C 9 13.449219 8.550781 13 8 13 Z'/></svg>",
	icon_fill_bookmark: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24px' height='24px'><path d='M 6 2 C 5.861875 2 5.7278809 2.0143848 5.5976562 2.0410156 C 4.686084 2.2274316 4 3.033125 4 4 L 4 22 L 12 19 L 20 22 L 20 4 C 20 3.8625 19.985742 3.7275391 19.958984 3.5976562 C 19.799199 2.8163086 19.183691 2.2008008 18.402344 2.0410156 C 18.272119 2.0143848 18.138125 2 18 2 L 6 2 z'/></svg>",
	icon_fill_edu: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24px' height='24px'><path d='M 12 5.9199219 L 0 11 L 4 13.539062 L 4 18 L 20 18 L 20 13.539062 L 22 12.269531 L 22 18 L 24 18 L 24 11 L 12 5.9199219 z'/></svg>",
	icon_fill_gift: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24px' height='24px'><path d='M 9.09375 2 L 8 3.59375 L 12 6 L 16 3.59375 L 14.90625 2 L 12 4 Z M 5 7 C 3.894531 7 3 7.894531 3 9 L 3 10 L 11 10 L 11 7 Z M 13 7 L 13 10 L 21 10 L 21 9 C 21 7.894531 20.105469 7 19 7 Z M 4 11 L 4 20 C 4 21.105469 4.894531 22 6 22 L 11 22 L 11 11 Z M 13 11 L 13 22 L 18 22 C 19.105469 22 20 21.105469 20 20 L 20 11 Z'/></svg>",
	icon_fill_alert: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24px' height='24px'><path d='M22.239,18.451L13.442,3.816C13.135,3.305,12.596,3,12,3s-1.135,0.305-1.441,0.815L1.761,18.451 c-0.312,0.519-0.32,1.168-0.022,1.695C2.036,20.673,2.597,21,3.203,21h17.595c0.605,0,1.167-0.327,1.464-0.854 C22.56,19.619,22.551,18.97,22.239,18.451z M13,18h-2v-2h2V18z M13,14h-2V9h2V14z'/></svg>",
	icon_fill_exclaim: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M16 8A8 8 0 110 8a8 8 0 0116 0zM8 4a.905.905 0 00-.9.995l.35 3.507a.552.552 0 001.1 0l.35-3.507A.905.905 0 008 4zm.002 6a1 1 0 100 2 1 1 0 000-2z'></path></svg>",
	icon_fill_donut: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24px' height='24px'><path d='M 11 2.0507812 C 5.947 2.5527813 2 6.815 2 12 C 2 17.523 6.477 22 12 22 C 15.803 22 19.109781 19.876 20.800781 16.75 L 18.003906 15.585938 C 16.781906 17.628937 14.554 19 12 19 C 8.134 19 5 15.866 5 12 C 5 8.474 7.609 5.5660781 11 5.0800781 L 11 2.0507812 z M 13 2.0507812 L 13 5.0800781 C 16.391 5.5660781 19 8.475 19 12 C 19 12.602 18.916437 13.181281 18.773438 13.738281 L 21.568359 14.904297 C 21.847359 13.984297 22 13.01 22 12 C 22 6.815 18.053 2.5527813 13 2.0507812 z'/></svg>",
	icon_fill_heart: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path fill-rule='evenodd' d='M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z'></path></svg>",
	icon_fill_geo: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' ><path d='M8 16s6-5.686 6-10A6 6 0 002 6c0 4.314 6 10 6 10zm0-7a3 3 0 110-6 3 3 0 010 6z'></path></svg>",
	icon_fill_check: "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24px' height='24px'><path d='M11,16.4l-4.7-4.7l1.4-1.4l3.3,3.3l8.4-8.4C17.5,3.3,14.9,2,12,2C6.5,2,2,6.5,2,12s4.5,10,10,10s10-4.5,10-10 c0-1.9-0.5-3.6-1.4-5.1L11,16.4z'/></svg>",
	icon_fill_cursor: "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M14.082 2.182a.5.5 0 0 1 .103.557L8.528 15.467a.5.5 0 0 1-.917-.007L5.57 10.694.803 8.652a.5.5 0 0 1-.006-.916l12.728-5.657a.5.5 0 0 1 .556.103z'></path></svg>",
});


var WTDialogEngine=new function __DialogEngine(){
	this.canvas=function(){
		return $("#apdialogs");
	};

	/**
	 * @desc Render the dialog.
	 */
	this.render=function(dialog){
		$(dialog.canvas()).append("<div class='core-semantic-ui core-semantic-dimmer core-semantic-modals core-semantic-page core-semantic-transition core-semantic-visible core-semantic-active' id='"+(dialog.w(true))+"' style='display: flex !important;'> <div class='__dialogwrapper core-semantic-ui core-semantic-"+(dialog._size)+" core-semantic-modal core-semantic-transition core-semantic-visible core-semantic-active' style='display: block !important;'> <div class='core-semantic-header core-ap-xdot'> "+(dialog._title)+" </div> <div class='core-semantic-content __dialogcontent'></div> <div class='core-semantic-actions __dialogbuttons'></div> </div> </div>");
	};


	/**
	 * @desc Balancing the dialog.
	 */
	this.balance=function(dialog){
		var wid=dialog.w();
		var t=$(window).height()/2- $(wid+' .__dialogwrapper').outerHeight(true)/2-30;
		var l=$(window).width()/2- $(wid+' .__dialogwrapper').outerWidth(true)/2;
		if (t<50){
			t=50;
		}

		if (Client.mobile){
			l=0;
		}

		$(wid+' .__dialogwrapper').css('top', t).css('left', l);
		$(wid+' .__dialogwrapper .__buttons .core-button:last').focus();
	};
};

var FullscreenDialogEngine=new function __FSDialogEngine(){
	this.canvas=function(){
		return $("#apdialogs");
	};

	/**
	 * @desc Render the dialog.
	 */
	this.render=function(dialog){
		var closable="<div class='full-mask' onclick='AP.closeDialog(this);'></div>";
		if (!dialog._closable){
			closable="<div class='full-mask'></div>";
		}

		$(dialog.canvas()).append("<div class='__fsdialog' id='"+(dialog.w(true))+"'> "+(closable)+" <div class='__dialogwrapper'><div class='__dialogcontent'></div></div> </div>");
	};

	this.balance=function(dialog){
		// var wid=dialog.w();
		// $(wid+" .__apdialog").css("right", $.sbWidth());
		return;
	};
};

var CustomDialogEngine=new function __CustomDialogEngine(){

	this.canvas=function(){
		return $("#apdialogs");
	};

	/**
	 * @desc Render the dialog.
	 */
	this.render=function(dialog){
		var close_button="";
		if (dialog._close_button){
			close_button="<div class='__close_button' onclick='AP.closeDialog(this);'><span>${SVG.close}</span></div>";
		}


		var closable="<div class='full-mask' onclick='AP.closeDialog(this);'></div>";
		if (!dialog._closable){
			closable="<div class='full-mask'></div>";
		}


		$(dialog.canvas()).append("" +
			"<div class='__customdialog' id='"+dialog.w(true)+"'>" +
				"<div class='__dialogwrapperscroller scroll-y forced-scroll'>"+
					closable +
					"<div class='__dialogwrapper'>" +
						"<div class='__dialogwrapper-inner'>" +
							"<div class='__dialogmain'>" +
								"<div class='__dialogtitle ap-xdot'>"+"&nbsp;</div>"+
								close_button+
								"<div class='__dialogcontent simple-form'></div>" +
							"</div>"+
						"</div>"+
					"</div>" +
					"<div class='clear'></div>"+
				"</div>"+
			"</div>");
	};

	/**
	 * @desc Balancing the dialog.
	 */
	this.balance=function(dialog){
		var wid=dialog.w();
		// $(wid).css("right", $.sbWidth());

		var t=$(window).height()/2- $(wid+' .__dialogwrapper').height()/2-45;

		if (!Client.native && !Client.mobile){
			var l=$(window).width()/2- $(wid+' .__dialogwrapper').outerWidth(true)/2;
			$(wid+' .__dialogwrapper').css('left', l);

			if (t<50){
				t=50;
			}
		}else{
			if ($(wid).hasClass('-baseui-fit') || (dialog._data && dialog._data.full)){
				$(wid+' .__dialogwrapper').css({float: 'none'}).css({width: '100%'}).css({margin: 'auto'});
				t=0;
			}else{
				$(wid+' .__dialogwrapper').css({float: 'none'}).css({width: '90%'}).css({margin: 'auto'});

				if (t<50){
					t=0;
				}

			}
		}


		if (dialog._data && dialog._data.full){
			$(wid+' .__dialogwrapper').css('top', 0).css('bottom', 0);
		}else{
			$(wid+' .__dialogwrapper').css('top', t);
		}
	};
};

var FormDialogEngine=new function __FormDialogEngine(){
	this.canvas=function(){
		return $("#apdialogs");
	};

	/**
	 * @desc Render the dialog.
	 */
	this.render=function(dialog){
        $(dialog.canvas()).append("<div class='core-semantic-ui core-semantic-dimmer core-scroll-y core-forced-scroll core-semantic-modals core-semantic-page core-semantic-transition core-semantic-visible core-semantic-active' id='"+(dialog.w(true))+"' style='display: flex !important;'> <div class='__dialogwrapper core-semantic-ui core-semantic-"+(dialog._size)+" core-semantic-modal core-semantic-transition core-semantic-visible core-semantic-active' style='display: block !important;'> <div class='__dialogclose' onclick='AP.dialog(\""+(dialog.id())+"\").close();'> <span>"+(SVG.close)+"</span> </div> <div class='core-semantic-header core-ap-xdot'> "+(dialog._title)+" </div> <div class='core-semantic-content __dialogcontent'></div> </div> </div>");
	};


	/**
	 * @desc Balancing the dialog.
	 */
	this.balance=function(dialog){
		var wid=dialog.w();
		var t=$(window).height()/2- $(wid+' .__dialogwrapper').outerHeight(true)/2-30;
		var l=$(window).width()/2- $(wid+' .__dialogwrapper').outerWidth(true)/2;
		if (t<50){
			t=50;
		}

		if (l<0){
			l=0;
		}

		$(wid).css("right", $.sbWidth());
		$(wid+' .__dialogwrapper').css('top', t).css('left', l);
		$(wid+' .__dialogwrapper .__buttons .button:last').focus();
	};
};

AP.config.dialog={};
AP.config.dialog.engine=WTDialogEngine;
AP.config.alertDialogEngine=WTDialogEngine;



var Clog=new function __WLog(){
	this.log=function(key, value){
		$.cookie(key, value,{expires: 7*24*3600, path:'/', domain: Client.domain});
	};
	
	
	this.getLog=function(key){
		return $.cookie(key);
	};
	
	
	this.removeLog=function(key){
		return $.cookie(key, null);
	};
	
	this.setCookie=this.log;
	this.getCookie=this.getLog;
	this.removeCookie=this.removeLog;
	
	this.setAppCookie=function(key, value){
		if (Client.viewer && Client.viewer.id){
			$.cookie(key, value,{expires: 7*24*3600, path:'/', domain: Client.base.app+"."+Client.domain});	
		}
	};
	
	
	this.getAppCookie=this.getLog;
	this.clearAppCookie=this.removeLog;
	
	this.set=function(key, val){
		var item=localStorage.getItem(key);
		if (!item){
			item=[];
		}else{
			item=JSON.parse(item);
		}
		
		var found=false;
		for (i=0; i<item.length; i++){
			if (AP.data.equal(item[i],val)){
				item.splice(i,1);
				item.unshift(val);
				found=true;
				break;
			}
		}
		
		if (!found){
			item.unshift(val);	
		}
		
		localStorage.setItem(key,JSON.stringify(item));
		
	};
	
	
	this.setAdv=function(key, obj){
		var item=localStorage.getItem(key);
		if (!item){
			item=[];
		}else{
			item=JSON.parse(item);
		}
		
		var found=false;
		for (i=0; i<item.length; i++){
			if (AP.data.equal(item[i].id,obj.id)){
				item.splice(i,1);
				item.unshift(obj);
				found=true;
				break;
			}
		}
		
		if (!found){
			item.unshift(obj);	
		}
		
		localStorage.setItem(key,JSON.stringify(item));
	};
	
	
	this.get=function(key){
		var item=localStorage.getItem(key);
		if (!item){
			item=[];
		}else{
			item=JSON.parse(item);
		}
		
		return item;
	};
	
	
	this.setObject=function(key, obj){
		localStorage.setItem(key, JSON.stringify(obj));
	};
	
	
	this.getObject=function(key){
		var item=localStorage.getItem(key);
		if (!item){
			item={};
		}else{
			item=JSON.parse(item);
		}
		
		return item;
	};
	
	
	this.setValue=function(key, value){
		localStorage.setItem(key, value);
	};
	
	
	this.getValue=function(key){
		var item=localStorage.getItem(key);
		if (!item){
			item="";
		}
		
		return item;
	};
	
	
	
	this.setArray=function(key, obj){
		localStorage.setItem(key, JSON.stringify(obj));
	};
	
	
	this.getArray=function(key){
		var item=localStorage.getItem(key);
		if (!item){
			item=[];
		}else{
			item=JSON.parse(item);
		}
		
		if (!AP.data.isArray(item)){
			return [];
		}
		return item;
	};
	
	
	this.clear = function(key){
		localStorage.removeItem(key);
	};
	
};


AP.log = Clog;


Core.pref=function(){
	return new PersonalPreference();
};

function PersonalPreference(){
	this.get=function(key, df){
		if (!df){
			df=null;
		}
		
		var obj=AP.log.getObject("_pref");
		var rkey="k"+trueKey(key);
		if (rkey in obj){
			return obj[rkey];
		}
		
		return df;
	};
	

	this.set=function(key, value){
		var obj=AP.log.getObject("_pref");
		
		obj["k"+trueKey(key)]=value;
		AP.log.setObject("_pref", obj);
		return true;
	};
	

	this.clear = function(key){
		var obj=AP.log.getObject("_pref");
		
		if (obj["k"+trueKey(key)]){
			delete obj["k"+trueKey(key)];
		}
		
		AP.log.setObject("_pref", obj);
		return true;
	};

	this.destroy=function(){
		if (localStorage){
			localStorage.removeItem("_pref");
		}
	};
	
	this.all=function(){
		return obj=AP.log.getObject("_pref");
	};
	
	this.flip = function(key){
		var v = this.get(key, null);
		if (v === null || !v || !parseInt(v)){
			this.set(key, 1);
			return 1;
		}else{
			this.set(key, 0);
			return 0;
		}
	};
	
	
	function trueKey(key){
		if (AP.data.isArray(key)){
			return key.join("_");
		}
		
		return key;
	};
	
};


Core.file = new function __CoreFileAPI() {
    this.preview=function(id){
		return FileX.quickPreview(id);
	};

	this.download=function(name, url){
		return url;
	};
}


var BC=new function __BC(){
    this.show=function(){
		$("#bcanvas").show().removeClass("__simple").addClass("__ontop");
		this.normal();
		
		if (!$("#bcanvas").hasClass('__init')){
			$("#bcanvas").addClass('__init');
			Layout.scrollable("#bside");
		}else{
			$("#bside").find(".scrollin").height("100%").css("width", $("#bside").width()+$.sbWidth());
		}
		
	};
	
	
	this.noSide=function(){
		$("#bcanvas").show().addClass("__simple");
	};

    this.hide=function(){
		$("#bcanvas").find(".__canvas").html("");
		$("#bcanvas").find(".__side").html("");
		$("#bcanvas").find(".__postbottom").html("");
		$("#bcanvas").fadeOut(200);
	};

    this.main=function(content){
		$("#bcanvas .__canvas").html(content);
	};

    this.normal=function(){
		$("#bcanvas").removeClass("extended");
	};
}


Core.applist = new function __CoreAppList(){
    this.init= function(){
		getApps().then(function(data) {
			var html = "<div class='-canvas full-mask' onclick='Core.close();'></div> <div class='core-arrow'></div> <div class='core-box'> <div class='core-top'> <div class='core-search'> <div class='core-input'><input type='text' name='q' id='js-app-search' placeholder='"+(__('Filter apps'))+"'/></div> </div> </div> <div class='core-sb core-scrollable' data-autohide='1' data-autoscroll='1'> <div class='core-inner core-clear-fix'>"+(data)+"</div> </div> </div>";
			$("#core-apps").html(html);
			Layout.scrollable("#core-apps .core-scrollable");
			$("#js-app-search").quickFilter("#core-apps .core-item", function($e, q){
				return AP.word.fulltextMatch($e.text(), q);
			});
		});
	};

    async function getGroups(){
		var groups = [];
		await $.ajax({
            url: Client.link_module,
            data: {
                _r: 1,
                _a: 'get_platform'
            },
            method: "POST",
            dataType: 'json',
            success: function (response) {
                if (!response.success) {
                    return;
                }
                groups = response.platform;
            }
        });
		var key_apps = Object.keys(groups);
		var applist = [];
		await $.ajax({
            url: Client.link_module,
            data: {
                _r: 1,
                _a: 'get_app_list'
            },
            method: "POST",
            dataType: 'json',
            success: function (response) {
                if (!response.success) {
                    return;
                }
                applist = response.app_list;
                Client.apps = response.app_list;
            }
        });
		ARR.loop(applist, function(g){
			var parts = AP.word.safeSplit(",", g.group);
            for (var i=0; i<parts.length; i++){
				if (key_apps.includes(parts[i])) {
                    groups[parts[i]].apps.push(g);
                }
			}
		});

		var gs = ARR.selectObj(groups, function(obj, index, key){
			obj.key = key;
			return obj;
		});
		return gs;
	};


	async function getApps(){
		var groups = await getGroups();
		return AP.render(groups, function(e, index){
			return getGroup(e, index);
		});
	};

    function getGroup(g, index){
		if (!g.apps || !g.apps.length){
			return '';
		}

		var apps = '';
		apps = AP.render(g.apps, function(app){
            return getApp(app);
        });

        return "<div class='core-app-group'> <div class='core-g-header'> <div class='core-g-title core-url' data-url=':collapse/2'><span>"+(g.title)+"</span></div> <div class='core-g-info'>"+(g.desc)+"</div> </div> <div class='core-g-body'> "+(apps)+" </div> </div>";
	};

    function getApp(app){
        var url_app = Client.dev ? "#" : app.url;
		return "<a class='core-item' target='_blank' href='"+(url_app)+"'> <span class='core-image'> <img src='"+(app.image)+"'/> </span> <span class='core-text core-ap-xdot'>"+(app.name)+"<em class='core-ap-xdot'>"+(app.title)+"</em></span> </a>";
	};
}



Core.videolist = new function __CoreVideoList(){
    this.init= function(){
        getVideos().then(function(data) {
            var html = "<div class='-canvas full-mask' onclick='Core.close();'></div> <div class='core-arrow'></div> <div class='core-box'> <div class='core-top'> <span class='video-introdute'>"+(__('These video tutorials will be helpful for you'))+"</span> <div class='core-search'> <div class='core-input'><input type='text' name='q' id='js-video-search' placeholder='"+(__('Filter videos'))+"'/></div> </div> </div> <div class='core-sb core-scrollable' data-autohide='1' data-autoscroll='1'> <div class='core-inner core-clear-fix'>"+(data)+"</div> </div> </div>";
            $("#core-video").html(html);
            Layout.scrollable("#core-video .core-scrollable");
            $("#js-video-search").quickFilter("#core-video .core-item", function($e, q){
                return AP.word.fulltextMatch($e.text(), q);
            });
            if(typeof Client.is_demo != 'undefined' && Client.is_demo) {
                $("#core-video").toggle();
            }
        });
    };

    async function getDataVideo(){
        var videolist = [];
        await $.ajax({
            url: Client.link_module,
            data: {
                _r: 1,
                _a: 'get_video_list'
            },
            method: "POST",
            dataType: 'json',
            success: function (response) {
                if (!response.success) {
                    return;
                }
                videolist = response.videos;
            }
        });

        if(typeof videolist[Client.name_module] == 'undefined') {
            return [];
        }
        return videolist[Client.name_module];
    };


    async function getVideos(){
        var videos = await getDataVideo();
        if(!videos.length) {
            $('#core-video').remove();
            $('.video-youtube-list').addClass('core-hidden');
            return $('.video-youtube-channel').removeClass('core-hidden');
        }
        return AP.render(videos, function(video, index){
            return getVideo(video);
        });
    };

    function getVideo(video) {
        return "<div class='core-app-group'> <div class='core-g-header'> <div class='core-g-title core-url' data-url=':collapse/2'><span>"+(video.title)+"</span></div> <div class='core-g-info'>"+(video.description)+"</div> </div> <div class='core-g-body'> <div class='core-item'> <span class='core-text core-ap-xdot core-hidden'><em class='core-ap-xdot'>"+(video.title)+"</em></span> <iframe width='730' height='400' src='"+(video.link)+"' title='"+(video.title)+"' frameborder='0' allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share' allowfullscreen></iframe> </div> </div> </div> ";
    }
}



Core.filter = function (opts) {
    opts = $.extend({}, {canvas: "#page", handler: "#js-filter-button"}, opts);

    $("#js-master-filters .js-close").click(function () {
        $("#js-master-filters").removeClass("open");
        setTimeout(function () {
            $("#js-master-filters").hide();
        });
    });

    $("#js-master-filters .js-submit").click(function () {
        updateFilters(this);
    });
    $("#js-master-filters .btn-clear-filter").click(function () {
        clearFilter();
    });

    setTimeout(function () {
        setValues();
    }, 100);

    $(opts.handler).click(function () {
        $("#js-master-filters").show();
        setTimeout(function () {
            $("#js-master-filters").addClass("open");
        });
    });


    function updateFilters(ref) {
        var data = assoc($("#js-master-filters .core-control :input").not($("#js-master-filters .core-control select[is_fake]")).not($("#js-master-filters .core-control input[is_fake]")).serializeArray());
        for (var key in data) {
            if (data[key] === "") {
                delete data[key];
                continue;
            }
            data[key] = data[key]?.replaceAll(', ', '-');

            if (data[key].match(/[0-9]+-[0-9]+/gm)) {
                var split = AP.word.split('-', data[key]);
                if (se(split[0], split[1])) {
                    delete data[key];
                }
            }
        }

        data["page"] = null;
        AP.setURLParams(data, true);
    };


    function setValues() {
        var active = 0;
        $("#js-master-filters :input").each(function () {
            var name = $(this).attr("name");
            var v = Query.get(name);
            if (v === null || v === "") {
                return;
            }
            v = v?.replaceAll('-', ', ');
            active++;
            $(this).val(v);
        });

        if (active) {
            $(opts.handler).addClass("active").find(".-txt").html(""+(__('Filters'))+" ("+(active)+")");
        }
    };

    function clearFilter() {
        var params = Query.all();
        var except = ['env', 'show', 'id', 'controller', 'token', '_a'];
        var reset = {};
        for (var key in params) {
            if (AP.array.contain(except, key)) {
                continue;
            }
            reset[key] = null;
        }
        AP.setURLParams(reset);
        AP.xRefresh();
    }
};



Rewrite.on("::core/-/{action}", function(qs){
    var action = qs.action
    if (action == "collapse_master_menu"){
        return collapseMasterMenu($(this));
    }
});

function collapseMasterMenu(ref) {
    var menu_wrapper = ref.closest("#page").find("> .core-master-menu");
    if (menu_wrapper.hasClass("-collapsed")) {
        menu_wrapper.css("width", "").removeClass("-collapsed");
        ref.removeClass("-collapsed");
        $(".core-master-page").css({
            "left": "220px"
        });
        setTimeout(function() {
            $(".core-master-page").css("transition", "");
        }, 1000);
        Core.pref().set('master-menu-collapsed', 0);
        return;
    }
    Core.pref().set('master-menu-collapsed', 1);
    menu_wrapper.css("width", "50px").addClass("-collapsed");
    $(".core-master-page").css({
        "transition": "left 0.5s linear 0.5s",
        "left": "50px"
    });
    ref.addClass("-collapsed");
}




var Render = new function __Render() {
    this._uis={};
    this._events={};
	this._event_queues = [];

    this.__cache_data = {};
	
	this.__custom_uis = {};

    this.on = function(ui, render, events){
		if (AP.data.isArray(ui)){
			for (var i=0; i<ui.length; i++){
				this.on(ui[i], render, events);
			}
			return;
		}
		
		var __evs = events;
		if (AP.data.isFunction(events)){
			__evs = {done: events};
		}
		
		if (!__evs){
			__evs = {};
		}
		
		this._uis[ui.replace(/-/g,'_')] = render;
		this._events[ui.replace(/-/g,'_')] = __evs;
	};

    this.uis = function(filter){
		if (!filter){
			return this._uis;	
		}
		
		var obj = {};
		for (var key in this._uis){
			if (key.indexOf(filter)!=-1){
				obj[key] = this._uis[key];
			}
		}
		
		return obj;
	};

    this.render = function(ui, attrs, content){
		if (!attrs.id){
			attrs.id = AP.uuid();
		}
		if (!this._uis[ui]){
			console.warn("NO UI render for "+ui);	
			
			var obj = new CoreComponent(attrs);
			var ec = ui.replace(/_/g,'-');
			if (ec.indexOf("-")==-1){
				ec='';
			}
			
			if (attrs.url){
				obj.addClass("url");
			}
			
			if ('acl' in attrs && !Render.helper.acl(attrs.acl)){
				return '';
			}
			
			if (attrs.fit){
				obj.addClass('ap-xdot');
			}
			
			if (attrs.inline){
				obj.addClass('inline');
			}
			
			if (attrs.upper){
				obj.css("text-transform", "uppercase");
			}
			
			if (attrs.fs){
				obj.css("font-size", attrs.fs+"px");
			}
			
			if ('color' in attrs){
				obj.addStatusColor(attrs.color);
				obj.css("color", Color.get(obj.color));
			}
			
			return "<div class='core-"+(ui)+" "+(ec)+" "+(obj.get('class'))+"' "+(obj.show('id'))+" "+(obj.css())+" "+(obj.show('url'))+" "+(obj.showAllHTMLEvents())+" "+(obj.showAllData())+">"+(content)+"</div>";
		}
		
		var fn = this._uis[ui];
		var obj = new CoreComponent(attrs);
		
		obj.name=ui;
		obj.content=content;
		
		attrs.name = ui;
		if (this._events[ui] && this._events[ui]["done"]){
			var done = this._events[ui]["done"];
			this._event_queues.push({fn: done, attrs: safeClone(attrs), obj: obj});
			
			if (this._debug){
				$.log(["EVENT REGISTERED", ui, obj.id, done]);
			}
		}
		
		return fn.apply(obj);
	};

    this.finish = function(){
		if (!this._event_queues.length){
			return;
		}
		
		while (true){
			if (!this._event_queues.length){
				return;
			}
			var ex = this._event_queues.shift();
			var $selector = $("#"+ex.attrs.id);
			if (!$selector.length){
				if (this._debug){
					$.log("COMPONENT DEBUG: ELEMENT NOT FOUND - "+ex.attrs.id);
				}
				continue;
			}
			
			ex.fn.apply($selector[0], [ex.attrs, ex.obj]);
		}
	};

    /**
	 * @desc Checking acl of a component
	 */
	this.acl = function(comp){
		if ('require' in comp && !Render.helper.acl(comp.require)){
			return false;
		}
		
		if ('acl' in comp && !Render.helper.acl(comp.acl)){
			return false;
		}
		
		return true;
	};

	function safeClone(obj){
		var r={};
		for (var key in obj){
			if (AP.data.isObject(obj[key]) || AP.data.isArray(obj[key]) || AP.data.isFunction(obj[key])){
				
			}else{
				r[key] = obj[key];
			}
		}
		
		return r;
	};
};

Render.ui = {};

(function(){
	jquery_domChanged = function(){
		Render.finish();
	};
})();



function CoreComponent(opts){
	this._params = {};

	this.addClass = function(_class){
		if (!this._class){
			this._class="";
		}

		this._class+= " "+_class;
	};

	if (opts){
		this._params = opts;

		for (var key in opts){
			if (key == "class"){
				this["_class"] = opts[key];
			} else{
				this[key] = opts[key];
			}

		}

		if (this.url){
			this.addClass("core-url");
		}

		if (this.thick){
			this.addClass("core-thick");
		}else if (this.bold){
			this.addClass("core-old");
		}


		if (opts.size && opts.size == 'sm'){
			opts.sm = 1;
		}else if (opts.size && opts.size == 'lg'){
			opts.lg = 1;
		}
	}



	this._css={};

	this.get = function(key){
		if (key == "class"){
			key = "_class";
		}

		if (this[key]){
			return this[key];
		}

		return "";
	};

	this.show = function(key){
		if (key == "class"){
			key = "_class";
		}

		if (key in this){
			if (key == "url"){
				var extra='';
				if (this.blank || this.target=='blank' || this.target=='_blank'){
					extra=" data-blank='1'";
				}

				return "data-url='"+(this[key])+"'"+(extra)+"";
			}

			return ""+(key)+"='"+(this[key])+"'";
		}

		return '';
	};


	this.setData = function(key, val){
		this["data_"+key] = val;
	};

	this.showData = function(key){
		var v = this.get(key);

		if (v === "" || AP.data.isObject(v) || AP.data.isArray(v)){
			return "";
		}

		return "data-"+(key)+"='"+(v)+"'";
	};


	this.showAllData = function(){
		var html='';

		for (var key in this){
			if (AP.data.isString(key) && AP.word.prefix(key, "data_")){
				var v= this[key];
				if (v === "" || AP.data.isObject(v) || AP.data.isArray(v)){
				}else{
					html+=" data-"+(key.substr(5))+"='"+(v)+"'";
				}
			}
		}

		return html;

	};


	this.showAllHTMLEvents = function(){
		var html = '';
		if (this.onclick){
			html +="onclick='"+(this.onclick)+"'";
		}

		return html;
	};


	// Extra support

	this.has = function(key){
		if (key in this){
			return true;
		}

		return false;
	};


	this.setParam = function(key, val){
		this[key]=val;
	};


	this.params = function(){
		return this._params;
	};


	/**
	 * @desc Check if a color is hex
	 */
	this.isHexColor = function(color){
		return /^#[0-9A-F]{6}$/i.test(color);
	};


	this.getColor = function(color, df){
		var r = "#aaaaaa";
		if (this.isHexColor(this[color])){
			r = this[color];
		}else{
			r = Color.get(this[color]);
		}

		if (!r){
			return df;
		}

		return r;
	};


	this.css = function(){
		if (!arguments.length){
			var styles = this.get("style");

			for (var key in this._css){
				styles+="; "+(key)+":"+(this._css[key])+"";
			}

			if (AP.word.prefix(styles, ";")){
				styles = styles.substr(2);
			}

			return "style='"+(styles)+"'";
		}else{

			this._css[arguments[0]] = arguments[1];

		}
	};


	this.addSizingClass = function(){
		if (this.md){
			this.addClass("-md");
		}

		if (this.el){ // Enlarged, 20px
			this.addClass("-el");
		}

		if (this.lg || this.size === "lg"){
			this.addClass("-lg");
		}

		if (this.sm || this.size === "sm"){
			this.addClass("-sm");
		}

		if (this.xs){
			this.addClass("-xs");
		}

		if (this.xl){
			this.addClass("-xl");
		}

		if (this.xxl){
			this.addClass("-xxl");
		}

		if (this.xxxl){
			this.addClass("-xxxl");
		}

		if (!this.md && !this.lg && !this.xl && !this.sm && !this.el){
			this.addClass("-size-df");
		}
	};


	this.addStatusColor=function(){
		if (this.success){
			this.color="success";
		}

		if (this.warning || this.orange){
			this.color="orange";
		}

		if (this.danger || this.error){
			this.color="error";
		}

		if (this.notice){
			this.color="notice";
		}

		if (this.gray){
			this.color= "gray";
		}

		if (this.yellow){
			this.color= "yellow";
		}
	};


	this.addStandardTextLayout = function(){
		this.addStatusColor();
		this.addSizingClass();
		this.addClass("-core-text");
	};

	this.addStateClass = function(){
		if (this.focus){
			this.addClass("-focus");
		}

		if (this.highlight){
			this.addClass("-highlight");
		}

		if (this.success){
			this.addClass("-success");
		}

		if (this.danger){
			this.addClass("-danger");
		}

		if (this.warning){
			this.addClass("-warning");
		}

	};


	this.showHTMLSemantics = function(){
		var html='';
		if (this.html_title){
			html+=" title='"+(this.html_title)+"' ";
		}

		return html;
	};

	this.showHTMLAttrs = this.showHTMLSemantics;

	this.showURL = function(){
		if (this.url){
			return " data-url='"+(this.url)+"'";
		}

		return '';
	};

	this.showHTMLEvents = function(){
		var events = '';
		if (this.onclick){
			events+=" onclick='"+(this.onclick)+"'";
		}

		return events;
	};


	this.convertTo = function(comp){
		return Render.render(comp.replace(/-/g,'_'), this._params, this.content);
	};


	this.templateHTML = function(tpl, html){
		this.templated_name = this.name.replace(/_/g,'-');
		return Render.template("layout", this, html);
	};


	function getURLParam(str){
		if (!str){
			return null;
		}

		if (str.match(/^([a-zA-Z0-9]+)\|([a-zA-Z0-9\_\-]*)$/)){
			var parts = str.split("|");
			if (parts.length!=2){
				return null;
			}

			return {param: $.trim(parts[0]), value: $.trim(parts[1])};
		}

		return null;
	};
}





var FileX = new function __File(){
    this.quickPreview=function(file_src, multiple){
		if (AP.data.isObject(file_src)){
			BC.show();
			BC.noSide();
			BC.main(FileX.ui.getMain(file_src));
			return;
		}
		var is_image=0;
		var ext=UI.file.ext(file_src);
		if (ext=="jpg" || ext=="png" || ext=="bmp" || ext=="jpeg" || ext=="gif"){
			is_image=1;
		}
		
		var file={name: file_src, src: file_src, image: is_image};
		BC.show();
		BC.noSide();
		BC.main(FileX.ui.getMain(file));
	};
}

FileX.ui=new function __FileUI(){
    this.getMain=function(file){
		var regEx = /(?:\.([^.]+))?$/;
		var fileExtension = regEx.exec(file.name)[1];
		if (isImage(file)){
			return "<div class='core-embed-20 core-embed-image'><div class='core-image'><img src='"+file.src+"'/></div></div>";
		}else if (isEmbeddable(file) || (fileExtension == "txt")){
			
			if (file.metatype=="onedrive"){
				var url=file.src+"&em=2";
				
				// get cid
				var pos = url.indexOf('resid=');
				var suburl = url.substring(pos);
				var pivot = suburl.indexOf('!');
				var cid = suburl.substring(6, pivot);
				
				url = url.replace("redir?","embed?cid="+cid+"&");
				
				return "<div class='core-embed-20 core-embed-file -iframe'>" +
					"<iframe src=\""+url+"\" style='width:100%; height:100%;' frameborder='0' scrolling='no'></iframe>"+
				"</div>";
			}else if (file.metatype=="dropbox"){
				var url=file.preview;
				if (!url){
					return "<div style='margin-top: 60px; font-size: 15px; text-align:center;'>" +
							"<div class='featured' style='margin-bottom: 15px;'>This file has been picked from Dropbox and can't be previewed.</div>" +
							"<a href='" + file.src + "'>Click here to download file</a>" +
							"</div>";
				}
				
				url=url.replace("bounding_box=75","bounding_box=800");
				return "<div class='core-embed-20 core-embed-image'><div class='core-image'><img src='"+url+"'/></div></div>"
			}else if (file.metatype == "google" || file.metatype == "googledrive"){
				if ($.inArray(fileExtension, ['gdoc', 'gsheet', 'gdraw', 'gslides']) < 0) {
					return "<div class='core-embed-20 core-embed-file'>" +
						"<iframe src=\""+file.preview+"\" style='width:100%; height:100%;' frameborder='0'></iframe>"+
					"</div>";
				} else {
					return "<div class='core-embed-20 core-embed-file'>" +
						"<iframe src=\""+file.src.substr(0, file.src.lastIndexOf('?'))+"\" style='width:100%; height:100%;' frameborder='0'></iframe>"+
					"</div>";
				}
			}

			// preview from drive
			if (file.name.indexOf("drive.google.com") !== -1 && file.name.indexOf("preview") !== -1){
				return "<div class='core-embed-20 core-embed-file -iframe'>"+
					"<iframe src='" + file.src + "' style='width:100%; height:100%;' frameborder='0'></iframe>" +
					"</div>";
			}
			
			// M$ Office file types
			
			if ($.inArray(fileExtension, ['doc', 'docx', 'xls', 'xlsx', 'xlsm', 'ppt', 'pptx']) >= 0) {
				return "<div class='core-embed-20 -iframe core-embed-file'>" +
					"<iframe src=\"https://view.officeapps.live.com/op/embed.aspx?src="+file.src+"\" style='width:100%; height:100%;' frameborder='0'></iframe>"+
				"</div>";
			}

			if (fileExtension == "pdf") {
				return "<div class='core-embed-20 core-embed-file -iframe'>"+
					"<iframe src='" + file.src + "' style='width:100%; height:100%;' frameborder='0'></iframe>" +
				"</div>";
			}

			if (Client.https) {
				return "<div class='core-embed-20 -iframe core-embed-file'>" +
					"<iframe src=\"https://docs.google.com/gview?url="+file.src+"&embedded=true\" style='width:100%; height:100%;' frameborder='0'></iframe>"+
				"</div>";
			}
			return "<div class='core-embed-20 -iframe core-embed-file'>" +
				"<iframe src=\"http://docs.google.com/gview?url="+file.src+"&embedded=true\" style='width:100%; height:100%;' frameborder='0'></iframe>"+
			"</div>";
		}else if (fileExtension=='webm'){
			return "<div class='core-embed-20 core-embed-image'><div class='core-embed-video-inline -abs-fit'> <video controls style='max-height:100%; width:100%; height: auto;'> <source src='"+(file.src)+"' type='video/webm'> Sorry, your browser doesn't support embedded videos. </video> </div></div>";
		}else if (fileExtension=='mp3'){
			return "<div class='core-embed-20 core-embed-image'><div class='core-embed-video-inline -abs-fit core-center'> <audio controls> <source src='"+(file.src)+"' type='audio/mpeg'> Your browser does not support the audio element. </audio> </div></div>";
		}else if (fileExtension=='svg'){
			return "<div class='core-embed-20 core-embed-image'><div class='core-embed-svg -abs-fit core-center'> <img src='"+(file.src)+"'/> </div></div>";
		}else{
			var download=file.src;
			return "<div class='core-center' style='padding:20px;'>No preview avaiable. Please <a href='"+download+"' target='_blank'>download the file</a>.</div>";
		}
	}; 

    function isImage(file){
		if (file.image && parseInt(file.image)){
			return true;
		}

		return false;
	};

    function isEmbeddable(file){
		var ext = AP.fileExt(file.name);
		
		if (file.metatype=="onedrive"){
			return true;
		}
		
		if (file.metatype=="dropbox" && file.preview && file.preview.length && (ext=="png" || ext=="jpg" || ext=="jpeg" || ext=="gif")){
			return true;
		}
		
		if (file.metatype == "google" || file.metatype == "googledrive"){
			return true;
		}

		if (file.name.indexOf("drive.google.com") !== -1 && file.name.indexOf("preview") !== -1){
			return true;
		}
		
		if ($.inArray(ext, ["doc", "docx", "rtf", "xls", "xlsx", "ppt", "pptx", "pdf", "txt", "json", "xml", "db"]) > -1) {
			return true;
		}
		
		return false;
	};
}




AP.sys.on("page.pre.transition", function (data) {
	loadBar(true);
});

AP.sys.on("page.post.transition", function (data) {
    loadBar(false);
    document.title = Client.pageData.meta_title;
});

AP.sys.on("form.pre.submit", function (selector) {
	if (Client.pageData.event && Client.pageData.event.id) {
		$(selector).append("<input type='hidden' name='__event' value='" + Client.pageData.event.id + "'/>");
	}
});

AP.adaptive = function (u1, u2) {
	return true;
};


function documentInit() {
	AP.initPageData();
	Layout.start();
};

function ap_update(selector, data) {
	$(selector).html(data);
	// AP.setContinuousRequest(selector);
	// AP.html.init(selector);
};

function getLinkDocument() {
    var lang_default = 'en';
    var lang_support = ['en', 'fr', 'es', 'it'];
    var lang_current = AP.array.find(Client.langs, function(lang) {
       return Number(lang.id_lang) == Number(Client.employee.id_lang);
    });
    var link = "https://attechteam.com/documents/"+(Client.name_module)+"/readme_en.pdf";
    if (lang_current && typeof lang_current?.iso_code !== 'undefined' && lang_support.includes(lang_current.iso_code)) {
        link = "https://attechteam.com/documents/"+(Client.name_module)+"/readme_"+(lang_current.iso_code)+".pdf";
    }
    return link;
}


function reset_page(callback) {
	$("#page").children().remove();
	$("#page").empty().html("&nbsp;");
	// Clear lock

	AP.__lock = false;

	AP.resetPageData();
	Render.graph_db = {};

	AP.sys.fire("page.pre.transition");

	if (callback) {
		callback();
	}
};

function update_page(data) {
	ap_update("#page", data);
	$("#master").scrollTop(0);

	window.scrollTo(0, 0);
	$("#ap-data").empty();

	documentInit();

	AP.sys.fire("page.post.transition");
	AP.sys.fire(AP.EVENTS.PAGE_UNLOAD);

	if (AP.isset('FB')) {
		try {
			FB.XFBML.parse();
		} catch (ex) {
		}
		;
	}
};

function loadBar(status) {
	if (!status) {
        NProgress.done();
	} else {
        NProgress.start();
	}
};

function copyClipBoard(element, value = '') {
    var $temp = $("<input>");
    $("body").append($temp);
    if (value == '') {
        var string_copy = AP.word.replace($(element).text(), ' ', '');
        $temp.val(string_copy).select();
    } else {
        var string_copy = AP.word.replace(value, ' ', '');
        $temp.val(string_copy).select();
    }
    document.execCommand("copy");
    $temp.remove();
    AP.toastr.success(__('Copy successfully'));
}

 


var UI = new function __UI(){
	this.ajaxShow = function(){
		$("#ajax-load-google").show();
	};

	this.ajaxHide = function(){
		$("#ajax-load-google").hide();
	};

	this.flash = function(msg){
		$("#core-flash-msg").show().html(msg).css({top: -80}).animate({top: 90}, 300).delay(1300).animate({top: -80}, 300, function(){
			$(this).hide();
		});
	};

	this.time = function(ts){
		return AP.time.time("%h:%i %M %d", ts);
	};


	this.simpleTime = function(time){
		var today = AP.time.time("%M %d", AP.time.now());
		var yesterday = AP.time.time("%M %d", AP.time.now() - 24 * 3600);
		var test = AP.time.time("%M %d", time);

		if (today == test){
			return AP.time.time("%H:%i today", time);
		} else if (today == yesterday){
			return AP.time.time("%H:%i yesterday", time);
		}

		return AP.time.time("%H:%i %M %d", time);
	};

	this.simpleDate = function(time){
		return AP.time.time("%M %d, %Y", time);
	};

	this.editor = function(selector, action, them){
	    if (AP.config.editor = 'suneditor') {
	        return this.editorSun(selector, action, them);
        }
	    this.editorQuill(selector, action, them);
	};

    this.inputDate = function(time){
        return AP.time.time(AP.i18n.dateFormat(), time);
    };

	this.editorSun = function(selector, action, them) {
	    $(selector).addClass("sun-editor-editable");
        var options = {
            minHeight: action.minHeight,
            minWidth: action.minWidth,
            maxHeight: action.maxHeight,
            buttonList: [
                ['undo', 'redo'],
                ['font', 'fontSize', 'formatBlock'],
                ['paragraphStyle', 'blockquote'],
                ['bold', 'underline', 'italic', 'strike', 'subscript', 'superscript'],
                ['fontColor', 'hiliteColor', 'textStyle'],
                ['removeFormat'],
                ['outdent', 'indent'],
                ['align', 'horizontalRule', 'list', 'lineHeight'],
                ['table', 'link', 'image', 'video', 'audio'],
                ['fullScreen', 'showBlocks', 'codeView'],
                ['preview', 'print']
            ],
            imageAccept: ".jpg, .jpeg, .png, .gif, .webp"
        };
        var editor = SUNEDITOR.create($(selector)[0], options);
        editor.onImageUploadBefore = function(files, info, core, uploadHandler) {
            var form_data = new FormData();
            form_data.append('file', files[0]);
            form_data.append('_a', 'upload');
            form_data.append('_r', 1);
            $.ajax({
                url: Client.link_module,
                type: 'POST',
                processData: false,
                contentType: false,
                data: form_data,
                success: function (response) {
                    uploadHandler(parseCode(response));
                }
            });
        }

        editor.onChange = function (contents, core) {
            $(selector).val(contents);
        }
    }

	this.editorQuill = function(selector, action, them) {
        if (!action && AP.data.isObject(selector)){
            return this._editor(selector);
        }

        if (action == 'empty'){
            $(selector).trumbowyg('empty');
            return;
        }

        if (action == 'focus'){
            $(selector).closest(".trumbowyg-box").find(".trumbowyg-editor").focus();
            return;
        }


        var mh=$(selector).data("minheight");
        if (!mh){
            $(selector).data("minHeight");
        }

        if (!mh && AP.data.isObject(action)){
            mh=action.minHeight;
        }

        if (!mh){
            mh=300;
        }

        if (mh<10){
            mh=20;
        }

        // Quill editor
        var opts={};
        if (AP.data.isObject(action)){
            opts=action;
        }

        var compact=$(selector).data("compact");
        if (!compact){
            compact=opts.compact;
        }

        var toolbarOptions = [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            ['blockquote', 'code-block',{"align": ['', 'center', 'right','justify']}],

            [{ 'header': 1 },{ 'header': 2 }],  // custom button values
            [{ 'list': 'ordered'},{ 'list': 'bullet' }],
            [{ 'script': 'sub'},{ 'script': 'super' }], // superscript/subscript
            ["link", "image"],

            [{ 'color': [] },{ 'background': [] }], // dropdown with defaults from theme
            ['clean'] // remove formatting button
        ];

        if (compact==1 || compact=="compact"){
            toolbarOptions = [
                ['bold', 'italic', 'underline', 'strike'], // toggled buttons
                [
                    {'header': 1 },{ 'header': 2 },
                    { 'list': 'ordered'},{ 'list': 'bullet' }
                ],

                [
                    {"align": ['', 'center', 'right','justify']},
                    'blockquote', 'code-block', "link", "image",
                ],

                [{ 'color': [] },{ 'background': [] }, // dropdown with defaults from theme
                    'clean'] // remove formatting button
            ];
        }else if (compact==2){
            toolbarOptions = [
                ['bold', 'italic', 'underline',  'strike'], [{'header': 1 },{ 'header': 2 }], // toggled buttons
                [{ 'list': 'ordered'},{ 'list': 'bullet' }],
                ['clean'],
            ];
        }

        var id=AP.uuid();
        var mh=300;
        if (opts.height){
            mh=opts.height;
        }else if (opts.minHeight){
            mh=opts.minHeight;
        }

        if (mh!="auto"){
            $(selector).hide().after("<div id='"+(id)+"' class='quill-wrapper' style='height:"+(mh)+"px'></div>");
        }else{
            $(selector).hide().after("<div id='"+(id)+"' class='quill-wrapper'></div>");
        }

        var theme = 'snow';
        if (action.theme){
            theme = action.theme;
        }else if (action.bubble){
            theme = 'bubble';
        }

        var q=new Quill('#'+id,{
            modules:{
                toolbar: toolbarOptions
            },
            theme: theme,
            placeholder:$(selector).attr("placeholder"),
        });


        var toolbar = q.getModule('toolbar');
        toolbar.addHandler('image', function(){
            var last_index=q.getSelection()?q.getSelection().index:0;
            quill_imageUpload(function(url){
                var s=q.getSelection();
                if (s){
                    last_index=s.index;
                }

                if (url.substring(0, 4) == "http"){
                    q.insertEmbed(last_index, 'image', url);
                }
            });
        });

        q.root.setAttribute('spellcheck', false);

        var $canvas=$("#"+id);
        $canvas.data("editor", q);
        $(selector).data("editor", q);

        if (opts.fit || action.autogrow){
            $canvas.addClass("-editor-fit");
        }

        if (mh!="auto"){
            $canvas.find(".ql-editor").css({minHeight: mh});
            $canvas.data("mh", mh);

            if (action.autogrow){
                $canvas.data("autogrow", 1);
            }
        }

        /*
        $canvas.screencopy(Base.domain("api")+"/ajax/api/file/upload", function(code, $_this){
            if (code.fid && code.image){
                var $q=$_this.data("editor");
                var s=$q.getSelection();
                var last_index=0;
                if (s){
                    last_index=s.index;
                }

                $_this.find('img[src^="data:"]').remove();
                if (code.image.substring(0, 4) == "http"){
                    $q.insertEmbed(last_index, 'image', code.image);
                }

                $(q.root).closest("form").trigger("change_base");
            }
        },{});
        */

        q.on("text-change", function(delta, oldDelta, source){
            var $qc=$(q.root).clone();

            var txt=(' '+$qc[0].innerHTML).slice(1);
            $qc.remove();

            $(selector).val(txt);

            if (mh!="auto"){
                quill_setHeight($canvas, q);
            }

            if (!q.__initialized){
                q.__initialized = 1;
            }else{
                $(q.root).closest("form").trigger("change_base");
            }
        });

        if (opts.value){
            UI.editorValue(selector, opts.value);

            if (mh!="auto"){
                quill_setHeight($canvas, q);
            }
        }

        $(q.root).on("focus", function(){
            $canvas.parent().addClass("-x-focus");

            $(".-x-focus").each(function(){
                if ($(this).attr("id") != $canvas.parent().attr("id")){
                    $(this).removeClass("-x-focus");
                }
            });
        });

        // Quill editor
    }

	this.previewImage = function(url){
		function resizeImgBox(ref){
			var h = $(ref).data("h");
			var w = $(ref).data("w");
			var mh = $("#image-dialog-previewer .image-wrap").height();

			if (!h || !mh){
				return;
			}

			if (h > mh){
				$(ref).css("height", mh).css("width", w * mh / h);
			}

			$(ref).dblclick(function(){
				var h = $(this).data("h");
				var w = $(this).data("w");
				var mh = $("#image-dialog-previewer .image-wrap").height();
				var s = $(this).data("s");

				if (s == 0){
					s = 1;
				} else{
					s = 0;
				}

				$(this).data("s", s);

				if (s == 1){
					$(ref).css({width: w, height: h});
				} else{
					$(ref).css("height", mh).css("width", w * mh / h);
				}
			});
		};


		$("#image-dialog-previewer").remove();

		$("<div id='image-dialog-previewer'></div>").appendTo(document.body);
		$("#image-dialog-previewer").html("" +
			"<div class='core-image-wrap'><div class='core-img'><img src='" + url + "'/></div></div>" +
			"<div class='core-image-actions'>" +
			"	<div class='core-action core-image-close'><span class='-icon-svg'>"+SVG.close+"</span></div>" +
			"	<a class='core-action core-url' href='" + url + "' target='_blank'><span class='-icon-svg'>"+SVG.share+"</span></a>" +
			"</div>");

		$("#image-dialog-previewer .core-image-close").click(function(){
			$("#image-dialog-previewer").remove();
		});

		$("#image-dialog-previewer .core-img img").load(function(){
			var h = $(this).height();
			var w = $(this).width();

			$(this).data("h", h);
			$(this).data("w", w);
			$(this).data("s", 0);

			resizeImgBox(this);
		});
	};

	function quill_imageUpload(callback){
		var html = " " +Render.render('form_input', {type: "file" , _name: "file" , label:__('Select image')}, '')+ "";

		Form.basic({
			id: "js-quill-imgupload",
			html: html,
			title: __('Upload an image'),
			action: Client.link_module,
			data: {_a: 'upload'},
			success: function(code) {
				if (!code.good()){
					return AP.alertError(code.message);
				}

				Form.hide('js-quill-imgupload');
				callback(code.image);
			}
		});

		return;
	};

	this.editorValue = function(selector, value){
		var $edx=$(selector).parent().find(".quill-wrapper");
		var content=value.replace(/\&amp;/g,'&').replace(/&#9290;/g, '&#92;');
		var q=$edx.data("editor");

		q.root.innerHTML = content;

		$(selector).val(content);
		$(selector).parent().find(".quill-wrapper pre").addClass("ql-syntax");

		return;
		$(selector).trumbowyg('html', value);
	};

	this.parse = function(content){
		return content.replace(/\{\{\@[a-zA-Z0-9\_]+\}\}/g, function(match){
			var key = match.substr(3, match.length - 5);
			if (key == "all"){
				return "<em class='url pointer inline-tag' title='Tag @all'>all</em>";
			}

			var u=People.get(key);
			if (u && parseInt(u.uid)){
				return "<em class='url pointer username inline-tag' data-username='"+(u.username)+"'>"+(u.name)+"</em>";
			}

			return "<em class='url pointer username inline-tag'>" + key + "</em>";
		});
	};

	function quill_setHeight($canvas, q){
		if ($canvas.hasClass("-editor-fit")){
			var rh=$canvas.find(".ql-editor").height();
			$canvas.height(rh);
			return;
		}

		var mh=$canvas.data("mh");
		if (!mh){
			mh=200;
		}

		var ih=0;
		$canvas.find(".ql-editor").first().children().each(function(){
			ih+=$(this).height();
		});

		if (ih + 50 < $canvas.height() && ih > mh){
			$canvas.css({height: ih+50});
		}

		var sh=$canvas.find(".ql-editor")[0].scrollHeight;
		var oh=$canvas.find(".ql-editor")[0].offsetHeight;


		if ((sh>oh+1) && !$canvas.hasClass("js-extended")){
			$canvas.css({height: sh+1});
		}

		if ((sh>mh*3+100 || sh>mh+400) && !$canvas.hasClass("js-extended")){
			$canvas.css({height: sh+5}).addClass("js-extended");
		}
	};
};


function getMainColor(){
	if (!Client.viewer || !Client.viewer.color){
		return "#000";
	}
	
	var c=parseInt(Client.viewer.color);
	if (c==0){
		c=1;
	}
	var list=["#267cde", "#7c32a1", "#0bba88", "#4CAF50", "#473db8", "#dbaa07", "#FF6F22", "#CF5555", "#ee5997"];
	return list[c-1];
	
}

UI.color=new function __UIColor(){
	var colors=["#EB6450","#F7CF2D","#CEED5F","#A5E33B","#49E33B"];
	var alts=[getMainColor(),"#2a91d6", "#00BCD4", "#26A69A", "#4CAF50", "#5969c5", "#FFC107", "#FF6F22", "#CF5555", "#ee59ba"];
	
	this.regs={};
	
	this.main=getMainColor();
	
	this.get=function(id){
		id = $.trim(id);
		
		if (id=="success"){
			return "#14cc3f";
		}
		
		if (id=="error"){
			return "#c34343";
		}
		
		if (id=="danger"){
			return "#de5954";
		}
		
		if (id == "main"){
			return this.main;
		}
		
		if (id == "orange" || id=="warning"){
			return "#ED6334";
		}
		
		if (id == "blue" || id=="active"){
			return "#267cde";
		}
		
		if (id == "yellow" || id=="notice"){
			return "#FFD000";
		}
		
		if (id=='gray'){
			return '#999999';
		}
		
		if (AP.data.isString(id) && isHexColor(id)){
			return id;
		}
		
		if (AP.data.isString(id) && AP.word.prefix(id, "rgb")){
			return id;
		}
		
		if (AP.data.isString(id) && AP.word.suffix(id, "-")){
			return Color.adjust(this.get(id.substr(0, id.length-1)), -15, -15);
		}
		
		if (AP.data.isString(id) && AP.word.suffix(id, "+")){
			return Color.adjust(this.get(id.substr(0, id.length-1)), 15, 15);
		}
		
		if (AP.data.isString(id) && AP.word.suffix(id, " less")){
			return Color.adjust(this.get(id.substr(0, id.length-5)), -15, -15);
		}
		
		if (AP.data.isString(id) && AP.word.suffix(id, " more")){
			return Color.adjust(this.get(id.substr(0, id.length-5)), 15, 15);
		}
		
		if (AP.data.isString(id) && AP.word.suffix(id, " inverse")){
			return Color.adjust(this.get(id.substr(0, id.length-8)), -10, -90);
		}
		
		
		if (id=='gray less'){
			return '#bbb';
		}
		
		if (AP.data.isString(id) && this.regs[id]){
			return this.regs[id];
		}
		
		if (AP.data.isString(id) && AP.word.prefix(id, "alt")){
			return alts[parseInt(id.substr(3))];
		}
		
		id=parseInt(id);
		if (id>=4){
			id=4;
		}
		
		return colors[id];
	};
	
	
	this.alt = function(id){
		id=parseInt(id);
		if (id>=9){
			id=(id % 9)+1;
		}
		
		return alts[id];
	}
	
	this.fromText = function(text){
		return this.alt(UI.str2int(text));
	};
	
	this.register=function(key, val){
		this.regs[key]=val;
	};
	
	this.getRandom=function(){
		return this.get(AP.data.randomInteger(0,5));
	};
	
	this.rgba=function(hexcolor, a){
		if (hexcolor=="transparent"){
			return "transparent";
		}
		
		var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexcolor);
		var rgb= result ? {
			r: parseInt(result[1], 16),
			g: parseInt(result[2], 16),
			b: parseInt(result[3], 16)
		} : null;
		
		if (rgb){
			return "rgba("+rgb.r+", "+rgb.g+", "+rgb.b+", "+a+")"
		}
		
		return "#000";
	};
	
	
	/**
	 * @desc Check to make sure a color is dark. If light, return false
	 */
	this.isDark = function(hexcolor){
		if (!hexcolor){
			return false;
		}
		
		var hsl=rgbToHsl(hexcolor);
		
		if (hsl.l >= 80){
			return false;
		}
		
		return true;
	};
	
	
	this.darken=function(hexcolor, point){
		return shadeColor(hexcolor, point);
	};
	
	this.adjust=function(hexcolor, x, y){
		if (typeof hexcolor == "undefined" || hexcolor==null){
			return "#ffffff";
		}
		
		if (hexcolor=="transparent"){
			return "transparent";
		}
		
		var hsl=rgbToHsl(hexcolor);
		
		y=-y;
		
		if (x>=0){
			hsl.s=(1-hsl.s/100.0)*x+hsl.s;	
		}else{
			hsl.s=(hsl.s/100.0)*x+hsl.s;
		}
		
		if (y>0){
			hsl.l=(1-hsl.l/100.0)*y+hsl.l;	
		}else{
			hsl.l=(hsl.l/100.0)*y+hsl.l;
		}
		
		return hsl2rgb(hsl);
	};
	
	/**
	 * @desc Mixing two color
	 * @param from Hex color
	 * @param to Hext color
	 * @param scale Number in [0,1]
	 */
	this.mix = function(from, to, scale){
		var from_rgb = getRGB(from);
		var to_rgb = getRGB(to);
		
		var r = from_rgb.r*(1-scale) + to_rgb.r*scale;
		var g = from_rgb.g*(1-scale) + to_rgb.g*scale;
		var b = from_rgb.b*(1-scale) + to_rgb.b*scale;
		
		return this.rgbToHex(r,g,b);
	};
	
	
	this.complete=function(percent){
		var x=parseFloat(percent);
		
		if (x<60){
			return colors[0];
		}
		
		if (x>=60 && x<80){
			return colors[1];
		}
		
		if (x>=80 && x<95){
			return colors[2];
		}
		
		if (x>=95 && x<100){
			return colors[3];
		}
		
		if (x>=100){
			return colors[4];
		}
	};
	
	
	this.incomplete=function(color){
		if (color>100){
			color=100;
		}
		
		return this.complete(100-color);
	};
	
	
	this.progress=function(obj){
		var x=0;
		var etime=parseInt(obj.etime);
		var stime=parseInt(obj.stime);
		var time=AP.time.now();
		
		if (obj.percent){
			var p=parseFloat(obj.percent);
			var target=100;
			var base=0;
			
			if (time> etime){
				x=parseInt(p);
			}else if (time > stime){
				var speed = (p - base)/(time-stime);
				var expected=(target-base)/(etime-stime);
				x=parseInt(speed*100.0/expected); // Expected speed
			}
		}else{
			var complete=parseInt(obj.complete);
			var target=100;
			var base=0;
			
			if (time> etime){
				x=parseInt(complete*100.0/target);
			}else if (time > stime){
				var speed = (complete - base)*1000.0/(time-stime);
				var expected=(target-base)*1000.0/(etime-stime);
				x=parseInt(speed*100.0/expected); // Expected speed
			}	
		}
		
		if (x<60){
			return colors[0];
		}
		
		if (x>=60 && x<80){
			return colors[1];
		}
		
		if (x>=80 && x<95){
			return colors[2];
		}
		
		if (x>=95 && x<100){
			return colors[3];
		}
		
		if (x>=100){
			return colors[4];
		}
		
	};
	
	
	this.speed = function(percent, start, end){
		var x=0;
		var etime=parseInt(end);
		var stime=parseInt(start);
		var time=AP.time.now();
		
		var p=parseFloat(percent);
		var target=100;
		var base=0;
		
		if (time> etime){
			x=parseInt(p);
		}else if (time > stime){
			var speed = (p - base)/(time-stime);
			var expected=(target-base)/(etime-stime);
			x=parseInt(speed*100.0/expected); // Expected speed
		}
		
		return x;
	};
	
	
	this.percent=function(p){
		return this.complete(p);
	};
	
	
	this.picker=function(selector){
		$(selector).each(function(){
			if ($(this).hasClass("__jscolorpicker")){
				return;
			}
			
			$(this).addClass("__jscolorpicker");
			$(this)[0].autocomplete="off";
			
			$(this).on('click', function () {
				var obj = $(this)[0];
				if (!obj.hasPicker) {
					var picker = new jscolor(obj, {});  //
					obj.hasPicker = true;
					picker.show();
				}
			}); 
		});   
	};


	this.rgbToHex = function(r, g, b) {
		return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
	};
	
	
	/**
	 * @desc Getting the palletes
	 */
	this.pallete = function(){
		var c1 = ["#2a91d6", "#00BCD4", "#26A69A", "#4CAF50", "#5969c5", "#FFC107", "#FF6F22", "#CF5555", "#ee59ba"];
		var c2 = ARR.clone(c1);
		
		var p = [];
		
		for (var i=3; i>0; i--){
			var c = ARR.select(c1, function(e){
				return Color.adjust(e, 20*i, 20*i);
			});
			
			p.push(ARR.clone(c));
		}
		
		p.push(ARR.clone(c1));
		
		for (var i=1; i<5; i++){
			var c = ARR.select(c2, function(e){
				return Color.adjust(e, -10*i, -19*i);
			});
			
			p.push(ARR.clone(c));
		}
		
		return p;
	};
	
	
	function shadeColor(hex, lum){
		// validate hex string
		hex = String(hex).replace(/[^0-9a-f]/gi, '');
		if (hex.length < 6) {
			hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
		}
		lum = lum || 0;

		// convert to decimal and change luminosity
		var rgb = "#", c, i;
		for (i = 0; i < 3; i++) {
			c = parseInt(hex.substr(i*2,2), 16);
			c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
			rgb += ("00"+c).substr(c.length);
		}

		return rgb;
	};
	
	
	function rgbToHsl(rgb){
		var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
		var hex = rgb.replace(shorthandRegex, function(m, r, g, b) {
			return r + r + g + g + b + b;
		});
		
		var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
		
		var color= result ? {
			r: parseInt(result[1], 16),
			g: parseInt(result[2], 16),
			b: parseInt(result[3], 16)
		} : null;
		
		var r=color.r/255.0;
		var g=color.g/255.0;
		var b=color.b/255.0;
		
		
		var max = Math.max(r, g, b), min = Math.min(r, g, b);
		var h, s, l = (max + min) / 2;

		if(max == min){
			h = s = 0; // achromatic
		}else{
			var d = max - min;
			s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
			switch(max){
				case r: h = (g - b) / d + (g < b ? 6 : 0); break;
				case g: h = (b - r) / d + 2; break;
				case b: h = (r - g) / d + 4; break;
			}
			h /= 6;
		}

		return {h: Math.floor(h * 360), s: Math.floor(s * 100), l: Math.floor(l * 100)};
	};
	
	
	function hsl2rgb(hsl){
		var r, g, b;
		
		var h=hsl.h/360.0;
		var s=hsl.s/100.0;
		var l=hsl.l/100.0;
		

		if (s == 0) {
			r = g = b = l; // achromatic
		} else {
			var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
			var p = 2 * l - q;

			r = hue2rgb(p, q, h + 1/3);
			g = hue2rgb(p, q, h);
			b = hue2rgb(p, q, h - 1/3);
		}

		return "#" + componentToHex(r*255) + componentToHex(g*255) + componentToHex(b*255);
	};
	
	
	function hue2rgb(p, q, t) {
		if (t < 0) t += 1;
		if (t > 1) t -= 1;
		if (t < 1/6) return p + (q - p) * 6 * t;
		if (t < 1/2) return q;
		if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
		return p;
	};
	
	function componentToHex(c) {
		c=parseInt(c);
		var hex = c.toString(16);
		return hex.length == 1 ? "0" + hex : hex;
	};
	
	
	function getRGB(color_code){
		
		var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
		var hex = color_code.replace(shorthandRegex, function(m, r, g, b) {
			return r + r + g + g + b + b;
		});
		
		var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
		
		var rgb= result ? {
			r: parseInt(result[1], 16),
			g: parseInt(result[2], 16),
			b: parseInt(result[3], 16)
		} : null;

		return rgb;
	}
	
	
	/**
	 * @desc Check if a color is hex
	 */
	function isHexColor(color){
		return /^#[0-9A-F]{6}$/i.test(color) || /^#[0-9A-F]{3}$/i.test(color);
	};
};

var Color=UI.color;


UI.liveCountdown=function(selector_string, show_full, format){
	function getFormatedString(format, d, h, m, s){
		return format.replace("%d", d).replace("%h", h).replace("%m", m).replace("%s", s);
	};
	
	AP.rtimeout(function(){
		var time=AP.time.now();
		$(selector_string).each(function(){
			var $item=$(this);
			var is_smart=$item.data("smart");
			var timer=parseInt($item.data('timer'));
			var ended=$item.data("ended");
			if (!ended){
				ended="00:00:00";
			}
			
			var rem=timer-time;
			
			if (rem<0){
				$item.html(ended).addClass('core-red').addClass("-ended");
			}else{
				var s=rem%60;
				var m=((rem-s)/60)%60;
				var h=Math.floor(rem/3600);
				var d=Math.floor(h/24);
				h=h%24;
				
				if (is_smart){
					if (d==0 || d==1){
						if (h==0 && d==0){
							$item.html("00:"+AP.data.zeroPrefix(m)+":"+AP.data.zeroPrefix(s));
							if (!$item.hasClass("core-red")){
								$item.addClass("core-red").addClass("anim-showhide-inf");
							}
						}else{
							h=h+d*24;
							$item.html(AP.data.zeroPrefix(h)+":"+AP.data.zeroPrefix(m)+":"+AP.data.zeroPrefix(s));
						}
					}else{
						$item.html(AP.time.time("%M %d", timer));
					}
				}else{
					if (d==0){
						if (h==0){
							$item.html("00:"+AP.data.zeroPrefix(m)+":"+AP.data.zeroPrefix(s));
							if (!$item.hasClass("core-red")){
								$item.addClass("core-red").addClass("anim-showhide-inf");
							}
						}else{
							$item.html(AP.data.zeroPrefix(h)+":"+AP.data.zeroPrefix(m)+":"+AP.data.zeroPrefix(s));
						}
					}else{
						if (show_full){
							if (format){
								$item.html(getFormatedString(format, AP.data.zeroPrefix(d), AP.data.zeroPrefix(h), AP.data.zeroPrefix(m), AP.data.zeroPrefix(s)));
							}else{
								$item.html(AP.data.zeroPrefix(d)+"d "+AP.data.zeroPrefix(h)+"h"+" "+AP.data.zeroPrefix(m)+"m "+AP.data.zeroPrefix(s)+"s");	
							}
						}else{
							$item.html(AP.data.zeroPrefix(d)+"d "+AP.data.zeroPrefix(h)+"h");	
						}
					}
				}
			}
		});
	},1000);
};


UI.pageCountdown=function(selector_string, show_full){
	return UI.liveCountdown(selector_string, show_full);
};


function ActionManager(opts){
	if (!opts){
		opts={};
	}
	this.opts=$.extend({icon: true}, opts);
	this.actions=[];

	this.add=function(action, extra){
		if (extra && AP.data.isString(action)){
			return this.add({label: action, url: extra});
		}

		if (AP.data.isObject(action)){
			if (action instanceof ActionManager){
				this.add("---");
				for (var i=0; i<action.actions.length; i++){
					this.add(action.actions[i]);
				}

				return this;
			}

			if ('acl' in action && !action.acl){
				return this;
			}
		}

		if (AP.data.isObject(action) && 'am' in action){
			action.type = 'am';
		}

		var last = null;
		if (this.actions.length){
			last = this.actions[this.actions.length-1];
		}

		if (!last || last=="sep" || last=="---"){
			if (action=="sep" || action=="---"){
				return this;
			}
		}


		this.actions.push(action);

		return this;
	};

	this.exclude = function(action){
		this.actions = ARR.filter(this.actions, function(e){
			if (!e.url || e.url.indexOf(action)!=-1){
				return false;
			}

			return true;
		});

		return this;
	};

	this.inline=function(){
		return AP.render(this.actions, function(action){
			if (action=="sep" || action=="---"){
				return "<div class='-item-sep'></div>";
			}

			if (action.type && action.type == 'am' && action.am){
				var align = 'left';
				if ('align' in action){
					align = action.align;
				}else if ('align' in action.am.opts){
					align = action.am.opts.align;
				}

				return "<div class='-item -submenu -"+(align)+"'> "+(action.label)+" <div class='submenu'> "+(action.am.inline())+" </div> </div>";
			}

			var ec="";
			if (action.style){
				ec=" "+action.style;
			}

			var blank = '';
			if (action.blank || action.target=='blank'){
				blank=" data-blank='1' ";
			}

			var extra_data='';
			if (action.data){
				for (var key in action.data){
					if (AP.data.isString(action.data[key]) || AP.data.isInt(action.data[key])){
						extra_data+=" data-"+(key)+"='"+(action.data[key])+"'";
					}
				}
			}

			var icon = '';
			if (action.icon){
				icon = "  " +Render.render('icon', {_class: "-cmenu-icon" , icon:action.icon}, '')+ '';
				ec+=' -with-icon';
			}

			if (action.embed) {
				return "<div class='-item core-url "+(ec)+"' "+(blank)+" "+(extra_data)+" title='"+(action.label)+"' "+(action.url)+">"+(icon)+""+(action.label)+"</div>";
			}

			return "<div class='-item core-url "+(ec)+" core-ap-xdot' data-url='"+(action.url)+"' "+(blank)+" "+(extra_data)+" title='"+(action.label)+"'>"+(icon)+""+(action.label)+"</div>";
		});
	};

	this.context=function(){
		return this.actions;
	};

	this.length=function(){
		return this.actions.length;
	};

	this.getURL = function(key){
		for (var i=0; i<this.actions.length; i++){
			var action=this.actions[i];
			if (action.url && action.url.indexOf(key)!=-1){
				return action.url;
			}
		}

		return "";
	};

	this.getAction = function(key){
		for (var i=0; i<this.actions.length; i++){
			var action=this.actions[i];
			if (action.url && action.url.indexOf(key)!=-1){
				return "<div class='-item core-url' data-url='"+(action.url)+"'>"+(action.label)+"</div>";
			}
		}

		return "";
	};


	this.release = function(){
		return this.actions;
	};


	/**
	 * @desc Show in dialog
	 */
	this.dialog = function(opts){
		var actions = AP.select(ARR.deepClone(this.actions), function(e){
			if (e == "---"){
				return null;
			}

			e.icon = $.trim("  " +Render.render('icon', {icon:e.icon}, '')+ '');
			return e;
		});

		AP.actionMenu(actions);
	};

	this.text=this.inline;
};


ActionManager.init = function(){
	return new ActionManager();
};



UI.file=new function __UIFile(){
    this.ext=function(file){
		var ext="unknown";
		
		if (!file){
			return ext;
		}
		
		data=file.split(".");
		
		if (!data.length){
			return ext;
		}
		
		return data[data.length-1].toLowerCase();
	}

	this.icon=function(file){
		var ext="text2";
		
		if (!file){
			return ext;
		}
		
		data=file.split(".");
		var fext="";
		
		if (!data.length){
			return ext;
		}
		fext=data[data.length-1]; 
		fext=fext.toLowerCase();
		if (fext=="jpeg"){
			fext="jpg";
		}

		if (fext == "xls" || fext == "xlsx" || fext == "gsheet" || fext == "xlsm") {
			ext = "excel";
		} else if (fext == "gif" || fext == "png" || fext == "jpg" || fext == "ai" || fext == "svg" || fext == "psd" || fext == "jpeg") {
			ext = 'image';
		} else if (fext == "doc" || fext == "docx" || fext == "gdoc") {
			ext = "word";
		} else if (fext == "ppt" || fext == "pptx" || fext == "gslides") {
			ext = "ppt";
		} else if (fext == "pdf") {
			ext = "pdf";
		} else if (fext == "zip") {
			ext = "zip";
		}
		
		return ext;
	};

	this.kb=function(size){
		var kb=Math.floor(size/1024);
		if (kb==0){
			return size+" B";
		}
		
		if (kb<1000){
			return kb+" KB";
		}
		
		return (kb/1024).toFixed(2)+" MB";
	};
}




var Form = new function __Form(){
    this.create= function(id, options){
		return new UIForm(id, options);
	};

	this.pop = function(options) {
		return new UIPopForm(options);
	}

	this.hide=function(ref){
		if (AP.data.isString(ref) && ref.charAt(0)!="#"){
			ref="#"+ref;
		}
		var dx=$(ref).closest(".__dialogwrapper").find(".__apdialog");
		if (dx && dx.length){
			AP.dialog("#"+dx.attr('id')).hide();
		}
	};

	this.submit=function(ref, callback, data, need_loading = true){
		if (!data){
			data={};
		}

		if (ref.charAt(0)!="#"){
			ref="#"+ref;
		}
		if (need_loading) {
            UI.ajaxShow();
        }
		UI.ajaxShow();
		AP.submit(ref, function(code){
            if (need_loading) {
                UI.ajaxHide();
            }
			callback(code);
		}, data);
	};
}

function UIForm(id, options){
	if (typeof id=='undefined'){
		id=null;
	}

	if (typeof options=='undefined'){
		options={};
	}


	if (id && id.charAt(0)=='#'){
		id=id.substr(1);
	}

	this.__id=id;
	this.__options=$.extend({},{action: '', method: 'POST'}, options);
	this.__hiddens = {};
	this.__buttons = [
		{
			label: __('Cancel'),
			action: function(ref){
				Form.basic.hide(ref);
                $(AP.dialog("#" + id).w() + "-dx").remove();
			},
			id: 'form-button-cancel',
			style: 'core-semantic-ui core-semantic-button core-form-button'
		},
		{
			label: __('Save'),
			action: function(ref){
				Form.basic.submit(function(code){
					if (!code.good()){
						return AP.alertError(code.message);
					}
					if (!options.success || !AP.data.isFunction(options.success)){
						UI.flash(__('Update successfully'));
						AP.xRefresh();
					}else if (AP.data.isFunction(options.success)){
						options.success(code);
						Form.basic.hide(ref);
					}
				}, ref);
			},
			id: 'form-button-save',
			style: 'core-semantic-ui core-semantic-button core-semantic-positive core-form-button',
			validator: options.validator
		}
	];

    if (options.disable_save) {
        this.__buttons.pop();
    }
    if (options.override_buttons) {
        this.__buttons = [];
    }

	this.buttons = function(buttons) {
	    var buttons_tmp = [];
        for (var i=0; i<buttons.length; i++){
            buttons_tmp.push(buttons[i]);
        };
        if (this.__buttons.length == 2) {
            this.__buttons = AP.array.merge([this.__buttons[0]], buttons_tmp, [this.__buttons[1]]);
        } else if(this.__buttons.length == 0) {
            this.__buttons = buttons_tmp;
        }else {
            this.__buttons = AP.array.merge([this.__buttons[0]], buttons_tmp);
        }
        return this;
    }

	this.find=function(name){
		return $("*[name='"+name+"']", "#"+this.__id);
	};


	this.findRow=function(name){
		return $("*[name='"+name+"']", "#"+this.__id).closest(".row");
	};


	this.matchRow=function(selector){
		return $("*[name^="+name+"]", "#"+this.__id).closest(".row");
	};


	this.elem=function(name){
		return $(name, "#"+this.__id);
	};

	this.selector=function(name){
		return this.elem(name);
	};

	this.focus=function(name){
		$("*[name="+name+"]", "#"+this.__id).focus();
	};

	this.balance=function(){
		AP.dialog(this.id).balance();
	};

	this.renderButtons = function() {
		var html="";
		for (var i=0; i<this.__buttons.length; i++){
			html+=this.renderButton(this.__buttons[i]);
		}
		return html;
	}

	this.getButton = function(index) {
		return this.__buttons[index];
	}

	this.renderButton = function(button) {
		var id='';
		if ('id' in button){
			id=" id='"+(button.id)+"'";
		}
		return "<div class='core-form-button "+(button.style)+"'"+(id)+">"+(button.label)+"</div>";
	}

	this.hiddens=function(hiddens){
		for (var key in hiddens){
			this.__hiddens[key]=hiddens[key];
		};

		return this;
	};

	this.htmlHidden=function(){
		var hidden="";
		for (key in this.__hiddens){
			hidden +="<input type='hidden' name='"+key+"' value='"+this.__hiddens[key]+"'/>";
		}

		return "<div style='display:none'>"+(hidden)+"</div>";
	}
};

function UIPopForm(options){
	options=$.extend({}, {id: 'popform','width': 800, label: 'Form dialog', closable: true}, options);
	this.options=options;
	this.formobj=null;
	this.html="";
	this.setForm=function(formObj){
		this.html="<div class='form form-dialog'><form method='post' id='"+formObj.__id+"' action='"+formObj.__options.action+"'>"+ formObj.htmlHidden()  + (formObj.__options.html || '')+"</form></div>";
		this.formObj=formObj;

		return this;
	};

	this.show=function(){
		this.options.engine=FormDialogEngine;
		AP.dialog(this.options.id)
		.engine(FormDialogEngine)
        .size(this.options.size)
		.title(this.options.label)
		.content(this.html)
		.closable(this.options.closable)
		.show()
		.balance();

		if (this.formObj.__options.render) {
			this.formObj.__options.render.apply(this.formObj);
		}

		$(document).on("keypress", "#"+this.formObj.__id+" input", function(event){
			if (event.keyCode == 13) {
		        event.preventDefault();
		    }
		});

		this.placeButtons(this.formObj);
		return this;
	};

	this.closable=function(opt){
		AP.dialog(this.options.id).closable(opt)

		return this;
	};

	this.focus=function(name){
		this.formObj.focus(name);
		return this;
	};

	this.addClass=function(name){
		$("#"+this.options.id).closest(".__dialog").addClass(name);
		return this;
	};

	this.placeButtons = function(form) {
        $("#"+this.options.id).closest(".__dialogwrapper").find(".form-buttons").remove();
		var html=form.renderButtons();
		var buttons_html = "<div class='core-semantic-actions form-buttons'>"+(html)+"</div>";
		$(buttons_html).insertAfter($("#"+this.options.id).closest(".__dialogcontent"));
		$("#"+this.options.id).closest(".__dialogwrapper").find(".form-buttons .core-form-button").each(function(index){
			var btn = form.getButton(index);
			$(this).data("action", btn.action);
			$(this).click(function(){
				if (AP.data.isFunction(btn.validator)) {
					var result = btn.validator.apply();
					if (result.code == 0) {
						AP.alertError(result.message);
						return;
					}
				}
				var action=$(this).data("action");
				action(this);
			});
		});
	}
};

function better_int_enter($input){
	$input.on("input", function(){
		var val=$(this).val();
		if (val.length && val.charAt(val.length-1)=="."){
			return;
		}

		var org_length = val.length;
		val=val.replace(/,/g,"");


		var caret = plugin_get_caret_position(this);

		if (AP.data.isNumber(val)){
			val=AP.data.numberFormat(val);
			var cur_length = val.length;

			$input.val(val);
			$input.setCursorPosition(caret + cur_length - org_length);
		}
	});

	var val=$input.val();
	if (!val){
		return;
	}
	if (val.length && val.charAt(val.length-1)=="."){
		return;
	}

	val=val.replace(/,/g,"");

	if (AP.data.isNumber(val)){
		val=AP.data.numberFormat(val);
		$input.val(val);
	}
};


Form.basic = function(opts){
	var focus = 'name';
    opts=$.extend({}, {width: 450, layout:"flat", protection: true, size: "tiny"}, opts);
    if (!opts.id){
		opts.id = 'form-basic-fx';
	}

	var hiddens = {};
    if (opts.hiddens){
        hiddens=opts.hiddens;
    }

	if (opts.data){
		hiddens=opts.data;
	}
	var form = Form.create(opts.id, opts);
	form.hiddens(hiddens);
    if (opts.buttons && AP.data.isArray(opts.buttons)){
        form.buttons(opts.buttons);
    }
	Form.pop({id: opts.id+"-dx", width: opts.width, label: opts.title, size: opts.size}).setForm(form).show().focus(focus);
}

Form.basic.hide=function(id){
	if (!id){
		id='form-basic-fx';
	}
	return Form.hide(id);
};

Form.basic.submit=function(callback, ref){
	var form_id = '#form-basic-fx';

	if (ref){
		form_id = "#"+$(ref).closest("#__apdialog_form-basic-fx-dx").find("form").attr("id");
		if (!form_id){
			form_id = '#form-basic-fx';
		}
	}
	return Form.submit(form_id, callback, {_r: 1});
};



Form.on = function(key, render, update){
	Form.customElem.defs[key] = {
		render: render,
		update: update
	}
};


Form.ui = {};


Form.improveSelect=function(selector, opts){
	if (!$(selector).length){
		return;
	}
	$(selector).hide().attr('is_fake', true);
	var placeholder = opts.placeholder;
	if (!placeholder){
		placeholder='-- '+__('Please select')+' --';
	}

	var items=[];
	var emp=null;
	var cv=$(selector).val();

	opts=$.extend({search: true, with_empty: 1}, opts);

	if (opts.multi || opts.multiple || opts.improve){
        cv=opts.value;
	}
	$(selector).find("optgroup").each(function(){
		items.push({label: $(this).attr("label"), type: "optgroup"});

		$(this).find("option").each(function(){
			if (AP.data.equal(this.value, opts.empty)){
				emp="<em>"+$(this).text()+"</em>";
			}else{
				items.push({label: $(this).text(), value: this.value, selected: this.selected?1:0});
			}
		});
	});

	if (!items.length){
		$(selector).find("option").each(function(){
			if (AP.data.equal(this.value, opts.empty)){
				emp="<em>"+$(this).text()+"</em>";
			}else{
				items.push({label: $(this).text(), value: this.value, selected: this.selected?1:0});
			}
		});
	}

	if (opts.options && !items.lenth){
		items=AP.select(opts.options, function(e){
			return {label: e.content, value: e.value};
		});

		if (opts.empty){
			items.unshift({label:(opts.empty === true)?"-- "+__('Please select')+" --":opts.empty, value: ""});
		}

		$(selector).html(AP.render(items, function(e){
			return "<option value='"+(e.value)+"'>"+(e.label)+"</option>";
		}));
	}else{
		if ('value' in opts){
			$(selector).val(opts.value);
		}
		cv=$(selector).val();
	}
	if (placeholder=="-- "+__('Please select')+" --" && emp){
		placeholder=emp;
	}


	var $p=$(selector).parent();
	var items_html=AP.render(items, function(e){
		if (e.type && e.type=="optgroup"){
			return "<div class='core-is-label'>"+(e.label)+"</div>";
		}

		var label=e.label;
		if (opts.render){
			var fn=opts.render;
			label=fn(e.value, label);
		}
		return "<div class='core-is-item' onclick='Form.improveSelectHelper.pickup(this);' data-value='"+(e.value)+"'>"+(label)+"</div>";
	});

	var name=AP.uuid();
	var search="<div class='core-is-search'><input type='text' is_fake='true' name='"+(name)+"' placeholder='"+(__('Quick filter'))+"'/></div>";
	if (!opts.search){
		search='';
	}

	var _close = '';
	if (opts.multiple || opts.multi){
		_close = "<div class='core-is-close'>"+(__('Done'))+"</div>";
	}

	var html="<div class='core-improve-select core-unselectable'> <div class='core-is-display core-url' data-url=':active:parent' data-placeholder='"+(placeholder)+"'><div class='core-ap-xdot'>"+(placeholder)+"</div></div> <div class='core-is-box'> "+(search)+" <div class='core-is-scroll core-scroll-y core-url'> <div class='core-is-items'>"+(items_html)+"</div> </div> "+(_close)+" </div> </div>";

	$p.append(html).addClass("core-js-improved-select");
	$p.find(".core-is-scroll").on("click", function(){
		if ($(this).closest(".core-js-improved-select").data("multiple")){
			$(this).parent().parent().addClass("core-active");
		}else{
			$(this).parent().parent().removeClass("core-active");
		}
	});


	var tname=$p.find("select").attr("name");

	if (opts.multiple || opts.multi){
		$p.find("select").hide().attr("name", AP.uuid()).after("<input type='hidden' class='core-js-select' name='"+(tname)+"'/>");
		$p.data("multiple", 1);
	}

	$p.find("input[name="+name+"]").on("input keypress", function(){
		var v=$(this).val();
		if (!v || !v.length){
			$p.find(".core-is-scroll").find(".core-is-item").show();
			return;
		}

		$p.find(".core-is-scroll").find(".core-is-item").each(function(){
			var txt=$(this).text();
			if (AP.word.fulltextMatch(txt, v)){
				$(this).show();
			}else{
				$(this).hide();
			}
		});
	});

	if (opts.multi || opts.multiple){
		if (opts.value && opts.value.length){
			$p.find(".core-is-item").each(function(){
				if (AP.array.contain(cv, $(this).data("value"))){
					$(this).click();
					$p.find(".core-improve-select").removeClass("core-active");
				}
			});
		}

		$p.find(".core-is-close").click(function(){
			$p.find(".core-improve-select").removeClass("core-active");
            Form.improveSelectHelper.updateValue($p);
		});
        Form.improveSelectHelper.updateValue($p);
		return;
	}


	// Set current value
	if (!cv && "value" in opts){
		cv=opts.value;
	}

	$p.find(".core-is-item").each(function(){
		if (AP.data.equal(cv, $(this).data("value"))){
			$(this).click();
			$p.find(".core-improve-select").removeClass("core-active");
		}
	});
    Form.improveSelectHelper.updateValue($p);
};



Form.improveSelectHelper=new function __FormIMPHelper(){
	this.pickup=function(ref){
		var $p=$(ref).closest(".core-js-improved-select");

		if ($p.data("multiple")){
			return this.pickupMulti(ref);
		}


		var label=$(ref).text();

		$(ref).siblings().removeClass("core-active");
		$(ref).toggleClass("core-active");

		var value=$(ref).data("value");
		if (!$(ref).hasClass("core-active")){
			value="";
			$p.find(".core-is-display div").html("---");
		}else{
			$p.find(".core-is-display div").html(safe(label));
		}

		$p.find("select").val(value).trigger("change");

	};


	this.pickupMulti=function(ref){
		$(ref).toggleClass("core-active");
		var $p=$(ref).closest(".core-js-improved-select");
		var value=[];
		var label=[];
		var placeholder_default = $p.find(".core-is-display").data('placeholder');

		$p.find(".core-is-item.core-active").each(function(){
			var lab=safe($(this).text());
			label.push("<span class='core-is-itag'>"+(lab)+"</span>");
			value.push($(this).data("value"));
		});

		value=AP.array.unique(value, function(e, f) {
			return e === f;
		});

		$p.find(".core-is-display div").html(label.join(" ")+"&nbsp;").removeClass("core-ap-xdot");
		if (value.length == 0) {
            $p.find(".core-is-display div").html(""+(placeholder_default)+"").addClass("core-ap-xdot");
        }
	};

	this.updateValue = function(wrapper) {
        var value=[];
        var $p= wrapper;
        $p.find(".core-is-item.core-active").each(function(){
            value.push($(this).data("value"));
        });
        value=AP.array.unique(value, function(e, f) {
            return e === f;
        });
        $p.find(".core-js-select").val(value.join(", ")).trigger("change");
    }
};






AP.chartFX=new function __APChartFX(){
	this.exportData=function(data, options){
		var r=[];
		for (var i=0; i<data.length; i++){
			r.push(parseInt(data[i].value));
		}
		return r;
	};
	
	this.exportLabels=function(data, options){
		var r=[];
		for (var i=0; i<data.length; i++){
			if (data[i].name && !data[i].label){
				data[i].label=data[i].name;
			}
			
			r.push(data[i].label);
		}
		return r;
	};
	
	this.exportColors=function(data, options){
		var r=[];
		for (var i=0; i<data.length; i++){
			var c=data[i].color;
			if (!c){
				c=AP.color(i);
			}
			
			if (AP.data.isInt(c)){
				c=AP.color(c);
			}
			r.push(c);
		}
		return r;
	};
	
	
	this.exportHC=function(data, options, color){
		var r=[];
		for (var i=0; i<data.length; i++){
			var c=data[i].color;
			
			if (!c){
				c=AP.color(i);
			}
			
			if (data[i].name && !data[i].label){
				data[i].label=data[i].name;
			}
			
			r.push({name: data[i].label, y: parseInt(data[i].value), color: c});
		}
		return r;
	};
	
	
	this.exportFunnel=function(data, options){
		
		var r=[];
		for (var i=0; i<data.length; i++){
			var c=data[i].color;
			
			if (!c){
				c=AP.color(i);
			}
			
			r.push([data[i].label, parseInt(data[i].value)]);
		}
		return r;
	};
};


AP.series=function(opts){
	var r=[];
	for (var i=0; i<opts.labels.length; i++){
		var obj={};
		if (opts.stacked){
			obj={label: opts.labels[i], value: [parseFloat(opts.values[i])]};	
		}else{
			obj={label: opts.labels[i], value: parseFloat(opts.values[i])};
		}
		
		if (opts.colors){
			obj.color=opts.colors[i];
		}
			
		r.push(obj);
	}
	
	return r;
};


AP.color=function(code, alpha){
	var colors=["#6091e0", "#51cc90", "#ed912f", 
        "#6b5cd1", "#ba4cad", "#40b74e",
        "#FFEB3B","#00BCD4","#9C27B0", 
        "#f1c40f", "#009688", "#673AB7",
        "#FF9800","#4CAF50","#3F51B5"];
	
	var codes={
		"best":"#4CAF50",
		"good":"#8BC34A",
		"average":"#CDDC39",
		"bad":"#FF9800",
		"worst": "#FF5722",
		"gray":"#9E9E9E",
		"gray2": "#ccc"
	};
	
	var color="#000";
	
	if (AP.data.isInt(code)){
		var key= code % colors.length;
		color= colors[key];
	}else{
		var c=code.toLowerCase();
		if (code.charAt(0)=="#"){
			color=c;
		}else{
			if (c=="success"){
				c="good";
			}
			
			if (codes[c]){
				color= codes[c];
			}else{
				color= codes["gray2"];	
			}	
		}
	}
	

	if (alpha){
		if (alpha>0 && alpha<1){
			return UI.color.rgba(color, alpha);	
		}else{
			if (alpha>1){
				return UI.color.darken(color, alpha/100);
			}
		}
	}
	
	return color;
};


AP.statusColor=function(status, alpha){
	status=parseInt(status);
	var color="#aaaaaa";
	if (status==0){
		color="#aaaaaa";
	}
	
	if (status==1){
		color= "#f24a37";
	}
	
	if (status==2){
		color= "#f9c134";
	}
	
	if (status==3){
		color= "#bce222";
	}
	
	if (status==4){
		color= "#6de21f";
	}
	
	if (status==5){
		color= "#24d82d";
	}
	

	return AP.color(color, alpha)
};




var CoreHelperNumber = new function __CoreHelperNumber() {
    /**
     * @desc Get int
     */
    this.getInt = function(ref, is_real = false) {
        if (is_real) {
            var input = ref;
        } else {
            var input = ref.val();
        }
        input = input.replace(/,/g, '');
        input = parseInt(input);
        if (!AP.data.isInt(input)){
            return 0;
        }
        return input;
    }

    /**
     * @desc Get float
     */
    this.getFloat = function(ref, is_real = false) {
        if (is_real) {
            var input = ref;
        } else {
            var input = ref.val();
        }
        input = input.replace(/,/g, '');
        input = parseFloat(input);
        if (!AP.data.isNumber(input)){
            return 0;
        }

        return input;
    }
}



Render.helper = new function __RenderHelper(){
	/**
	 * @desc Check if a color is hex
	 */
	 this.isHexColor = function(color){
		return /^#[0-9A-F]{6}$/i.test(color) || /^#[0-9A-F]{3}$/i.test(color);
	};

	this.getFunction = function(str){
		return getFunctionByName(str);
	};

	this.getTextContent = function(obj){
		if (obj.ap_xdot || obj.fit){
			return "<div class='ap-xdot'>"+(obj.content)+"</div>";
		}

		return obj.content;
	};

	this.escape = function(content){
	    if (AP.data.isEmpty(content)) {
	        return content;
        }
		var cx=content.toString().replace(/&amp;/g, '&').replace(/&#8216;/g, "'").replace(/&#9290;/g, "&#92;").replace(/&#39;/g, "`").replace(/⑊/g, "&#92;").replace(/‘/g, "'").replace(/&lsquo;/g, "'").replace(/\{br\}/g,'<br>').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;&nbsp;')
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#39;");
		return cx;
	};

	this.acl = function(acl_key){
		if (typeof acl_key == 'undefined'){
			return true;
		}

		return computeACL(acl_key);
	};

	function computeACL(acl_key){
        if (acl_key === true){
            return true;
        }else if (acl_key === false){
            return false;
        }
        if (acl_key === "1"){
            return true;
        }

        if (acl_key === "0"){
            return false;
        }
        if (AP.data.isInt(acl_key)){
            if (parseInt(acl_key) == 0){
                return false;
            }

            if (parseInt(acl_key) == 1){
                return true;
            }

            return false;
        }
        if (typeof acl_key === "undefined"){
            return false;
        }
        if (acl_key && !AP.data.isNumber(acl_key) && !AP.data.isString(acl_key)){
            return false;
        }

        return true;
    };

	this.getIcon = function(obj, set_color){
		var icon = obj.svg;
		if (icon){
			if (AP.data.isString(icon) && icon.length <= 32){
				icon = SVG[icon];
				return icon;
			}else{
				return icon;
			}
		}

		icon = obj.icon;

		if (!icon){
			return '';
		}

		var ec = [];

		if (set_color || obj.icon_color){
			var cx=obj.icon_color;
			if (!cx && set_color){
				cx=obj.color;
			}

			if (cx){
				var color = this.getColor(cx);

				if (icon == "dot"){
					ec.push("background-color: "+(color)+"");
				}else{
					ec.push("color: "+(color)+"");
				}

			}
		}


		// Special case
		if (icon == 'dot'){
			return "<span class='-idot' style='"+(ec.join(' '))+"'></span>";
		}

		if (icon.length<=32){
			if (AP.word.prefix(icon, 'edge ')){
				return "<span class='-icon-svg -edge-svg' style='"+(ec.join(' '))+"' data-svgicon='"+(icon)+"'>"+(SVG._edge_icons[icon.substr(5)])+"</span>";
			}

			return "<span class='-icon-svg' data-svgicon='"+(icon)+"' style='"+(ec.join(' '))+"'>"+(SVG[icon]||'')+"</span>";
		}

		if (AP.word.prefix(icon, "https://")){
			return "<img class='-img-icon' src='"+(icon)+"'>";
		}

		return icon;

	};

	this.getColor = function(color, df){
		var r = "#aaaaaa";

		if (this.isHexColor(color)){
			if (color.length==4){
				r = color+color.substr(1);
			}else{
				r = color;
			}
		}else{
			if (AP.word.prefix(color, 'rgba(')){
				return color;
			}

			r = Color.get(color);
		}


		if (!r){
			return df;
		}

		return r;
	};

	this.getIconType = function(obj){
		var icon = obj.icon;
		if (!icon){
			return "-icon-none";
		}

		if (AP.data.isString(icon) && icon.length >= 64){
			return '-icon-is-svg';
		}

		return 'core-icon-svg';
	};

	this.getIconByName = function(icon){
		if (AP.data.isString(icon) && icon.length >= 64){
			return icon;
		}

		return SVG[icon];
	};
}




Render.on("text-title", function(){
    if (typeof this.url !== 'undefined') {
        this.addClass("core-url");
    }
	return "<div "+(this.css())+" "+(this.showAllData())+" class='core-text core-text-title "+(this.get('class'))+"' "+(this.showURL())+">"+(Render.helper.getTextContent(this))+"</div>";
});

Render.on("text-info", function(){
    return "<div "+(this.css())+" class='core-text text-info "+(this.get('class'))+"'>"+(Render.helper.getTextContent(this))+"</div>";
});


Render.on("text-upper", function(){
	if (this.color){
		this.css("color", Render.helper.getColor(this.color));
	}

	this.css("text-transform", "uppercase");

	if (this.thick){
		this.addClass("core-thick");
	}

	if (this.bold){
		this.addClass("core-bold");
	}

	return "<span class='core-text-upper "+(this.get('class'))+"' "+(this.css())+">"+(this.content)+" </span>";
});

Render.on("text-index", function(){
	this.addSizingClass();
	return "<div class='core-text-index "+(this.get('class'))+"'>"+(AP.data.zeroPrefix(this.index))+"</div>";
});

Render.on("text-code", function(){
	if (this.fit){
		this.addClass("-fit");
	}

	if (this.inline){
		this.addClass("-inline");
	}

	return "<div class='core-text-code "+(this.get('class'))+"' "+(this.css())+">"+(this.content)+"</div>";
});

Render.on("text-number", function(){
	this.addStandardTextLayout();

	return "<span class='core-text-number "+(this.get('class'))+"' "+(this.css())+">"+(AP.data.numberFormat(this.content||this.value))+"</span>";
});

Render.on("text-explain", function(){
	var exp = explain(this.content, this);

	if (this.left){
		this.css("padding-left", this.left+"px");
	}

	if (!this.label) {
	    return "<span class='core-text-explain inline' "+(this.css())+">"+(exp)+"</span>";
    }

	return "<div class='core-text-explain-wrapper'> <label>"+(this.label)+"</label> <span class='core-text-explain inline' "+(this.css())+">"+(exp)+"</span> </div>";
});

Render.on("text-datetime", function(){
	var ts= this.ts;
	if (this.ts=="" || this.ts==null || typeof(this.ts)=="undefined"){
		ts = this.content;
	}

	this.addStandardTextLayout();

	if (!ts || !parseInt(ts)){
		return "<span class='core-text-datetime'>"+(this.es||'NA')+"</span>";
	}

	if (this.ago){
		return "<span class='core-text-datetime'>"+(AP.time.ago(ts))+"</span>";
	}

	if (this.inline){
		this.addClass("-inline");
	}

	if (this.multiple_lines){
		return "<div class='core-text-datetime'> <div class='core-td-date core-ap-f14'>"+(AP.time.time('%M %d', this.ts))+"</div> <div class='core-td-time core-ap-f12 core-text-a' style='padding-top:3px;'>"+(AP.time.time('%H:%i:%s', ts))+"</div> </div>";
	}

	return "<span class='core-text-datetime' "+(this.css())+">"+(AP.i18n.datetime(ts))+"</span>";
});

Render.on("text-date", function () {
	var ts = this.ts;
	if (this.ts == "" || this.ts == null || typeof (this.ts) == "undefined") {
		ts = this.content;
	}

	this.addStandardTextLayout();

	if (!ts || !parseInt(ts)) {
		return "<span class='core-text-date -es'>"+(this.es||this._default || 'NA')+"</span>";
	}

	return "<span class='core-text-date "+(this.get('class'))+"' "+(this.css())+">"+(AP.i18n.date(ts))+"</span>";
});

Render.on("text-ago", function () {
	var ts = this.ts;
	if (this.ts == "" || this.ts == null || typeof (this.ts) == "undefined") {
		ts = this.content;
	}

	this.addStandardTextLayout();

	if (!ts || !parseInt(ts)) {
		return "<span class='core-text-date'>"+(this.es || 'NA')+"</span>";
	}
	return "<span class='core-text-ago' "+(this.css())+">"+(AP.time.ago(ts))+"</span>";
});

Render.on("text-duration", function(){
	var duration= this.duration;
	if (!duration || !parseInt(duration)){
		return "<span class='core-text-date'>"+(this.es||'NA')+"</span>";
	}

	return "<span class='core-text-duration'>"+(AP.i18n.duration(duration))+"</span>";
});

Render.on(["text-datecount", "text-date-count"], function(){
	var from = parseInt(this._from);
	var to = parseInt(this.to);
	if (to<=from){
		return "<span class='core-text-datecount'>Day 0 of 0</span>";
	}

	var total = Math.ceil((to-from)/(24*3600));

	var time = AP.time.now();
	if (time<from){
		return "<span class='core-text-datecount'>Day 0 of "+(total)+"</span>";
	}else if (time>to){
		return "<span class='core-text-datecount'>Day "+(total)+" of "+(total)+"</span>";
	}else{
		var count = Math.ceil((time-from)/(24*3600))
		return "<span class='core-text-datecount'>Day "+(count)+" of "+(total)+"</span>";
	}
});

Render.on(["text-int", "text-num"], function(){
	var val=this.content;
	if (!val){
		val=this.value;
	}

	if (!val){
		val=0;
	}else{
		val=parseInt(val);
	}

	if (this.with_zero){
		val= AP.data.zeroPrefix(val);
	}

	return "<span>"+(val)+"</span>";
});

Render.on("text-box", function(){
	this.addStatusColor();
	this.addSizingClass();

	if (this.color){
		var c= Render.helper.getColor(this.color);

		if (this.subtle){
			this.css("background-color", Color.rgba(c, 0.1));
			this.css("color", Color.adjust(c, 10, 10));
		}else{
			this.css("background-color", c);
			this.css("color", "#fff");
		}
	}

	if (this.inline){
		this.addClass("-inline");
	}

	if (this.icon){
		this.addClass("-picon");
	}

	return "<div class='core-text-box "+(this.get('class'))+"' "+(this.css())+">"+(Render.helper.getTextContent(this))+"</div>";
});

Render.on("text-status", function(){
	this.addStatusColor();
	this.addSizingClass();

	if (this.inline){
		this.addClass("-inline");
	}

	if (this.color){
        var c= Render.helper.getColor(this.color);

        if (this.subtle){
            this.css("background-color", Color.rgba(c, 0.2));
            this.css("color", this.color);
        }else{
            this.css("background-color", c);
            this.css("color", "#fff");
        }
	}

	if (this.padding){
		this.addClass("-padding");
	}

	if (this.simple) {
        this.addClass("-simple");
    }

	if (this.icon){
		this.addClass("-picon");
	}

	return "<div class='core-text-status "+(this.get('class'))+"' "+(this.css())+">"+(Render.helper.getTextContent(this))+"</div>";
});


Render.on("text-icon", function(){
	if (!this.icon){
		return '';
	}

	this.addStandardTextLayout();
	if (this.url){
		this.addClass('core-url');
	}

	if (this.inline){
		this.addClass("-inline");
	}

	if (this.fullfill) {
		this.addClass('fullfill');
	}

	return "<div "+(this.showAllData())+" class='core-icon-stat inline "+(this.get('class'))+" "+(Render.helper.getIconType(this))+"' "+(this.show('url'))+" "+(this.css())+"> <span class='-bis-icon'>"+(Render.helper.getIcon(this))+"</span> <span class='-bis-content' "+(this.css())+">"+(this.content)+"</span> </div>";
});

Render.on("text-dot", function(){
	var color = Render.helper.getColor(this.color||'#aaaaaa');
	this.addStandardTextLayout();
	if (this.text_fill || this.fill_text){
		this.css("color", color);
	}
    if (this.url){
        this.addClass("core-url");
    }

	return "<div class='core-text-dot "+(this.get('class'))+"' "+(this.show('url'))+" "+(this.showAllData())+" "+(this.css())+"> <span class='-td-inner'> <span class='-dot' style='background-color:"+(color)+"'></span> <span class='-txt core-ap-xdot'>"+(this.content)+"</span> </span> </div>";
});

Render.on("text-editor", function(){
	if (!this.content){
		return "<div class='text-editor -no-content "+(this.get('class'))+"' "+(this.show('id'))+"> " +Render.render('none', {}, ""+(this.es||'')+"")+ "</div>";
	}

	if (this.code_highlight){
		return "  " +Render.render('text_editor_code', {}, ""+(Render.helper.escape(this.content))+"")+ '';
	}

	this.addSizingClass();

	return "<div class='text-editor "+(this.get('class'))+"' "+(this.show('id'))+"> "+(UI.parse(this.content))+" </div>";
}, function(params){
	if (params.linkify || params.linkified){
		$(this).linkify();
	}
});

Render.on("text-editor-code", function(){
	return "<div class='text-editor' "+(this.show('id'))+"> "+(this.content)+" </div>";
}, {
	done: function(params){
		Render.helper.showCode($(this).find("pre"));
	}
});

Render.on("text-daterange", function(){
	var from = parseInt(this._from);
	var to = parseInt(this.to);

	if (AP.time.sameYear(from, to)){

		if (AP.time.sameYear(from, AP.time.now())){
			return "<span class='core-text-daterange'>"+(AP.time.time('%M %d',from))+" - "+(AP.time.time('%M %d',to))+"</span>";
		}

		return "<span class='core-text-daterange'>"+(AP.time.time('%M %d',from))+" - "+(AP.time.time('%M %d %Y',to))+"</span>";
	}

	return "<span class='core-text-daterange'>"+(AP.time.time('%M %d, %Y',from))+" - "+(AP.time.time('%M %d, %Y',to))+"</span>";
});

Render.on("text-byte", function(){
	this.addStandardTextLayout();
	var value = parseFloat(this.content||this.value);
	if (this.byte_unit) {
		value = (value / 1024).toFixed(2);
	}
	if(value >= 1024 && value < 1024000){
		value = AP.data.numberFormat((value / 1024).toFixed(2)) + ' MB';
	}else if(value >= 1024000 && value < 1000000000){
		value = AP.data.numberFormat((value / 1024000).toFixed(2)) + ' GB';
	}else{
		value = AP.data.numberFormat(value) + ' KB';
	}
	return "<span class='core-text-number "+(this.get('class'))+"' "+(this.css())+">"+(value)+"</span>";
});

Render.on("text-seo", function(){
	var title = this.title;
	if(title.length > 60) {
		title = title.substr(0, 60) + '...';
	}

	var description = this.description;
	if(description.length > 160) {
		description = description.substr(0, 160) + '...';
	}

	return "  " +Render.render('card_basic', {_class: "core-seo "+(this.get('class'))+"" }, "<div class='core-seo-title'>"+(title)+"</div> <div class='core-seo-link'>"+(this.link)+"</div> <div class='core-seo-desciption'>"+(description)+"</div>")+ "";
});



Render.on("card-basic", function(){
    let border_color = '';
    let text_color = '';
    let title = '';
    if (this.color){
        let list_color = ["primary", "secondary", "success", "danger", "warning", "info", "light", "dark"];
        if(list_color.includes(this.color)){
            border_color = "core-card-border-"+this.color;
            text_color = "core-card-text-"+this.color;
        }
    }

    if (this.title || this.icon){
        title = '<div class="core-card-header"';
        if(this.title_size){
            title += 'style="font-size: '+this.title_size+'px;';
            if(this.title_weight){
                title += 'font-weight: '+this.title_weight+';'
            }
            title += '"';
        }
        title += '>' + Render.helper.getIcon(this) + ' '+ this.title +
            '</div>';
    }

    return "<div class='core-card "+(border_color)+" "+(this.get('class'))+"' "+(this.css())+"> "+(title)+" <div class='core-card-body "+(text_color)+"'> "+(this.content)+" </div> </div>";
});

Render.on("card-image", function(){
    let border_color = '';
    let text_color = '';
    let image_top = '<img src="'+this.src+'" class="core-card-img" alt="'+this.alt+'">';
    let image_bottom = '';
    if (this.color){
        let list_color = ["primary", "secondary", "success", "danger", "warning", "info", "light", "dark"];
        if(list_color.includes(this.color)){
            border_color = "core-card-border-"+this.color;
            text_color = "core-card-text-"+this.color;
        }
    }

    if(this.position && this.position == 'bottom'){
        image_bottom = image_top;
        image_top = '';
    }

    return "<div class='core-card "+(border_color)+" "+(this.get('class'))+"' "+(this.css())+"> "+(image_top)+" <div class='core-card-body "+(text_color)+"'> "+(this.content)+" </div> "+(image_bottom)+" </div>";
});


Render.on("card-content-header", function() {
    var title = this.title || '';
    var meta = this.meta || '';
    if (this.url){
        this.addClass('core-url');
    }
    return "<div class='core-card-item core-semantic-card "+(this.get('class'))+"' "+(this.show('url'))+"> <div class='core-semantic-content'> <div class='core-semantic-header'>"+(title)+"</div> <div class='core-semantic-meta'>"+(meta)+"</div> <div class='core-semantic-description'> "+(this.content)+" </div> </div> </div> ";
})

Render.on('cards', function() {
    return "<div class='core-cards'>"+(this.content)+"</div>";
});



Render.on("icon", function(){
	var color = this.color;
	if (color){
		this.css("color", color);
	}else if (this.icon_color){
		this.css("color", this.icon_color);
	}
	
	if (this.url || this.urlparam){
		this.addClass("core-url");
	}
	
	if (this.fit){
		this.addClass("-fit");
	}
	
	if (this.sm){
		this.size=14;
	}
	
	if (this.lg){
		this.size=24;
	}
	
	if (this.xl){
		this.size=32;
	}
	
	if ('size' in this){
		this.css("width", this.size+"px");
		this.css("height", this.size+"px");
		this.addClass("-fixed-size");
	}else{
		this.addSizingClass();	
	}
	
	this.addClass("-ic-"+Render.helper.getIconType(this));

    var tt = '';
	
	if (this.inline){
		return "<div class='core-icon-inline "+(this.get('class'))+"'><div "+(this.showURL())+" class='core-icon "+(this.get('class'))+"' "+(this.css())+" "+(this.showData('urlparam'))+" "+(this.showHTMLSemantics())+" "+(this.showData('value'))+"> "+(Render.helper.getIcon(this))+" "+(tt)+" </div></div>";
	}
	
	return "<div "+(this.showURL())+" class='core-icon "+(this.get('class'))+"' "+(this.css())+" "+(this.showData('urlparam'))+" "+(this.showData('value'))+" "+(this.showHTMLSemantics())+"> "+(Render.helper.getIcon(this))+" "+(tt)+" </div>";
});

Render.on("iconbox", function(){
	var icon, bg;
	if (this.url){
		this.addClass("core-url");
	}
	
	if (this.iconbox){
		var parts = this.iconbox.split(" ");
		if (parts.length==2){
			icon = Render.helper.getIconByName(parts[0]);
			color = parts[1];
		}else if (parts.length==3){
			icon = Render.helper.getIconByName(parts[0]+ " "+parts[1]);
			color = parts[2];
		}else{
			return "";
		}
		

		color = Color.get(color);
		
		
		this.fill=1;
		
		if (Color.isDark(color)){
			this.addClass("-is-dark");
		}else{
			this.subtle=1;
			this.addClass("-is-light");
		}
		
		if (this.size||this.width){
			var w = this.size||this.width;
			if (AP.data.isInt(w)){
				this.css("width", w+"px");
				this.css("height", w+"px");
				this.css("padding-top", ((w-10)/3)+"px")	
			}
		}
	}else{
		icon = Render.helper.getIcon(this);
		
		var color = "#aaaaaa";
		if (this.isHexColor(this.color)){
			color = this.color
		}else{
			color = Color.get(this.color);
		}
	}
	
	this.addSizingClass();
	if (this.square){
		this.addClass("-square");
	}
	
	if (this.no_fill){
		this.css("color", Color.adjust(color, 20, 20));
	}else{
		if (this.fill || this.solid){
			if (this.fill == "none"){
				this.css("background-color", Color.adjust(color));
			}else if (this.fill == "subtle"){
				this.css("color", Color.adjust(color, 20, 20));
				this.css("background-color", Color.adjust(color, 10, -85));
			}else if (this.subtle==1){
				this.css("color", Color.adjust(color, 50, 50));
				this.css("background-color", color);
			}else if (this.fill == 1){
				this.css("color", "#fff");
				this.css("background-color", color);	
			}else{
				this.css("color", "rgba(255,255,255,0.9)");
				this.css("background-color", Color.adjust(color, 10, 10));	
			}
			
		}else{
			this.css("color", Color.adjust(color, 20, 20));
			this.css("background-color", Color.adjust(color, 10, -80));
			if (this.edge){
				this.addClass("-edge");
				this.css("border", ""+(this.edge)+"px solid "+Color.adjust(color, 15, -70));
			}
		}
	}
	
	
	return "<div class='core-iconbox "+(this.get('class'))+"' "+(this.showHTMLSemantics())+" data-url='"+(this.url||'')+"'> <div class='-bi' "+(this.css())+"> <div class='-icon'>"+(icon)+"</div> </div> </div>";
});


Render.on("cmenu", function(){
	var that = this;

	if (this.sm){
		this.css("width", "150px");
	}else{
		this.css("width", "200px");
	}

	if (this.width){
		this.css("width", this.width+"px");
	}

	var opts ="";

	if (this.options){
		if (AP.data.isArray(this.options)){
			opts = AP.render(this.options, function(e){
				if (e=="---"){
					return "<core-cmenu-item sep/>";
				}
				return "  " +Render.render('cmenu_item', {url:e.url||e.link||e.path, icon:e.icon||''}, ""+(e.opt_name||e.name||e.label)+"")+ '';
			});
		}else if (AP.data.isObject(this.options)){
			opts = this.options.inline();
		}
	}else if (this.items){
		opts = AP.render(this.items, function(e){
			var url = e.url||e.link||e.path;
			if (that.url){
				url = Render.matchURL(that.url, e);
			}

			return "  " +Render.render('cmenu_item', {url:url, icon:e.icon||''}, ""+(e.opt_name||e.name)+"")+ '';
		});
	}

	var filter = '';
	if (this.filter){
		var id = this.get('id');

		filter="<div class='-cmenu-filter'> " +Render.render('search', {placeholder: "{{Quick filter}}" , filter: "#"+(id)+" .-item" , disable_autocomplete:1, borderless:1}, '')+ "</div>";
	}

	var content = ""+(opts)+""+(this.content)+"";

	if (this.height || this.max_height){
		var mh = this.height || this.max_height;
		content = ""+(filter)+"<div class='-cmenu-scroll scroll-y' style='max-height:"+(mh)+"px'>"+(content)+"</div>";
		this.addClass('-scroll-fit');
	}

	if (this.url && !this.items){
		this.addClass("core-url");
	}

	return "<div class='-cmenu -padding -no-icon "+(this.get('class'))+"' "+(this.showData('url'))+" "+(this.css())+" "+(this.show('id'))+">"+(content)+"</div>";
}, function(params, obj){
	if (params.auto_active && params.urlparam){
		$(this).find(".-item").addClass("core-url").each(function(){
			$(this).data("urlparam", params.urlparam);
		});
		$(this).find(".-item").setActiveURLParam(params.urlparam, '');
	}else if (params.active_url){
		$(this).find(".-item").setActiveURL(params.active_url);
	}
});

Render.on("cmenu-item", function(){
    if ('acl' in this && !this.acl){
        return '';
    }
	if (this.sep){
		return "<div class='-item-sep'></div>";
	}

	var prefix='';

	if (this.icon){
		prefix = "<div class='-cmenu-icon'>"+(Render.helper.getIcon(this))+"</div>";
		this.addClass('-with-icon');
	}

	if (this.danger) {
		this.addClass('core-red');
	}

	if (this.complex){
		return "<div class='-item core-url -submenu -left "+(this.get('class'))+" core-complex' "+(this.show('url'))+" "+(this.showData('username'))+" "+(this.showAllData())+" title='"+(this.label||'')+"'> <span class='"+(this.xdot ? '-item-label-xdot core-ap-xdot' : '')+"'>"+(prefix)+""+(this.label||'')+"</span> <div class='submenu'> "+(this.content)+" </div> </div>";
	}else{
		var urlvalue = '';
		if (this.value){
			urlvalue= " data-value='"+(this.value)+"' ";
		}

		return "<div class='-item core-url core-ap-xdot "+(this.get('class'))+"' "+(this.show('url'))+" "+(urlvalue)+" "+(this.showData('username'))+" "+(this.showAllData())+" title='"+(this.label||inline(this.content)||'')+"'><span class='"+(this.xdot ? '-item-label-xdot core-ap-xdot' : '')+"'>"+(prefix)+""+(this.label||'')+"</span>"+(this.content)+"</div>";
	}
});



Render.ui.autocomplete = {
	cancel: function(ref){
		var name = $(ref).data("name");
		AP.setURLParams(assoc(name, null), true);
	},
};

Render.on("search", function(){
	var p = this.placeholder || __('Type to search');
	this.input_name = this.input_name||this._name||'qsearch';
	var extra='';
	if (this.disable_autocomplete || this.filter || this.autocomplete){
		extra="autocomplete='off'";
	}
	
	if (this.borderless){
		this.addClass("-borderless");
	}
	
	var cancel = '';
	if (this.autocomplete){
		this.addClass("-ac");
		cancel = "<div class='ac-cancel' onclick='Render.ui.autocomplete.cancel(this)' data-name='"+(this.filter||this._name)+"'> " +Render.render('icon', {icon: "ap ion-android-close" }, '')+ "</div>";
	}
	
	this.addSizingClass();
	
	if (this.icon_left){
		this.addClass("-icon-left");
	}
	
	return "<div class='search core-search "+(this.get('class'))+"' id='"+(this.id)+"-wrapper'> <input type='text' "+(extra)+" name='"+(this.input_name)+"' "+(this.show('id'))+" placeholder='"+(p)+"'/> "+(cancel)+" </div>";
},{
	done: function(params, obj){
		if (params.autocomplete){
			if (params.value){
				$(this).val(params.value);
				$(this).parent().addClass("-activated");
			}
			
			var $p = $(this).parent();
			
			// Handle auto-complete
			if (params.autocomplete === 1){
				var source = AP.select(obj.source, function(e){
					return {label: e.name, value: e.name, id: e.id};
				});
				
				$(this).apcomplete(source, false, function(e){
					if (params.filter){
						AP.setURLParams(assoc(params.filter, e.id), true);
					}
					
					if ($p.hasClass("__input_autocomplete")){
						$p.parent().find(".hidden input").val(e.id);
						$p.parent().find(".hidden input").data("obj", e);
					}
				});
				
				if (params.filter && Query.get(params.filter)){
					var v = ARR.findObj(source, Query.get(params.filter));
					if (v){
						$(this).val(v.value);
						$(this).parent().addClass("-activated");
					}
				}
			}else{
				$(this).apcomplete(params.autocomplete, false, function(e){
					if (params.filter){
						AP.setURLParams(assoc(params.filter, e.id), true);
					}
					
					if ($p.hasClass("__input_autocomplete")){
						$p.parent().find(".hidden input").val(e.id);
						$p.parent().find(".hidden input").data("obj", e);
					}
				});
			}
			
		}else if (params.binding || params.bind){
			AP.bindSearch("#"+params.id);
		}
	}
});

Render.on("search-ajax", function(){
	return "<div class='core-search-ajax "+(this.get('class'))+"' "+(this.css())+" "+(this.show('id'))+"> <div class='con-input'> " +Render.render('form_addon', {icon_right: "search" , type: "text" , _name: "search_ajax" , placeholder:this.placeholder || __("Search"), value: '' }, '')+ "</div> <div class='core-recent-search__list'></div> <div class='core-search-content-results'> <div class='con-results'></div> <div class='not-results'>"+(__('Not Results'))+"</div> </div> </div>";
}, {
	done: function(params, obj) {
		var _this = this;
		var multiple = params.multiple ? 1 : 0;
		if($(_this).find('.core-recent-search__list').html().trim() == ''){
			$(_this).find('.con-input').show();
		}else{
			$(_this).find('.con-input').hide();
		}
		$(document).on('click', '.con-results .result', function () {
			var search_id = $(this).find('.search_id').val();
			var title = $(this).find('h5').text();
			$(_this).find('.core-recent-search__list').append("  " +Render.render('search_item', {value:search_id, title:title, _name:params._name || "data_search", multiple:multiple}, '')+ '');
			if(!multiple){
				$(_this).find('.con-input').hide();
				$(_this).removeClass('focus');
			}
		});
		$(document).on('click', '.search-item__close', function () {
			$(this).parents('.search-item').remove();
			if(!multiple){
				$(_this).find('.con-input').show();
			}
		});
		$(this).find('[name="search_ajax"]').keyup(function () {
			if($(this).val().trim() == ''){
				$(_this).find('.con-results').empty();
				$(_this).removeClass('focus');
				return true;
			}
		});
		$(this).find('[name="search_ajax"]').keypress(function(event){
			if($(this).val().trim() == ''){
				$(_this).find('.con-results').empty();
				$(_this).removeClass('focus');
				return true;
			}
			var keycode = (event.keyCode ? event.keyCode : event.which);
			if (keycode == '13') {
				AP.post(Client.link_module, {_a: 'search_ajax', k: $(this).val()}, function (code) {
					if (!code.good()) {
						return AP.toastr.error(code.message);
					}
					var data_html = '';
					var data = code.data;
					if(code.data.length > 0){
						for(i in data){
							data_html += "  " +Render.render('search_result', {id:data[i].id, title:data[i].title, data:data[i].content || ""}, '')+ '';
						}
						$(_this).find('.con-results').html(data_html);
						$(_this).removeClass('notValue');
						$(_this).addClass('focus');
						return true;
					}
					$(_this).find('.con-results').empty();
					$(_this).addClass('notValue');
					$(_this).addClass('focus');
				});
			}
		});
	}
});

Render.on("search-item", function(){
	var name  = this._name;
	if(this.multiple){
		name += '[]';
	}
	return "<span class='search-item'> <input type='hidden' name='"+(name)+"' value='"+(this.value)+"'> <span>"+(this.title)+"</span> <span class='search-item__close'>×</span> </span>";
});

Render.on("search-result", function(){
	var content = '';
	if(this.data){
		content = "<div>"+(this.data)+"</div>";
	}
	return "<div class='result'> <input type='hidden' class='search_id' value='"+(this.id)+"'> <h5>"+(this.title)+"</h5> "+(content)+" </div>";
});


Render.on("side", function(){
    if ('acl' in this && !Render.helper.acl(this.acl)){
        return '';
    }

	if (this.width){
		this.css("width", this.width+"px");
	}

	if (this.left) {
		this.addClass('-left');
	}

	return "<div class='core-side "+(this.get('class'))+"' "+(this.css())+" "+(this.show('id'))+">"+(this.content)+"</div>";
});

Render.on("sep", function(opts){
	if (this.value) {
		return "<div class='core-sep' style='height: "+(this.value)+"px;'></div>";
	}
	return "<div class='core-row-hr'></div>";
});


Render.on("skeleton", function() {
    var rows = this.rows || 4;
    var paragraph = '';
    for (var i=0; i<rows; i++) {
        paragraph += '<li></li>';
    }
    if (this.active) {
        this.addClass('core-skeleton-active');
    }
    return "<div class='core-skeleton "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.css())+"> <div class='core-skeleton-content'> <h3 class='core-skeleton-title'></h3> <ul class='core-skeleton-paragraph'> "+(paragraph)+" <li style='width: 61%;'></li> </ul> </div> </div> ";
});


Render.on("none", function(){
	if (this.inline){
		this.addClass('inline');
	}

	if (this.normal){
		this.addClass('normal');
	}

	if (this.fit){
		this.addClass("-fit");
	}

	return "<div class='core-none "+(this.get('class'))+"'>"+(this.content)+"</div>";
});

Render.on("empty", function(){
	var title=this.title?"<div class='-title'>"+(this.title)+"</div>":'';
	if (this.md){
		this.addClass("-md");
	}else if (this.sm){
		this.addClass("-sm");
	}

	if (this.fill){
		this.addClass("-fill");
	}

	if (this.inline){
		this.addClass("-inline-display");
	}

	return "<div class='core-empty-state "+(this.get('class'))+"'> <div class='-icon'>"+(Render.helper.getIcon(this))+"</div> "+(title)+" <div class='-text'>"+(this.content)+"</div> </div>";
});

Render.on("block", function(){
	var icon = '';
	var split_content = '';
	if (this.split_content) {
	    split_content = '-split';
    }
	if (this.icon){
		if (this.icon=='1' || this.icon==1){

		}else{
			icon = "<div class='-icon'>"+(Render.helper.getIcon(this))+"</div>";
		}

		this.addClass("-picon");
	}

	if (this.borderless) {
	    this.addClass('-borderless');
    }

	if (this.clean) {
        this.addClass('-clean');
    }

	var title_df=this.title?("<div class='core-block-title'>"+(this.title)+"</div>"):'';
	var subtitle_df=this.subtitle?("<div class='core-block-info'>"+(this.subtitle)+"</div>"):'';

	if (this.fit){
		this.addClass("-fit");
	}

	this.addSizingClass();

	if (this.width){
		this.css("width", this.width+"px");
	}

	if (this.top){
		this.css("margin-top", this.top+"px");
	}

	if (this.compact){
		this.addClass("-compact");
	}

	if (this.block_table) {
		this.addClass('-table-content');
	}

	if (this.content_compact) {
		this.addClass('-content-compact');
	}

	return "<div class='core-block "+(this.get('class'))+"' "+(this.css())+" "+(this.showAllData())+" "+(this.showHTMLSemantics())+" "+(this.showURL())+"> "+(icon)+" "+(title_df)+" "+(subtitle_df)+" <div class='core-block-content "+(split_content)+"'>"+(this.content)+"</div> </div>";
});

Render.on("support", function() {
    return "<div class='core-support-popup' id='"+(this.id)+"'> <div class='-title'>"+(this.title || __('Getting started with APP'))+"</div> <div class='core-support-items'>"+(this.content)+"</div> </div>";
}, {
    done: function(params) {
        var $that = this;
        $($that).find(".core-button").each(function() {
            $(this).click(function() {
                Core.pref().set('action-support', $(this).attr('id'));
            })
        });
    }
});

Render.on("empty-state", function() {
	var image_empty = "  " +Render.render('image', {src: ""+(Client.base_link)+"modules/"+(Client.name_module)+"/views/img/module/empty.state.svg" , no_view_detail:1}, '')+ '';
	if (this.no_image) {
		image_empty = '';
	}
	if (this.name_file) {
		var link = ""+(Client.base_link)+"modules/"+(Client.name_module)+"/views/img/module/"+(this.name_file)+"";
		image_empty = "  " +Render.render('image', {src:link, no_view_detail:1}, '')+ '';
	}
	return "<div class='core-empty-state'> "+(image_empty)+" <div class='-title'> "+(this.title || __('No data found'))+" </div> <p>"+(this.msg || '')+"</p> <div class='-content'> "+(this.content)+" </div> </div>";
});

Render.on("recommend-module", function() {
	var number_check = 0;
	var e_id = this.id;
	var item_per_page = this.item_per_page || 2;
	var check_apps = setInterval(function() {
		number_check++;
		if (number_check > 10) {
			clearInterval(check_apps);
		}
		if (!Client.apps) {
			return;
		}
		clearInterval(check_apps);
		var apps = Client.apps;
		var navigation = '';
		var carousel_selector_items = '';
		var html_items = '';
		var start = 0;
		var num_page = Math.ceil(apps.length/item_per_page);
		for (var i=0; i<num_page; i++) {
			var id = "core-pd-carousel-item"+(i)+"";
			var checked_first = se(i, 0) ? "checked='checked'" : "";
			var carousel_selector_checked = se(i, 0) ? "-selected" : "";
			var carousel_item_checked = se(i, 0) ? "style='display: block;'" : "";
			navigation += "<input type='radio' id='"+(id)+"' class='core-pd-carousel-input' "+(checked_first)+">";
			carousel_selector_items += "<li class='core-pd-carousel-selector_item "+(id)+" "+(carousel_selector_checked)+"'><label for='"+(id)+"' class='core-pd-carousel-selector'></li>";

			var modules = apps.slice(start * item_per_page, item_per_page * (start + 1));
			start++;
			var html_modules = AP.render(modules, function(module) {
				return "<div class='-appmain'> " +Render.render('image', {src:module.image, no_view_detail:1}, '')+ "<div class='-app-detail'> " +Render.render('title', {}, ""+(module.name)+"")+ " " +Render.render('text_info', {}, ""+(module.title)+"")+ "</div> </div>";
			});
			html_items += "<li class='core-pd-carousel-item "+(id)+"' "+(carousel_item_checked)+">"+(html_modules)+"</li>";
		}
		if (se(num_page, 1)) {
			carousel_selector_items = '';
		}
		$("#"+e_id).html("<div class='core-recommend-module'> <div class='inputs'>"+(navigation)+"</div> <ul class='core-pd-carousel-items'>"+(html_items)+"</ul> <ul class='core-pd-carousel-selector-items'> "+(carousel_selector_items)+" </ul> </div>");
	}, 1000);

	return "<div id='"+(e_id)+"'></div>";
}, {
	done: function (params) {
		var $that = $(this);
		var dispay_content_slider = function() {
			$that.find(".core-pd-carousel-input").each(function () {
				if (!$(this).prop('checked')) {
					return;
				}

				var id = $(this).attr('id');
				$that.find(".core-pd-carousel-items .core-pd-carousel-item").hide();
				$that.find(".core-pd-carousel-selector-items .core-pd-carousel-selector_item").removeClass('-selected');

				$that.find("."+id).show();
				$that.find("."+id).addClass('-selected');
			});
		}

		var check_render_finished = setInterval(function() {
			if (!$(".core-recommend-module").length) {
				return;
			}
			clearInterval(check_render_finished);
			setInterval(function() {
				var input_checked = $(".core-pd-carousel-input:checked");
				input_checked.prop("checked", false).next().prop("checked", true).end().appendTo($that.find(".inputs"));

				dispay_content_slider();
			}, 4000);
		});
	}
});

Render.on("devider", function() {
	if (this.inline){
		this.addClass('inline');
	}
	if (this.horizontal) {
		this.addClass('core-divider-horizontal');
	}
	if (this.dashed) {
		this.addClass('-dashed');
	}
	if (this.label) {
		this.addClass('-has-label');
	}
	if (this.label_left) {
		this.addClass('-label-left');
	}
	if (this.label_right) {
		this.addClass('-label-right');
	}
	if (this.mr) {
		this.css("margin-right", ""+(this.mr)+"px");
	}
	if (this.ml) {
		this.css("margin-left", ""+(this.ml)+"px");
	}
	if (this.height) {
		this.css("height", ""+(this.height)+"px");
	}
	return "<div class='core-divider "+(this.get('class'))+"' id='"+(this.id)+"' "+(this.css())+">"+(this.label || '')+"</div>";
});


Render.on("section", function(){
	if (this.fill){
		this.addClass("-fill-"+this.fill);
	}
	
	return "<div class='core-section "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.showAllData())+">"+(this.content)+"</div>";
});

Render.on("section-header", function(){
	this.addStateClass();
	
	if (this.dd){
		this.addClass("-picon -dd");
	}
	
	var arr='';
	if (this.collapsible){
		this.addClass("-collapsible");
        this.icon = 'caret_down_fill';
		arr = "<div class='core-triangle core-url' "+(this.showData('ckey'))+" data-url=':collapse/2'>"+(Render.helper.getIcon(this))+"</div>";
	}
	
	return "<div class='core-section-header "+(this.get('class'))+"' "+(this.show('id'))+"> "+(arr)+" <div class='-inner'>"+(this.content)+"</div> </div>";
}, {
	done: function(params) {
		if (Core.pref().get($(this).find('.core-triangle').data('ckey'))) {
			$(this).closest('.core-section').addClass("-collapsed");
			return;
		}
	}
});

Render.on("section-content", function() {
	return "<div class='core-section-content "+(this.get('class'))+"' "+(this.show('id'))+"> <div class='-inner'>"+(this.content)+"</div> </div>";
});


Render.ui.setAutoActiveTab = function($this, params){
	if (params.param){
		$this.find(".core-tab").addClass("core-url").data("urlparam", params.param);
		$this.find(".core-tab").setActiveURLParam(params.param, {fallback: params._default||''});

		if (!$this.find(".core-tab.core-active").length){
			$this.find(".core-tab").setActiveData("value", params._default);
		}
	}else{
		$this.find(".core-tab").setActiveURL({fallback: params._default||''});
		if (!$this.find(".core-tab.core-active").length){
			$this.find(".core-tab").setActive(params._default);
		}
	}
};

Render.on("tabs", function(){
	if (this.inline){
		return "<div class='core-tabs -inline clear-fix "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.css())+"><div class='-bt-inner'>"+(this.content)+"</div></div>";
	}

	return "<div class='core-tabs clear-fix "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.css())+">"+(this.content)+"</div>";

}, {
	done: function(params){
		if (params.param){
			$("#"+params.id).find(".core-tab").addClass("core-url").data("urlparam", params.param);
		}else if (params.urlparam){
			$("#"+params.id).find(".core-tab").addClass("core-url").data("urlparam", params.urlparam);
			$(this).find(".core-tab").setActiveURLParam(params.urlparam, {fallback: params._default||''});
		}

		var $this = $(this);
		if (params.auto_active){
			Render.ui.setAutoActiveTab($this, params);
		}

		if (params.persistent){
			AP.sys.on(AP.EVENTS.PAGE.AFTERLOAD, function(){
				Render.ui.setAutoActiveTab($this, params);
			})
		}
	}
});


Render.on("tab", function(){
	var icon='';
	var dd_icon='';

	if (this.icon){
		icon="  " +Render.render('icon', {icon:this.icon}, '')+ '';
		this.addClass("-picon");
	}

	if (this.dd){
		this.addClass('-pdd -cmenuw relative');
	}

    if (this.active){
		this.addClass("core-active");
	}

	var value='';
	if ('value' in this){
		value=" data-value='"+(this.value)+"'";
	}

	if (this.dd && this.url){
		return "<div class='core-tab "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.showData('activate'))+" "+(value)+" "+(this.showAllData())+" "+(this.showData('url'))+" "+(this.showData('action'))+"> <div class='-tab-wrapper'> "+(icon)+" <div class='-tab-inner'> <span class='core-url' data-url='"+(this.url)+"'>"+(this.label||'')+"</span> "+(this.content)+" </div> "+(dd_icon)+" </div> </div>";
	}

	return "<div class='core-tab "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.show('url'))+" "+(this.showData('action'))+" "+(this.showData('activate'))+" "+(value)+" "+(this.showAllData())+"> <div class='-tab-wrapper'> "+(icon)+" <div class='-tab-inner'>"+(this.label||'')+""+(this.content)+"</div> "+(dd_icon)+" </div> </div>";
});

Render.on("block-tabs", function() {
    var position = "core-block-ant-tabs-"+(this.position || 'top')+"";
    if (this.tab_card) {
        this.addClass('core-block-ant-tabs-card');
    }
    if (this.tab_center) {
        this.addClass('core-block-ant-tabs-centered');
    }
    if (this.card_container) {
        return "<div class='core-block-card-container'> <div class='core-block-ant-tabs "+(position)+" "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.css())+"> "+(this.content)+" </div> </div> ";
    }
    return "<div class='core-block-ant-tabs "+(position)+" "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.css())+"> "+(this.content)+" </div> ";
}, {
    done: function (params) {
        $(this).append("<div role='tablist' class='core-block-ant-tabs-nav'> <div class='core-block-ant-tabs-nav-wrap'> <div class='core-block-ant-tabs-nav-list'></div> </div> </div> <div class='core-block-ant-tabs-content-holder'> <div class='core-block-ant-tabs-content core-block-ant-tabs-content-"+(params.position || 'top')+"'></div> </div> ");

        var $that = $(this);
        $(this).find(".core-block-ant-tabs-tab").each(function(index) {
            $that.find(".core-block-ant-tabs-nav-list").append($(this));
            $(this).click(function() {
                $that.find(".core-block-ant-tabs-nav-list .core-block-ant-tabs-tab").removeClass("core-block-ant-tabs-tab-active");
                $(this).addClass("core-block-ant-tabs-tab-active");
                $that.find('.core-block-ant-tabs-ink-bar').css({
                    left: $(this).position().left + (index == 0 ? 0 : 32),
                    width: $(this).outerWidth()
                });
                $that.find(".core-block-ant-tabs-tabpane").addClass("core-block-ant-tabs-tabpane-hidden");
                $("#"+$(this).find(".core-block-ant-tabs-tab-btn").attr("aria-controls")).removeClass("core-block-ant-tabs-tabpane-hidden");
            });
        });

        if ($(this).find(".core-block-ant-tabs-nav-list .core-block-ant-tabs-tab-active").length == 0) {
            $(this).find(".core-block-ant-tabs-nav-list .core-block-ant-tabs-tab").first().addClass("core-block-ant-tabs-tab-active");
        }
        $that.find(".core-block-ant-tabs-nav-list").append("<div class='core-block-ant-tabs-ink-bar core-block-ant-tabs-ink-bar-animated'></div> ");

        var e_tab_active = $(this).find(".core-block-ant-tabs-nav-list .core-block-ant-tabs-tab-active");
        var index_tab_active = e_tab_active.index($(this).find(".core-block-ant-tabs-nav-list .core-block-ant-tabs-tab"));
        setTimeout(function() {
            $that.find('.core-block-ant-tabs-ink-bar').css({
                left: e_tab_active.position().left + (index_tab_active == 0 ? 0 : 32),
                width: e_tab_active.outerWidth()
            });
        });

        $(this).find(".core-block-ant-tabs-tabpane").each(function() {
            $that.find(".core-block-ant-tabs-content").append($(this));
        });

        $("#"+e_tab_active.find(".core-block-ant-tabs-tab-btn").attr("aria-controls")).removeClass("core-block-ant-tabs-tabpane-hidden");
    }
});

Render.on("block-tab-pane", function () {
    var label = this.label || __('Tab Label');
    var key = this.key || 'tab-pane-'+ AP.uuid();
    if (this.active) {
        this.addClass("core-block-ant-tabs-tab-active");
    }

    if (this.center) {
        this.addClass("core-tcenter");
    }

    if (this.width) {
        this.css('width', this.width + 'px');
    }
    return "<div class='core-block-ant-tabs-tab "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.css())+"> <div role='tab' class='core-block-ant-tabs-tab-btn' id='js-tabs-tab-"+(key)+"' aria-controls='js-tabs-panel-"+(key)+"'> "+(label)+" </div> </div> <div role='tabpanel' class='core-block-ant-tabs-tabpane core-block-ant-tabs-tabpane-hidden' id='js-tabs-panel-"+(key)+"' aria-labelledby='js-tabs-tab-"+(key)+"'> "+(this.content)+" </div> ";
})



Render.ui.filter = {
	cancelUserFilter: function(ref){
		var name = $(ref).data("name");
		if (name && Query.get(name)){
			AP.setURLParams(assoc(name, null), true);
		}
	},

	cancelDateRangeFilter: function(ref){
		var names = $(ref).data("names");
		var parts = AP.word.split(",", names, true);

		if (parts && parts.length==2){
			var ps = {};
			ps[parts[0]]=null;
			ps[parts[1]]=null;
			AP.setURLParams(ps, true);
		}
	},

	cancelDateFilter: function(ref){
		var filter = $(ref).data("filter");
		AP.setURLParams(assoc(filter, null), true);
	}
};

Render.on("filter-list", function(){
	if (this.borderless){
		this.addClass('core-borderless');
	}

	if (!this.filter && this.binding){
		this.filter = this.binding;
	}

	if (this.right){
		this.css("core-float", "core-right");
	}

	this.addSizingClass();

	if (this.checkbox){
		this.type='checkbox';
	}else{
		this.type='radio';
	}

	var title = this.title;
	if (this.dd){
		this.addClass("-dd");
		var ckey = '';
		if (this.dd!='1' && this.dd!=1){
			ckey = this.dd;
		}

		title = "<span class='core-url' data-url=':collapse/3' data-ckey='"+(ckey)+"'>"+(this.title)+"</span>";
	}

	var options="";
	if (this.options){
		options = AP.render(this.options, function(e){
			return "  " +Render.render('filter_opt', {value:e.id, label:e.name}, '')+ '';
		});

		if (this.empty || this._default){
			var lb = this.empty || this._default;
			options="  " +Render.render('filter_opt', {value: '' , label:lb}, '')+ ''+options;
		}

		options="  " +Render.render('filter_opts', {list:1}, ""+(options)+"")+ '';
	}

	return "<div class='core-filter-block core-filter-list core-js-filter -is-"+(this.type)+" "+(this.get('class'))+"' "+(this.css())+" data-filter='"+(this.filter)+"' "+(this.show('id'))+"> <div class='core-filter-list-inner'> <div class='core-bf-header'>"+(title)+"</div> <div class='core-bf-body'> "+(options)+" "+(this.content)+" </div> </div> </div>";
}, {
	done: function(attrs){
		if (attrs.dd){
			var ckey = '';
			if (attrs.dd!='1' && attrs.dd!=1){
				ckey = attrs.dd;
			}

			var pref = Core.pref().get(ckey);
			if (pref){
				$(this).addClass("-collapsed");
			}
		}

		var f = $(this).data("filter");

		$(this).find(".core-js-filter-opt").each(function(){
			$(this).data("urlparam", f);
		});

		$(this).find(".core-js-filter-opt").setActiveURLParam(f, {fallback: ""});

		var v= $(this).find(".core-js-filter-opt.core-active").data('label');
		if (!v){
			return;
		}
	}
});

Render.on("filter-opts", function(){
	var html = '';
	if (this.empty){
		html="  " +Render.render('filter_opt', {value: '' , label:this.empty}, '')+ '';
	}else if (this._default){
		html="  " +Render.render('filter_opt', {value: '' , label:this._default}, '')+ '';
	}

	if (this.options){
		html += AP.render(this.options, function(e){
			if (e.id && e.name){
				return "  " +Render.render('filter_opt', {value:e.id, label:e.name}, '')+ '';
			}else{
				return "  " +Render.render('filter_opt', {value:e.value, label:e.label}, '')+ '';
			}
		});
	}

	if (this.list){
		return "<div class='core-filter-opts' "+(this.show('id'))+"> "+(html)+" "+(this.content)+" </div>";
	}

	return "<div class='-cmenu -padding -no-icon' "+(this.show('id'))+"> "+(html)+" "+(this.content)+" </div>";
});

Render.on("filter-opt", function(){
	if (this.sep){
		return "<div class='core-filter-opt-sep'></div>";
	}

	return "<div class='core-filter-opt core-js-filter-opt -item core-url' data-value='"+(this.value)+"' data-label='"+(this.label)+"'> <div class='core-filter-ic'></div> <div class='core-ap-xdot'>"+(this.label||'')+""+(this.content)+"</div> </div>";
});

Render.on("filter", function(){
	if (this.borderless){
		this.addClass('core-borderless');
	}

	if (!this.filter && this.binding){
		this.filter = this.binding;
	}

	if (this.right){
		this.css("float", "right");
		this.addClass("-right");
	}

	this.addSizingClass();

	var prefix = this.get("prefix")||'';

	var options="";
	if (this.options){
		options = AP.render(this.options, function(e){
			return "  " +Render.render('filter_opt', {value:e.id, label:e.name}, '')+ '';
		});

		if (this._default){
			options="  " +Render.render('filter_opt', {value: '' , label:this._default}, '')+ ''+options;
		}

		options="  " +Render.render('filter_opts', {}, ""+(options)+"")+ '';
	}

	var icon="<div class='core-bf-icon'><span class='core-ficon-filter'></span></div>";

	if (this.icon && this.icon == ":none:"){
		icon = '';
		this.addClass("-no-icon");
	}else if (this.icon){
		icon="<div class='core-bf-icon'>"+(Render.helper.getIcon(this.icon || 'filter'))+"</div>";
	}


	if (this.no_icon){
		icon = '';
		this.addClass("-no-icon");
	}else{
		this.addClass("-with-icon");
	}

	return "<div class='core-filter core-js-filter -cmenuw "+(this.get('class'))+"' "+(this.css())+" data-filter='"+(this.filter)+"' "+(this.show('id'))+"> "+(icon)+" " +Render.render('filter_current', {prefix:prefix}, "--")+ ""+(options)+" "+(this.content)+" </div>";
}, {
	done: function(attrs){
		var f = $(this).data("filter");

		$(this).find(".core-js-filter-opt").each(function(){
			$(this).data("urlparam", f);
		});

		$(this).find(".core-js-filter-opt").setActiveURLParam(f, {fallback: ""});

		var v= $(this).find(".core-js-filter-opt.core-active").data('label');
		if (!v){
			return;
		}

		$(this).find(".core-filter-current .core-js-value").html(v);
	}
});

Render.on("filter-current", function(){
	var txt = this.prefix;
	if (!txt){
		return "<div class='core-filter-current core-no-prefix'><span class='core-js-value -value'>---</span></div>";
	}

	return "<div class='core-filter-current'> <span class='core-js-prefix -prefix'>"+(txt)+"</span>: <span class='core-js-value -value'></span> </div>";
});

Render.on("filter-daterange", function(){
	var title = '';
	if (this.title){
		title = "<div class='core-bf-header'>"+(this.title)+"</div>";
	}

	var names = this.names||this._name||'start,end';
	var pnames = AP.word.split(",", names, true);

	if (pnames.length!=2){
		AP.toastr.error(__('ERROR_FILTER_DATE_RANGE_NAME'));
		return '';
	}

	var start = pnames[0];
	var cancel = "<div class='core-fd-cancel core-url' data-names='"+(names)+"' onclick='Render.ui.filter.cancelDateRangeFilter(this)'> " +Render.render('icon', {icon: "close" }, '')+ "</div>";

	if (!Query.getInt(start)){
		this.addClass('-not-chosen');
	}

	return "<div class='core-filter-block core-filter-daterange "+(this.get('class'))+"' "+(this.show('id'))+" data-names='"+(names)+"' "+(this.css())+"> "+(title)+" <input type='hidden' name='"+(pnames[0])+"'/> <input type='hidden' name='"+(pnames[1])+"'/> <div class='core-fd-comp'> <div class='core-fd-label'>"+(__('Date'))+":</div> <div class='core-fd-value core-js-range'> " +Render.render('none', {}, ""+(__('Please select'))+"")+ "</div> <div class='core-fd-mask core-abs-fit'></div> "+(cancel)+" </div> </div>";
}, {
	done: function(params){
		var m_start = null;
		var m_end = null;
		var $that = $(this);
        var names = params.names||params._name||'start,end';
        var pnames = AP.word.split(",", names, true);

		var ts = Query.get(pnames[0]);
		if (ts){
			m_start = moment(ts, "DD-MM-YYYY");
		}

		var ts = Query.get(pnames[1]);

		if (ts){
			m_end = moment(ts, "DD-MM-YYYY");
		}

		$("#"+params.id+" .core-fd-mask").dateRangePicker({
			getValue: function(){
				return this.innerHTML;
			},
			onSelect: function(from, to){
			    if (!params.no_bind) {
			        var data = {};
			        data[pnames[0]] = encodeURIComponent(AP.time.time("%d-%m-%Y", from));
			        data[pnames[1]] = encodeURIComponent(AP.time.time("%d-%m-%Y", to));
                    AP.setURLParams(data, true);
                } else {
			        $that.removeClass('-not-chosen');
			        var start_time = encodeURIComponent(AP.time.time("%d-%m-%Y", from));
			        var to_time = encodeURIComponent(AP.time.time("%d-%m-%Y", to));
                    $that.find("input[name='"+pnames[0]+"']").val(start_time);
                    $that.find("input[name='"+pnames[1]+"']").val(to_time);
                    $that.find(".core-js-range").html("  " +Render.render('text_daterange', {_from:moment(start_time, "DD-MM-YYYY").unix(), to:moment(to_time, "DD-MM-YYYY").unix()}, '')+ '');
			    }
				$(this).data('dateRangePicker').close();
			}
		});

		if (m_start && m_end){
			$("#"+params.id).find(".core-js-range").html("  " +Render.render('text_daterange', {_from:m_start.unix(), to:m_end.unix()}, '')+ '');
		}

        var dr = $("#"+params.id+" .core-fd-mask").data("dateRangePicker");
		if (m_start){
			dr.setStart(m_start.format("YYYY-MM-DD"));
		}

		if (m_end){
			dr.setEnd(m_end.format("YYYY-MM-DD"));
		}
	}
});



Render.on("pagination", function(){
	var url = this.url;

	if (!url){
		url = Render.pagination.getContextURL();
	}

	var page = Query.getInt("page");
	if (!page) {
		page = 1;
	}
	this.addSizingClass();

	if (!('num_items' in this)){
		return "<div class='core-pagination "+(this.get('class'))+"'> <div class='core-apppages core-center "+(this.get('class'))+"'>"+(Render.pagination.simple(url, page))+"</div> </div>";
	}

	if (!this.ipp){
		this.ipp=20;
	}

	if (!this.limit){
		this.limit=8;
	}

	this.num_items = parseInt(this.num_items);
	this.ipp = parseInt(this.ipp);

	var pages = Render.pagination.getPages(this, url, page);

	var html = AP.render(pages, function(e){
		if (e == "-truncation-"){
			return "<div class='core-pag-trunc'><span class='-ap icon-dots-two-horizontal'></span></div>";
		}else{
			return "<div class='core-pag core-url "+(parseInt(e)==page?'core-active':'')+"' data-url='"+(Render.pagination.url(url, e))+"'>"+(e)+"</div>";
		}
	});
	var prev = "<div class='core-pag-nav -prev core-url' data-url='"+(Render.pagination.url(url, page-1))+"'><span class='-bis-icon'>"+(SVG.chevron_left)+"</span></div>";
	if (page<=1){
		prev = "<div class='core-pag-nav -prev -disabled'><span class='-bis-icon'>"+(SVG.chevron_left)+"</span></div>";
	}

	var num_pages = Math.ceil(this.num_items/this.ipp);

	var next = "<div class='core-pag-nav -next core-url' data-url='"+(Render.pagination.url(url, page+1))+"'><span class='-bis-icon'>"+(SVG.chevron_right)+"</span></div>";
	if (page>=num_pages){
		next = "<div class='core-pag-nav -next -disabled'><span class='-bis-icon'>"+(SVG.chevron_right)+"</span></div>";
	}


	html=""+(prev)+" "+(html)+" "+(next)+"";

	var _from = (page-1)*this.ipp+1;
	var _to = page*this.ipp;
	if (_to>this.num_items){
		_to=Math.max(this.num_items, 1);
	}

	return "<div class='core-pagination "+(this.get('class'))+"' "+(this.css())+"><div class='core-bp-wrapper'> <div class='core-bp-panel'>"+(html)+"</div> <div class='core-bp-exp'>"+(__('Showing results'))+" <em>"+(_from)+"</em> - <em>"+(_to)+"</em> "+(__('of'))+" <em>"+(this.num_items)+"</em></div> </div> </div>";
});




Render.pagination = new function __RenderPag(){
	this.getPages = function(context, url, page){
		var num_pages = Math.ceil(context.num_items/context.ipp);

		var pages=[];
		for (var i= page-context.limit; i<page+context.limit; i++){
			if (i<=0 || i>num_pages){
				continue;
			}

			pages.push(i);
		}

		while (true){
			if (pages.length<=context.limit){
				break;
			}

			var left_diff = page - pages[0];
			var right_diff = pages[pages.length-1] - page;

			if (right_diff >= left_diff){
				pages.pop();
			}else{
				pages.shift();
			}
		}

		if (pages.length==0){
			return [1];
		}

		if (pages.length<=1){
			return pages;
		}

		if (pages[0]>2){
			pages.unshift("-truncation-");
			pages.unshift(1);
		}else if (pages[0]==2){
			pages.unshift(1);
		}

		if (pages[pages.length-1] <= num_pages-2){
			pages.push("-truncation-");
			pages.push(num_pages);
		}else if (pages[pages.length-1] == num_pages-1){
			pages.push(num_pages);
		}

		return pages;
	};


	this.simple = function(url, page){
		var counter='';
		if (Client.pageData.result_counts){
			counter = " &nbsp; (of total "+(Client.pageData.result_counts)+" records) ";
		}

		var prev = "<div class='core-prev core-url "+(page==1?'core-disabled':'')+"' data-url='"+(this.url(url, page-1))+"'><span class='-bis-icon'>"+(SVG.chevron_left)+"</span></div>";
		var next = "<div class='core-next core-url' data-url='"+(this.url(url, page+1))+"'><span class='-bis-icon'>"+(SVG.chevron_right)+"</span></div>";

		var html = "<div class='core-icons'> "+(prev)+"<div class='core-label core-url' data-url=':xrefresh'>Page "+(page)+" "+(counter)+"</div>"+(next)+" </div>";

		return html;
	};


	this.url = function(url, page){
		if (!page || page<=1){
			return url;
		}

		if (url.indexOf("?") != -1){
			return url + "&page=" + (page);
		}else{
			return url + "?page=" + (page);
		}
	};

	this.getContextURL = function(){
		var url=Client.current_path;
		if (!url){
			url="";
		}

		var cqs="";

		var qs=Query.all();
		for (var key in qs){
			if (key=="env" || key=="page" || !key){
				continue;
			}
			cqs+=key+"="+qs[key]+"&";
		}

		if (cqs.length){
			cqs=cqs.substr(0, cqs.length-1);
		}
		if (cqs){
			/*
			if (document.URL.indexOf("?")==-1 || cqs){
				url=url+"?"+cqs;
			}else{
				url=url+"&"+cqs;
			}*/
			url=url+"&"+cqs;
		}

		return url;
	};
};



Render.on("card-basic", function(){
    let border_color = '';
    let text_color = '';
    let title = '';
    if (this.color){
        let list_color = ["primary", "secondary", "success", "danger", "warning", "info", "light", "dark"];
        if(list_color.includes(this.color)){
            border_color = "core-card-border-"+this.color;
            text_color = "core-card-text-"+this.color;
        }
    }

    if (this.title || this.icon){
        title = '<div class="core-card-header"';
        if(this.title_size){
            title += 'style="font-size: '+this.title_size+'px;';
            if(this.title_weight){
                title += 'font-weight: '+this.title_weight+';'
            }
            title += '"';
        }
        title += '>' + Render.helper.getIcon(this) + ' '+ this.title +
            '</div>';
    }

    return "<div class='core-card "+(border_color)+" "+(this.get('class'))+"' "+(this.css())+"> "+(title)+" <div class='core-card-body "+(text_color)+"'> "+(this.content)+" </div> </div>";
});

Render.on("card-image", function(){
    let border_color = '';
    let text_color = '';
    let image_top = '<img src="'+this.src+'" class="core-card-img" alt="'+this.alt+'">';
    let image_bottom = '';
    if (this.color){
        let list_color = ["primary", "secondary", "success", "danger", "warning", "info", "light", "dark"];
        if(list_color.includes(this.color)){
            border_color = "core-card-border-"+this.color;
            text_color = "core-card-text-"+this.color;
        }
    }

    if(this.position && this.position == 'bottom'){
        image_bottom = image_top;
        image_top = '';
    }

    return "<div class='core-card "+(border_color)+" "+(this.get('class'))+"' "+(this.css())+"> "+(image_top)+" <div class='core-card-body "+(text_color)+"'> "+(this.content)+" </div> "+(image_bottom)+" </div>";
});


Render.on("card-content-header", function() {
    var title = this.title || '';
    var meta = this.meta || '';
    if (this.url){
        this.addClass('core-url');
    }
    return "<div class='core-card-item core-semantic-card "+(this.get('class'))+"' "+(this.show('url'))+"> <div class='core-semantic-content'> <div class='core-semantic-header'>"+(title)+"</div> <div class='core-semantic-meta'>"+(meta)+"</div> <div class='core-semantic-description'> "+(this.content)+" </div> </div> </div> ";
})

Render.on('cards', function() {
    return "<div class='core-cards'>"+(this.content)+"</div>";
});



Render.on("actions", function(){
	if (this.borderless){
		this.addClass("-borderless");
	}
	
	if (this.cta){
		this.addClass("-cta");
	}
	
	this.addSizingClass();
	
	return "<div class='core-actions core-clear-fix "+(this.get('class'))+"' "+(this.css())+" "+(this.show('id'))+">"+(this.content)+"</div>";
	
}, function(params){
	
	if (params.auto_active){
		$(this).find(".core-action").setActiveURL();
	}
	
});


Render.on("action", function(){
	var label = this.title;
	if (!label){
		label = this.label;
	}
	
	if (!label){
		label='';
	}
	
	var prefix = '';
	var suffix = '';
	
	if (this.more){
		this.dd=1;
	}
	
	if (this.dd){
		this.addClass("-pdd -cmenuw");
		suffix="<span class='-ap icon-chevron-down2'></span>";
	}
	
	if (this.icon || this.svg){
		prefix = "<div class='-icon'>"+(Render.helper.getIcon(this))+"</div>";
		this.addClass("-picon");
	}
	
	if (this.icon || this.svg){
		prefix = "<div class='-icon'>"+(Render.helper.getIcon(this))+"</div>";
		this.addClass("-picon");
	}
	
	if (this.right_icon){
		suffix = "<div class='-ricon'>"+(Render.helper.getIconByName(this.right_icon))+"</div>";
		this.addClass("-pricon");
	}
	
	if (this.upper){
		this.addClass("-uppercase");
	}
	
	if (this.link){
		this.addClass("-link");
	}
	
	if (this.danger){
		this.addClass("-danger");
	}
	
	if (this.disabled){
		this.addClass("-disabled");
	}
	
	if (this.subtle){
		this.addClass("-subtle");
	}
	
	if (this.cta){
		this.addClass("-cta");
	}
	
	if (this.url || this.urlparam){
		this.addClass("core-url");
	}
	
	if (this.active){
		this.addClass("-active");
	}
	
	if (this.inline){
		this.addClass("-inline");
	}
	
	if (this.icon_only){
		this.addClass("-icon-only");
	}
	
	this.addSizingClass();
	
	return "<div class='core-action "+(this.get('class'))+"' "+(this.show('url'))+" "+(this.showData('urlparam'))+" "+(this.showData('value'))+" "+(this.showAllData())+"> "+(prefix)+" <span class='-txt'>"+(label)+"</span> "+(suffix)+" "+(this.content)+" </div>";
	
});


Render.on("list", function(){
	if (this.borderless){
		this.addClass("-borderless");
	}
	
	if (this.comfort){
		this.addClass("-comfort");
	}
	
	if (this.sortable){
		this.addClass("-sortable");
	}
	
	if (this.compact){
		this.addClass("-compact");
	}

	return "<div class='core-list "+(this.get('class'))+"' "+(this.css())+" "+(this.show('id'))+"> <div class='core-list-items'> "+(this.content)+" </div> </div>";
});

Render.on("list-item", function(){
	var icon = '';
	if (this.icon){
		this.addClass("-picon");
		if (this.icon=="1" || this.icon==1){
		}else{
			icon = "<div class='core-list-icon'><div class='-icon'>"+(Render.helper.getIcon(this))+"</div></div>";
		}
	}

	if (this.url){
		this.addClass("url");
	}

	if (this.no_padding) {
		this.addClass('-no-padding');
	}

	if (this.no_border_bottom) {
		this.addClass('-no-border-bottom');
	}

	if (this.checkbox) {
		this.addClass('-checkbox-item');
	}
	
	return "<div class='core-list-item "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.show('url'))+" "+(this.showAllData())+"><div class='core-li-container' "+(this.css())+"> "+(icon)+" "+(this.content)+" </div></div>";
});


Render.on("special-tag", function(){
	if (this.url){
		this.addClass("core-url");
	}
	
	if (this.noticable || this.edge){
		this.addClass("-noticable -edge");
	}
	
	if (this.circled){
		this.addClass("-circled");
	}
	
	this.addSizingClass();
	this.addStatusColor();
	
	if (this.color){
		var color = Render.helper.getColor(this.color);
		
		if (this.subtle){
			this.css("color", Color.adjust(color, 30, 30));
			if (this.no_fill){
				this.css("border", "1px solid "+(Color.rgba(color, 0.25))+"");	
			}else{
				this.css("background-color", Color.rgba(color, 0.15));	
			}
		}else{
			this.css("color", '#fff');
			this.css("background-color", Color.adjust(color, 10, 10));	
		}
	}

	if (this.inline) {
		this.addClass("inline");
	}
	
	return "<div class='core-special-tag "+(this.get('class'))+"' "+(this.show('url'))+" "+(this.showHTMLSemantics())+" "+(this.css())+">"+(this.label||'')+""+(this.content)+"</div>";
});


Render.on("badge-basic", function(){
    var color = '';
    var content = this.content;
    var notify = '';
    var list_color = ["primary", "secondary", "success", "danger", "warning", "info", "light", "dark"];
    if (this.color && list_color.includes(this.color)){
        color = "core-badge-"+this.color;
        if(this.color == "warning" || this.color == "info" || this.color == "light"){
            color += " core-badge-text-dark";
        }
    }else{
        color = "core-badge-default";
    }

    if (this.icon){
        if(this.icon_position && this.icon_position == "right"){
            content = this.content +' '+ Render.helper.getIcon(this);
        }else{
            content = Render.helper.getIcon(this) +' '+ this.content;
        }
    }

    if(this.size){
        this.css("font-size", this.size+'px;');
    }

    if(this.notify){
        notify += '<span class="core-badge-notify';
        if(this.notify_color && list_color.includes(this.notify_color)){
            notify += " core-badge-"+this.notify_color;
            if(this.notify_color == "warning" || this.notify_color == "info" || this.notify_color == "light"){
                notify += " core-badge-text-dark";
            }
        }else{
            notify += " core-badge-danger";
        }
        notify += '">'+this.notify+'</span>';
    }
    return "<span class='core-badge "+(color)+" "+(this.get('class'))+"' "+(this.css())+"> "+(content)+""+(notify)+" </span>";
});


Render.on("cols", function(){
	if (this.col){
		this.addClass("-col-"+this.col);
	}
	
	if (this.space || this.gap || this.padding){
		this.addClass("-spacing");
	}
	
	return "<div class='core-flex-cols "+(this.get('class'))+"' "+(this.css())+" "+(this.show('id'))+">"+(this.content)+"</div>";
}, function(params){
	if (params.equal){
		var len =$(this).children().length;
		
		$(this).children().each(function(){
			$(this).css("width", (100/len)+"%");
		});
	}
});

Render.on("col", function(){
	if (this.top){
		if (this.top < 0){
			this.css('margin-top', this.top+'px');
		}else{
			this.css('padding-top', this.top+'px');	
		}
		
	}
	
	if (this.left){
		this.css('padding-left', this.left+'px');
	}
	
	if (this.right){
		this.css('padding-right', this.right+'px');
	}
	
	if (this.width){
		this.css('width', this.width+'px');
	}
	
	if (this.fit){
		this.addClass("-fit");
	}
	
	var title = "";
	if (this.title){
		title = "<div class='core-col-title'>"+(this.title)+"</div>";
	}
	
	return "<div class='core-col "+(this.get('class'))+"' "+(this.css())+"> <div class='-bc-inner'>"+(title)+""+(this.content)+"</div> </div>";
});


Render.on("switch-basic", function(){
    var checked = '';
    var text_on = '';
    var text_off = '';
    var nochecked = '';
    if(this.checked){
        checked = 'checked';
        nochecked = '';
    }else{
        checked = '';
        nochecked = 'checked';
    }

    if(this.size){
        this.css("font-size", this.size+'px;');
    }

    if(this.text_on){
        text_on = this.text_on;
    }else{
        text_on = 'YES';
    }

    if(this.text_off){
        text_off = this.text_off;
    }else{
        text_off = 'NO';
    }
    return "<div class='core-switch-input-group "+(this.get('class'))+"' "+(this.css())+"> <span class='core-switch'> <input id='"+(this.name_switch)+"_1' class='core-switch core-switch-button' name='"+(this.name_switch)+"' value='0' "+(nochecked)+" type='radio'> <label for='"+(this.name_switch)+"_1'>"+(text_off)+"</label> <input id='"+(this.name_switch)+"_2' class='core-switch core-switch-button' name='"+(this.name_switch)+"' value='1' "+(checked)+" type='radio'> <label for='"+(this.name_switch)+"_2'>"+(text_on)+"</label> <span class='core-switch-slide-button'></span> </span> </div>";
});

Render.on("radio-group", function() {
    var label = '';
    var name_radio = this._name;
    var value_checked_radio = this.value;
    if (this.label) {
        label = "<div class='core-radio-group-title'>"+(this.label)+"</div>";
    }
    if (this.gray) {
        this.addClass('-gray');
    }
    if (this.borderless) {
        this.addClass('-borderless');
    }
    var items_html = AP.render(this.items, function(item) {
        var img = '';
        var checked = item.value == value_checked_radio ? 'checked' : '';
        var disabled = item.disable ? 'disabled' : '';
        var highlight = '';
        if (item.img) {
            img = "<img src='"+(item.img)+"'/>";
        }
        if (item.highlight) {
            highlight = "<div class='-highlight'>"+(item.highlight)+"</div>";
        }
        return "<label class='core-radio-group-item "+(item.classes || '')+"' for='"+(item.title)+"'> <input type='radio' "+(checked)+" "+(disabled)+" id='"+(item.title)+"' name='"+(name_radio)+"' value='"+(item.value)+"'/> <div class='content'> "+(img)+" <div class='details'> <span>"+(item.title)+"</span> <p>"+(item.desc)+"</p> </div> "+(highlight)+" </div> </label> ";
    });
    return "<div class='core-radio-group "+(this.get('class'))+"' "+(this.css())+" "+(this.show('id'))+"> "+(label)+" "+(items_html)+" </div> ";
});

Render.on("radio-image", function() {
    var label = '';
    if (this.label) {
        label = "<div class='core-radio-image-title'>"+(this.label)+"</div>";
    }
    var name_radio = this.name;
    var value_checked_radio = this.value;
    var image_size_style = '';
    var min_height = '';
    if (this.size) {
        image_size_style = " flex-basis: calc("+(this.size)+"% - 12px); ";
    }
    if (this.min_height) {
        min_height = " min-height: "+(this.min_height)+"px; ";
    }

    var items_html = AP.render(this.items, function (item) {
        var checked = item.id == value_checked_radio ? 'checked' : '';
        return "<label style='"+(image_size_style)+" "+(min_height)+"' class='core-radio-image-item "+(item.classes || '')+"' for='image-"+(item.id)+"'> <input type='radio' "+(checked)+" id='image-"+(item.id)+"' name='"+(name_radio)+"' value='"+(item.id)+"'/> <img src='"+(item.link)+"'/> </label> ";
    });
    return "<div id='"+(this.id)+"' class='core-radio-image "+(this.get('class'))+"' "+(this.css())+"> "+(label)+" "+(items_html)+" </div> ";
});

Render.on("checkbox-image", function() {
    var label = '';
    if (this.label) {
        label = "<div class='core-checkbox-image-title'>"+(this.label)+"</div>";
    }
    var name_checkbox = this.namme;
    var value_checked = this.value;
    var image_size_style = '';
    var min_height = '';
    if (this.size) {
        image_size_style = " flex-basis: calc("+(this.size)+"% - 12px); ";
    }
    if (this.min_height) {
        min_height = " min-height: "+(this.min_height)+"px; ";
    }

    var items_html = AP.render(this.items, function (item) {
        var checked = value_checked.indexOf(item.id) === -1 ? '' : 'checked';
        return "<label style='"+(image_size_style)+" "+(min_height)+"' class='core-checkbox-image-item "+(item.classes || '')+"' for='image-"+(item.id)+"'> <input type='checkbox' "+(checked)+" id='image-"+(item.id)+"' name='"+(name_checkbox+'['+item.id+']')+"' value='"+(item.id)+"'/> <img src='"+(item.link)+"'/> </label> ";
    });
    return "<div id='"+(this.id)+"' class='core-checkbox-image "+(this.get('class'))+"' "+(this.css())+"> "+(label)+" "+(items_html)+" </div> ";
});



Render.on("uploader-dragdrop", function() {
    var multiple = '';
    if (this.multiple) {
        multiple = 'multiple';
    }
    if (!this.icon) {
        this.icon = 'uploader';
    }
    if (!this.icon_color) {
        this.icon_color = '#1677ff';
    }
    return "<div class='core-upload-wrapper "+(this.get('class'))+"' "+(this.css())+" "+(this.show('id'))+"> <div class='core-upload core-upload-drag'> <span class='core-upload core-upload-btn'> <input type='file' "+(multiple)+" name='"+(this._name)+"'/> <div class='core-upload-drag-container'> <p class='core-upload-drag-icon'> "+(Render.helper.getIcon(this))+" </p> <p class='core-upload-text'>"+(this.label || __('Click or drag file to this area to upload'))+"</p> <p class='core-upload-hint'>"+(this.sublabel || '')+"</p> </div> </span> </div> <div class='core-upload-list core-upload-list-text'></div> </div> ";
}, {
    done: function(params, obj) {
        var $that = $(this);
        $that.find("input[type='file']").change(function() {
            var files = this.files;
            CoreUploader.triggerUpload(params, obj, files);
        });

        $that.bind('dragover drop', function(e) {
            e.stopPropagation();
            e.preventDefault();
            if (e.type == 'drop') {
                CoreUploader.triggerUpload(params, obj, e.originalEvent.dataTransfer.files);
            }
        });
    }
});

var CoreUploader = new function __CoreUploader() {
    this.triggerUpload = function(params, obj, files) {
        if (AP.data.isFunction(obj.callback)) {
            return obj.callback();
        }
    }
}

SVG.extends({
   uploader: "<svg viewBox='0 0 1024 1024' focusable='false' data-icon='inbox' width='1em' height='1em' fill='currentColor' aria-hidden='true'><path d='M885.2 446.3l-.2-.8-112.2-285.1c-5-16.1-19.9-27.2-36.8-27.2H281.2c-17 0-32.1 11.3-36.9 27.6L139.4 443l-.3.7-.2.8c-1.3 4.9-1.7 9.9-1 14.8-.1 1.6-.2 3.2-.2 4.8V830a60.9 60.9 0 0060.8 60.8h627.2c33.5 0 60.8-27.3 60.9-60.8V464.1c0-1.3 0-2.6-.1-3.7.4-4.9 0-9.6-1.3-14.1zm-295.8-43l-.3 15.7c-.8 44.9-31.8 75.1-77.1 75.1-22.1 0-41.1-7.1-54.8-20.6S436 441.2 435.6 419l-.3-15.7H229.5L309 210h399.2l81.7 193.3H589.4zm-375 76.8h157.3c24.3 57.1 76 90.8 140.4 90.8 33.7 0 65-9.4 90.3-27.2 22.2-15.6 39.5-37.4 50.7-63.6h156.5V814H214.4V480.1z'></path></svg>",
});



Render.on("star-rating", function(){
    var classStar = 'core-stars-no-change';
    var input_star = '';

    if(this.change){
        classStar = 'core-stars';
        input_star = '<input type="hidden" name="'+this.name_star+'" value="'+this.value+'">';
    }

    return "<div class='"+(classStar)+" "+(this.get('class'))+"' "+(this.css())+"  data-stars='"+(this.value)+"' "+(this.show('id'))+"> <svg height='25' width='23' class='star rating' data-rating='1'> <polygon points='9.9, 1.1, 3.3, 21.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78' style='fill-rule:nonzero;'/> </svg> <svg height='25' width='23' class='star rating' data-rating='2'> <polygon points='9.9, 1.1, 3.3, 21.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78' style='fill-rule:nonzero;'/> </svg> <svg height='25' width='23' class='star rating' data-rating='3'> <polygon points='9.9, 1.1, 3.3, 21.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78' style='fill-rule:nonzero;'/> </svg> <svg height='25' width='23' class='star rating' data-rating='4'> <polygon points='9.9, 1.1, 3.3, 21.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78' style='fill-rule:nonzero;'/> </svg> <svg height='25' width='23' class='star rating' data-rating='5'> <polygon points='9.9, 1.1, 3.3, 21.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78' style='fill-rule:nonzero;'/> </svg> "+(input_star)+" </div>";
}, function (params) {
    if(params.change){
        var id_element = '#'+this.id;
        $(id_element).find('.star.rating').click(function () {
            $(id_element).attr('data-stars', $(this).data('rating'));
            var name_star = '[name="'+params.name_star+'"]';
            $(id_element).find(name_star).val($(this).data('rating'));
        });
    }
});



Render.on("display-field", function(){
	var value='';
	
	if (this.value){
		value = "<div class='core-field-value'>"+(this.value)+"</div>";
	}
	
	var sublabel = '';
	if (this.sublabel){
		sublabel = "<div class='core-field-sublabel core-ap-xdot' title='"+(this.sublabel)+"'>"+(this.sublabel)+"</div>";
	}
	
	var label = this.field?"<div class='core-field-label'>"+(this.field)+"</div>":'';
	
	var icon='';
	
	if (this.icon){
		icon = "<div class='-icon'>"+(Render.helper.getIcon(this, true))+"</div>";
		this.addClass("-picon");
	}
	
	if (this.width){
		this.css("width", this.width+"px");
	}
	
	var content=this.content?"<div class='core-field-value'>"+(this.content)+"</div>":'';
	
	if (this.fit){
		this.addClass("-fit");
	}

	if (this.horizontal) {
		this.addClass("-horizontal");
	}
	
	return "<div class='core-display-field "+(this.get('class'))+"' "+(this.show('id'))+" data-ui='info-row' "+(this.css())+"> "+(icon)+" "+(label)+" "+(sublabel)+" "+(value)+" "+(content)+" </div>";
});

Render.on("display-fields", function(){
	return "<div class='core-info-rows'> <div class='core-bi-rows-title'>"+(this.title)+"</div> <div class='core-bi-rows'>"+(this.content)+"</div> </div>";
});


Render.on("display-sections", function(){
	return "<div class='core-display-sections core-sections' id='"+(this.id)+"'>"+(this.content)+"</div>";
}, {
    done: function(params) {
        Render.display.groupSections();
    }
});

Render.on("display-obj", function(){	
	if (this.dialog){
		return "<div class='core-display-obj core-display-obj-dx "+(this.get('class'))+"' "+(this.show('id'))+"> "+(this.content)+" </div>";	
	}else if (this.with_sidebar){
		return "<div class='core-display-obj-with-sidebar "+(this.get('class'))+"' "+(this.show('id'))+"> <div class='core-do-wrapper core-clear-fix'>"+(this.content)+"</div> </div>";	
	}else if (this.multi || this.fs){
		if (this.compact){
			this.addClass("-compact");
		}
		
		if (this.darken || this.fs){
			this.addClass("-darken");
		}
		
		return "<div class='core-display-obj-multi -fs "+(this.get('class'))+"' "+(this.show('id'))+"> "+(this.content)+" </div>";
	}else{
		if (this.connected){
			this.addClass("-connected");
		}
		return "<div class='core-display-obj "+(this.get('class'))+"' "+(this.show('id'))+"> "+(this.content)+" </div>";
	}
}, {
	done: function(params){
		if (params.multi || params.fs){
			return Render.display.fs(this, params);
		}else if (params.with_sidebar){
			return Render.display.withSidebar(this, params);
		}else if (params.dialog){
			return Render.display.dialog(this, params);
		}
	}
});

Render.on("display-sidebar", function(){
	return "<div class='core-display-sidebar' "+(this.show('id'))+"> "+(this.content)+" </div>";
});

Render.on("display-main", function(){
	return "<div class='core-display-main' "+(this.show('id'))+"> "+(this.content)+" </div>";
});

Render.on("display-header", function(){
	var title=this.title?("<div class='core-title'>"+(this.title)+"</div>"):'';
	
	return "<div class='core-display-header "+(this.show('class'))+"' "+(this.show('id'))+"> <div class='-close' onclick='Core.load.closeFS();'><span class='-icon-svg'>"+(SVG.chevron_left)+"</span></div> "+(title)+" "+(this.content)+" </div>";
});

Render.on("display-cover", function(){
	var icon='';
	if (this.icon || this.svg){
		icon="<div class='core-cover-icon'>"+(Render.helper.getIcon(this))+"</div>";
		this.addClass("-picon");
	}
	
	if (this.avatar){
		if (this.avatar=="1" || this.avatar==1){
			
		}else{
			
		}
		
		this.addClass("-pavatar");
	}
	
	var bg='';
	if (this.bg){
		bg="<div class='core-dc-cover'><img src='"+(this.bg)+"'/></div>";
	}
	
	return "<div class='core-display-cover"+(this.special?'-special':'')+""+(this.exchange?'-exchange':'')+" "+(this.get('class'))+"' "+(this.css())+"> "+(bg)+" "+(icon)+" "+(this.content)+" </div>";
});

Render.on("display-section-connector", function(){
	return "<div class='core-section-connector'>"+(this.content)+"</div>";
});


Render.on("display-section", function(){
	var header = "<div class='core-header'> <div class='core-title'>"+(this.title)+"</div> </div>";
	
	if (!this.title){
		header = '';
	}
	
	if (this.icon){
		this.data_icon=this.icon;
	}
	
	if (this.active){
		this.addClass("core-active");
	}
	
	var html = ""+(header)+" <div class='core-body'>"+(this.content)+"</div>";
	
	if (this.float){
		html =  "<div class='core-section-inner'>"+(html)+"</div>"
	}
	
	return "<div class='core-section core-display-section "+(this.get('class'))+"' "+(this.showAllData())+" "+(this.showData('title'))+" "+(this.show('id'))+" "+(this.css())+"> "+(html)+" </div>";
	
});

Render.display = new function __RenderDisplay(){
	this.fs = function(canvas, params){
		setTimeout(function(){
			render();
		});
	};

	this.withSidebar = function(canvas, params){
		setTimeout(function(){
			renderWithSidebar(canvas, params);
		});
	};
	
	this.dialog = function(canvas, params){
		setTimeout(function(){
			renderDialog(canvas, params);
		});
	}


	function render(){
		if (!$("#core-master-fs .core-display-sidebar .core-section.core-active").length){
			$("#core-master-fs .core-display-sidebar .core-section").eq(0).addClass("core-active");
		}
		
		var tabs = [];
		$("#core-master-fs .core-display-sidebar .core-section").each(function(){
			var uuid = AP.uuid();
			$(this).addClass("core-js-"+uuid);
			tabs.push({
				title: $(this).data("tab")||$(this).data("title"),
				uuid: uuid,
				icon: $(this).data("icon"),
				active: $(this).hasClass("core-active")
			});
		});
		
		var tabs_html = AP.render(tabs, function(e){
			return "<div class='core-icon core-js-icon-tab "+(e.active?'core-active':'')+"' data-tab='"+(e.uuid)+"' title='"+(e.title)+"'>"+(SVG[e.icon])+"</div>";
		});
		
		var html = "<div class='core-display-controls'> <div class='core-area'><div class='core-icon -close' onclick='Core.load.closeFS();'><span class='-icon-svg'>"+(SVG.close)+"</span></div></div> <div class='core-area'> "+(tabs_html)+" </div> </div>";
		
		$("#core-master-fs .core-display-obj-multi.-fs").append(html);
		
		$("#core-master-fs .core-display-controls .core-js-icon-tab").on("click", function(){
			$(this).siblings().removeClass("core-active");
			$(this).addClass("core-active");
			var uuid=$(this).data("tab");
			$("#core-master-fs .core-display-sidebar .core-section").removeClass("active").setActive(".core-js-"+uuid);
			
			setSidebarTitle();
		});
		
		
		$("#core-master-fs .core-display-sidebar").wrapInner("<div class='core-display-sidebar-scroller' data-autohide='1' data-autoscroll='1'></div>");
		$("#core-master-fs .core-display-sidebar").prepend("<div class='core-sidebar-header'></div>");
		Layout.scrollable("#core-master-fs .core-display-sidebar-scroller");
		
		
		$("#core-master-fs .core-display-obj").wrap("<div class='core-display-obj-scroller core-scroll-y core-forced-scroll'></div>");
		if (!$("#core-master-fs .core-display-header").length){
			$("#core-master-fs .core-display-obj-scroller").css({top: 0});
		}
		
		setSidebarTitle();
		
		Render.display.groupSections("#core-master-fs .core-display-main .core-display-obj");
	};

	function setSidebarTitle(){
		var title=$("#core-master-fs .core-display-sidebar .core-section.core-active .core-header").first().text();
		$("#core-master-fs .core-display-sidebar .core-sidebar-header").html($.trim(title));
	};

	this.groupSections = function(){
		$(".core-sections").addClass("-bs-connected").each(function(){
			var tabs=[];
			$(this).find(".core-section, .core-section").each(function(){
				$(this).addClass("core-js-section");
				
				var ref=AP.uuid();
				var tab=$(this).data("tab");
				
				if (!tab){
					tab = safe($(this).find(".core-header .core-title").text());
				}
				$(this).addClass("core-js-"+ref);
				tabs.push({ref: ref, tab: tab});
				$(this).find(".core-header").remove();
			});
			
			$(this).wrapInner("<div class='core-sections-body'></div>");
			var tabs_html = AP.render(tabs, function(t){
				return "<div class='core-tab' data-ref='"+(t.ref)+"'>"+(t.tab)+"</div>";
			});
			
			$(this).prepend("<div class='core-tabs'>"+(tabs_html)+"</div>");
			$(this).find(".core-tabs .core-tab").on("click", function(){
				$(this).siblings().removeClass("core-active");
				$(this).addClass("core-active");
				$(this).closest(".core-sections").find(".core-sections-body .core-js-section").setActive(".core-js-"+$(this).data("ref"));
			});
			
			$(this).find('.core-tabs .core-tab:first').click();
		});
	};
	
};



var SuperTable = new function __SuperTable(){
    this.mdefs = [];
	this.filter = null;

    this.current = function(){
		return SuperTable.cache.model;
	};

	this.model = function(opts){
		if (AP.data.isArray(opts)){
			return new SuperModel({
				models: safeTransform(opts)
			});
		}

		opts.models = safeTransform(opts.models);
		return new SuperModel(opts);
	};

    this.def = function(def){
		def.__permanent = 1;
		def.key = def.key || def.id;
		this.mdefs.push(def);
	};

	this.dynamicDef = function(def){
		def.key = def.key || def.id;
		this.mdefs.push(def);
	};

	this.on = function(id, config){
		config.id = id;
		this.def(config);
	}

    this.getModel = function(model_key){
		return ARR.findObj(SuperTable.mdefs, model_key);
	}

	this.register = this.def;

    function safeTransform(models){
		var ms = [];

		for (var i=0; i<models.length; i++){
			if (AP.data.isObject(models[i])){
				ms.push(models[i].id);
				SuperTable.dynamicDef(models[i]);
			}else{
				ms.push(models[i]);
			}
		}

		return ms;
	}
}

SuperTable.cache = {};


AP.gc(function(){
	SuperTable.mdefs = ARR.filter(SuperTable.mdefs, function(e){
		if (!e.__permanent){
			return false;
		}

		return true;
	});

	SuperTable.mdefs = ARR.unique(SuperTable.mdefs, function(e, f){
		return e.id == f.id;
	});

});

SuperTable.ui = new function __SuperTableUI(){
	this.header = function(model){
		var filters ="";
		var sorter ="";
		var exp = "";
		var ec='';
		if (SuperTable.filter && !model.metatype) {
			var filter = AP.array.findObj(SuperTable.filter.filters, model.id);
			var icon = filter ? SVG.filtered : SVG.filter2;
			filters= "<div class='filter' id='"+(uuid)+"'> <div class='dd'>"+(icon)+"</div> </div>";
		} else if (model.filter && model.options){
			var opts = AP.render(model.options, function(e){
				return "<div class='opt core-ap-xdot core-url "+(activeClass(model.key, e.id))+"' data-urlparam='"+(model.key)+"' data-value='"+(e.id)+"'>"+(e.name)+"</div>";
			});

			opts = "<div class='opt core-ap-xdot core-url "+(activeClass(model.key, null))+"' data-urlparam='"+(model.key)+"' data-value=''>"+(__('No filter'))+"</div>" + opts;

			var title = '';
			if (model.filter_title){
				title = "<div class='-opts-title'>"+(model.filter_title)+"</div>";
			}

			var uuid = AP.uuid();
			var search = '';
			if (model.options && model.options.length>=10){
				search = "  " +Render.render('search', {filter: "#"+(uuid)+" .opt" , placeholder:__('Quick filter'), sm:1}, '')+ '';
			}

			var header = '';
			if (title || search){
				header = "<div class='-opts-header "+(search?'-with-search':'')+"'>"+(search)+""+(title)+"</div>";
			}

			filters= "<div class='filter' id='"+(uuid)+"'> <div class='dd'> " +Render.render('icon', {icon: "ui_filter" , size: "16" }, '')+ "</div> <div class='opts' style='max-height:"+(model.maxHeight||300)+"px'> "+(header)+" <div class='-opts-wrapper'>"+(opts)+"</div> </div> </div>";

			if (Query.get(model.id)){
				ec='-filter-activated';
			}
		}

		if (filters){
			ec+=" -has-filter";
		}

		if (SuperTable.filter && SuperTable.filter.sorting && SuperTable.filter.sorting.model_id == model.id) {
			var icon = SuperTable.filter.sorting.sort == "asc" ? SVG.sort_asc : SVG.sort_desc;
			sorter = "<div class='sorter'> <div class='dd'>"+(icon)+"</div> </div>";
		}

		if (sorter){
			ec+=" -sorted";
		}

		if ('explain' in model){
			exp = "<div class='exp'>"+explain(model.explain, {direction: 'down'})+`</div>`;
		}

		var sc='';

		if (model.sticky_left || model.locked){
			sc='-sticky-left';
		}

		if (model.group){
			sc+=" -ml";
		}else{
			sc+=" -sl";
		}

		var html = "<div class='core-ap-xdot'>"+(model.label||model.name)+"</div>";
		if (model.html){
			html = model.html;
		}

		return "<div class='th "+(sc)+"' data-width='"+(model.width)+"' data-id='"+(model.id)+"' style='width:"+(model.width)+"px'> "+(sorter)+" <div class='cell "+(ec)+"' title='"+(model.label||model.name)+"'> <div class='name'>"+(html)+"</div> "+(exp)+" </div> "+(filters)+" </div>";
	};

	this.headerCB = function(model){
		return "<div class='th "+(model.sticky_left?'-sticky-left':'')+"' data-width='40' data-id='table:checkbox' style='width:40px'> <div class='cell'> <div class='row-checkbox core-url' data-url='::super/table/all-selected'></div> </div> </div>";
	};

	this.gheader = function(cg){
		return "<div class='colgroup' style='left:"+(cg.__st_left)+"px; width:"+(cg.__st_width)+"px'> <div class='cg-inner'>"+(cg.name)+"</div> </div>";
	};

	this.extra = function(table){
		var num_items = table.data.length;
		var ipp = parseInt(table.ipp)||0;

		var num_pages = ipp>0?Math.ceil(num_items/ipp):0;
		var cur_page = Query.getInt("page") || 0;

		if (num_pages <= 1 && !cur_page){
			return "<div class='super-table-extra -es'> <div class='st-pagination'> <div class='stp-total'><em>"+(AP.data.numberFormat(num_items))+"</em> records</div> </div> </div>";
		}

		if (num_pages<=1 && cur_page){
			num_pages=1;
		}

		var pages = AP.render(range(1, num_pages), function(e){
			return "<option value='"+(e)+"'>Page "+(e)+"</option>";
		});

		var extra = "<div class='super-table-extra'> <div class='st-pagination'> <div class='stp -left'><span class='-ap icon-chevron-left22'></span></div> <div class='stp-total'><em>"+(AP.data.numberFormat(num_items))+"</em> records</div> <div class='stp-select'> <select name='q'><option>--</option>"+(pages)+"</select> </div> <div class='stp -right'><span class='-ap icon-chevron-right22'></span></div> </div> </div>";

		return extra;
	};

    this.updatePage = function(val){
		var page = Query.getInt("page");
		if (!page || page<=0){
			page=1;
		}

		page = page+val;
		if (!page || page<=0){
			page=1;
		}

		AP.setURLParams({"page": page}, true);
	};

	this.setPage = function(page){
		page = parseInt(page);

		if (!page || page<=0){
			page=1;
		}

		AP.setURLParams({"page": page}, true);
	};

	function activeClass(filter, value){
		var q=Query.get(filter);
		if (!q){
			if (!value){
				return 'active';
			}

			return '';
		}

		if (q==value){
			return 'active';
		}

		return '';
	};
};

function SuperModel(opts){
	this.models = [];
	this.selection = false;
	this.canvas_id = opts.canvas_id || AP.uuid();

	this.index= opts.index||null;
	this.setClass = opts.setClass||null;

	for (var i=0; i<opts.models.length; i++){
		var m = ARR.findObj(SuperTable.mdefs, opts.models[i]);
		if (m){
			m.superModel = function(){
				return SuperTable.cache.model;
			}

			this.models.push(m);
		}else{
			var df = {
				id: opts.models[i],
				key: opts.models[i],
				width: 130,
				label: opts.models[i].toUpperCase(),
				render: function(obj, md){
					var id = md.id;
					if (obj[id]){
						val=obj[id];
					}else{
						val= "  " +Render.render('none', {}, "---")+ '';
					}

					return "  " +Render.render('super_cell', {top: "11" , fit:1}, ""+(val)+"")+ '';
				},
				filter: "string"
			};

			this.models.push(df);
		}
	}

	this.width = function(){
		var w=0;

		for (var i=0; i<this.models.length; i++){
			w+= (this.models[i].width||130);
		}

		if (this.selection){
			w+=40;
		}

		return w;
	};

	this.prepareRender = function(){
		var w=0;

		if (this.selection){
			w=40;
		}

		for (var i=0; i<this.models.length; i++){
			w+= (this.models[i].width||130);
			this.models[i].marginLeft = w;

			if (this.models[i].sticky_left || this.models[i].locked){
				this.sticky_left=1;
			}
		}
	};


	this.getRowHTML = function(row){
		var cells = AP.render(this.models, function(m){
			return getCellHTML(m, row);
		});

		if (this.selection){
			cells = getRowCheckbox(row, this) + cells;
		}

		var cx = '';
		if (this.setClass){
			cx = this.setClass(row);
		}

		return "  " +Render.render('super_row', {data_id:row.id, data_index:this.getIndex(row), _class:cx}, ""+(cells)+"")+ '';
	};


	this.getIndex = function(row){
		if (!this.index){
			return '';
		}
		return this.index(row);
	};


	function getCellHTML(model, data){
		var editable = '';
		var ec = '';
		var id = AP.uuid();
		var qe = '';

		if ('editable' in model){
			if (AP.data.isFunction(model.editable)){
				var temp = model.editable(data);
				if (temp && AP.data.isObject(temp) && temp instanceof ActionManager){
					temp = temp.release();
				}

				if (!temp || !AP.data.isObject(temp)){
					if (AP.data.isString(temp)){
						editable = "<div class='cell-edit core-url' title='"+(__('Edit'))+"' id='"+(id)+"' data-url='"+(temp)+"'>"+(SVG.form_edit)+"</div>";
					}else{
						editable='';
					}
				}else if (AP.data.isArray(temp)){
					if (temp.length == 1){
						editable = "<div class='cell-edit core-url' title='"+(temp[0].label)+"' id='"+(id)+"' data-url='"+(temp[0].url)+"'>"+(SVG.form_edit)+"</div>";
					}else{
						var opts = AP.render(temp, function(opt){
							if (!opt){
								return '';
							}

							if (opt === "---" || opt === "sep"){
								return "  " +Render.render('cmenu_item', {sep:1}, '')+ '';
							}

							if (opt.style == 'red') {
								return "  " +Render.render('cmenu_item', {_class: "core-red" , url:opt.url}, ""+(opt.label)+"")+ '';
							}

							return "  " +Render.render('cmenu_item', {url:opt.url}, ""+(opt.label)+"")+ '';
						});

						editable = "<div class='cell-edit -cmenuw core-url' id='"+(id)+"' data-url=':active'>"+(SVG.form_edit)+" " +Render.render('cmenu', {}, ""+(opts)+"")+ "</div>";
					}
				}else{
					if (temp.quick_edit){
						qe=1;
					}

					editable = "<div class='-qe-edit core-url' data-url='::super/table/inline-edit' data-ref_id='"+(id)+"'></div> <div class='cell-edit unselectable core-url' id='"+(id)+"' data-ref_id='"+(id)+"' data-url='::super/table/inline-edit'>"+(SVG.form_edit)+"</div>";
				}
			}else if (parseInt(model.editable)){
				editable = "<div class='cell-edit unselectable core-url' id='"+(id)+"' data-url='::super/table/inline-edit'>"+(SVG.form_edit)+"</div>";
			}
		}

		var pad = 0;
		if (model.sticky_left || model.locked){
			pad = model.marginLeft;
		}

		var cx = ""+(editable?'-editable-cell':'')+" "+(ec)+"";

		return "  " +Render.render('super_cell_wrapper', {width:model.width, sticky_left:model.sticky_left||model.locked||0, sticky_margin:pad, _class:cx, qe:qe}, ""+(model.render(data, model))+" "+(editable)+"")+ '';
	};


	function getRowCheckbox(row, model){
		return "  " +Render.render('super_cell_wrapper', {width: "40" , sticky_left:model.sticky_left?1:0}, '' +Render.render('super_row_checkbox', {}, '')+ '')+ '';
	};
};

SuperTable.inline = new function __SuperTableInline(){
	this.init=function(canvas){
		$(canvas).prepend("<div id='board-ie'></div>");
		$(canvas).find(".super-table-wrapper").on("scroll", function(){
			var sleft = $(this).scrollLeft();
			var stop = $(this).scrollTop();

			$("#board-ie").css("left", -sleft);
			$("#board-ie").css("top", -stop);
		});

		$(canvas).click(function(e){
			if ($(e.target).closest(".ie").length || $(e.target).closest(".iedit").length){
			}
		});
	};

	this.trigger=function(event, ref, qs){
		if (event=="inline-edit"){
			if ($(ref).data("ref_id") && $("#board-ie").data("ref_id")==$(ref).data("ref_id")){
				closeIE();
			}else{
				activate(ref);
			}

			return;
		}

		if (event=="inline-save"){
			return saveText(ref);
		}

		if (event=="inline-cancel"){
			return closeIE();
		}

		if (event=="inline-opt"){
			if (qs.multiple && parseInt(qs.multiple)){

			}

			return saveListItem(ref);
		}
	};


	this.context=function(am, pos){
		var html=am.text();
		$("#board-ie")
	};

	function saveText(ref, cell){
		Form.submitFrom(ref, function(code){
			$(ref).closest("form").find("textarea").css("min-height", "33px");

			if (!code.good()){
				return AP.alertError(code.message);
			}

			var id = "#"+$("#board-ie").data("ref_id");
			var header = getHeaderByRef(id);
			var row_id = $(id).closest(".super-row").data("id");
			var old_obj = ARR.findObj(SuperTable.cache.data, row_id);

			if (header && header.editable && AP.data.isFunction(header.editable) && old_obj){
				var temp_fx = header.editable(old_obj);
				if (temp_fx){
					temp_fx.success.apply(code, [header, $(id).closest(".super-cell-wrapper").find(".super-cell").first(), SuperTable.cache.data]);
				}
			}

			closeIE();

		});
	};

	function saveListItem(ref){
		var $box = $(ref).closest(".dd.scroll-y");
		if (!$box.length){
			return;
		}

		var value = "";
		if ($box.data("multiple")){
			$(ref).toggleClass("-selected");
			$box.find(".opt").each(function(){
				if ($(this).hasClass("-selected")){
					value+=","+$(this).data("value");
				}
			});
		}else{
			value = $(ref).data("value");
		}

		$(ref).closest("form").find("input[name=value]").val(value);

		Form.submitFrom(ref, function(code){
			if (!code.good()){
				return AP.alertError(code.message);
			}

			var id = "#"+$("#board-ie").data("ref_id");
			var header = getHeaderByRef(id);
			var row_id = $(id).closest(".super-row").data("id");
			var old_obj = ARR.findObj(SuperTable.cache.data, row_id);

			if (header && header.editable && AP.data.isFunction(header.editable) && old_obj){
				var temp_fx = header.editable(old_obj);
				if (temp_fx){
					temp_fx.success.apply(code, [header, $(id).closest(".super-cell-wrapper").find(".super-cell").first(), SuperTable.cache.data]);
				}
			}

			if ($box.data("multiple")){

			}else{
				closeIE();
			}
		});
	};

	function getPosition(e){
		var top=e.pageY;
		var left=e.pageX;

		return {top: top, left: left}
	};

	function activate(ref){
		var $cell=$(ref).closest(".super-cell-wrapper");
		var $row = $cell.closest(".super-row");
		$row.siblings().removeClass("-selected");
		$row.addClass("-selected");


		var cell_index = $cell.index();
		var $header_cell = $(ref).closest(".super-table").find(".thead").find(".th:nth-child("+(cell_index+1)+")");

		if (!$header_cell.length){
			return;
		}

		var key=$header_cell.data("id");
		var header = getHeader(key);

		var obj = ARR.findObj(SuperTable.cache.data, $row.data("id"));

		if (!header || !obj){
			return;
		}

		var computed = header.editable(obj);

		if (AP.data.isArray(computed)){
			return;

		}else if (computed.type == "select"){
			var value = computed.value;

			var select_options = computed.options;
			if (!select_options){
				select_options = header.options;
			}

			if (computed.empty){
				select_options = ARR.clone(select_options);
				select_options.push({id: "", name: "-- <i>"+(computed.empty)+"</i> --"});
			}

			var html=AP.render(select_options, function(e){
				var selected='';

				if (typeof value!='undefined'){
					if (computed.multiple){
						if (ARR.contain(value, e.id, function(v, eid){
							return AP.data.equal(v, eid);
						})){
							selected=' -selected';
						}
					}else{
						if (e.id==value || (AP.data.isInt(e.id) && AP.data.isInt(value) && parseInt(e.id)==parseInt(value))){
							selected=' -selected';
						}
					}
				}

				return "<div class='opt core-ap-xdot core-url "+(selected)+" "+(computed.multiple?'':'-singular')+"' title='"+(safe(e.name))+"' data-value='"+(e.id)+"' data-url='::super/table/inline-opt?multiple="+(computed.multiple?1:0)+"'>"+(e.name)+"</div>";
			});

			var id=$row.data("id");
			var submit_multi = '';

			html="<div class='dd scroll-y' data-col='"+(key)+"' data-row='"+(id)+"' data-multiple='"+(computed.multiple?1:0)+"'> <div class='ie-scroll-list'> "+(html)+" </div> </div> <div class='ie-footer'> "+(submit_multi)+" <span class='core-url' data-url='::super/table/inline-cancel'>{{Close}}</span> </div>";

			var opts = {
				top: $row.position().top+$cell.height(),
				left: $cell.position().left+$cell.width()-180,
				html: html,
				items: header.options,
				ref: $(ref).data("ref"),
				position: {col: key, row: $row.data("id"), row_index: $row.index()},
				ref_id: $(ref).data("ref_id")
			};

			for (var tkey in computed){
				if (!(tkey in opts)){
					opts[tkey]=computed[tkey];
				}
			}

			showSelect(opts);
		}else{
			var w=$cell.width();
			if (w<200){
				w=200;
			}

			var opts={
				top: $row.position().top,
				left: $cell.position().left,
				width: w,
				ref: $(ref).data("ref"),
				placeholder: header.label||header.name,
				value: computed.value,
				data: computed.data,
				position: {col: key, row: $row.data("id"), row_index: $row.index()},
				ref_id: $(ref).attr("id")
			};

			var index = $row.index();

			for (var tkey in computed){
				if (!(tkey in opts)){
					opts[tkey]=computed[tkey];
				}
			}

			showInput(opts);
		}
	};

	function showSelect(opts){
		var top=opts.top;
		var left=opts.left;

		var html=opts.html;
		if (opts.options && opts.options.length>5){
			html="<div class='ie-filter'> " +Render.render('search', {filter: "#board-ie .opt" , placeholder: "Filter options" }, '')+ ''+html;
		}

		var data = '';
		if (opts.data){
			for (var key in opts.data){
				data+="<input type='hidden' name='"+(key)+"' value='"+(opts.data[key])+"'/>";
			}
		}

		html="<div class='dd-scrollbox'> <form method='POST' action='"+(opts.action)+"'> "+(html)+" <div class='hidden'> <input type='hidden' name='key' value='"+(opts.position.col)+"'/> <input type='hidden' name='value' value='"+(opts.value||'')+"'/> "+(data)+" </div> </form> </div>";

		$("#board-ie").html("<div class='ie' style='top:"+(top)+"px; left:"+(left)+"px'>"+(html)+"</div>").show().data("ref_id", opts.ref_id);
		makeVisible("#board-ie");
		Render.finish();
	};

	function showInput(opts){
		var top=opts.top;
		var left=opts.left;
		var data = '';
		if (opts.data){
			for (var key in opts.data){
				data+="<input type='hidden' name='"+(key)+"' value='"+(opts.data[key])+"'/>";
			}
		}

		var val = opts.value||'';

		if (val && opts.tag){
			var u = People.get(val);
			if (u && !u.error){
				val='@'+u.username;
			}
		}


		var html="<form method='POST' action='"+(opts.action)+"'> <div class='textarea'> <textarea placeholder='"+(opts.placeholder)+"' data-role='"+(opts.tag?'tag':'')+"' name='value' data-value='"+(val)+"' data-col='"+(opts.position.col)+"' data-row='"+(opts.position.row)+"'></textarea> </div> <div class='hidden'> <input type='hidden' name='key' value='"+(opts.position.col)+"'/> "+(data)+" </div> <div class='actions'> <div class='action js-ib save core-url' data-url='::super/table/inline-save'><span>&#10003;</span> {{Save}}</div> <div class='action js-ib cancel core-url' data-url='::super/table/inline-cancel'><span>&#10006;</span> {{Cancel}}</div> </div> </form>";

		$("#board-ie").html("<div class='ie' style='top:"+(top)+"px; left:"+(left)+"px'><div class='ibox' style='width:"+(opts.width)+"px'>"+(html)+"</div></div>").show().data("ref_id", opts.ref_id);
		makeVisible("#board-ie");
		Form.render("#board-ie .textarea");

		$("#board-ie textarea").focus().val(val).enter(function(){
			SuperTable.inline.trigger("inline-save", this);
		});
	};

	function getHeader(key){
		return ARR.single(SuperTable.mdefs, function(e){
			return e.id == key;
		});
	};

	function getHeaderByRef(ref){
		var $cell=$(ref).closest(".super-cell-wrapper");
		var cell_index = $cell.index();
		var $header_cell = $(ref).closest(".super-table").find(".thead").find(".th:nth-child("+(cell_index+1)+")");

		if (!$header_cell.length){
			return;
		}

		var key=$header_cell.data("id");
		return getHeader(key);
	};

	function initContextMenu(canvas){
		$(canvas+" .tbody").on("contextmenu", function(e){
			if (e.ctrlKey){
				return;
			}

			e.preventDefault();

			var $row=$(e.target).closest(".js-row");
			var obj=AP.array.findObj(Board.table.opts.rows, $row.data("id"));

			if (obj){
				Board.context(obj, getPosition(e));
			}
		});
	};

	function makeVisible(box){
		var $canvas = $(box).closest(".super-table-canvas");
		var $ie = $(box).find(".ie");
		var top = $ie.position().top;
		var height = $ie.find("form").height();
		var sh = $canvas.find(".super-table-wrapper")[0].scrollHeight;

		if (top + height > sh){
			top = sh - height;
			$ie.css({"top": top});
		}

		return;
	};

	function closeIE(){
		$("#board-ie").hide().data("ref_id", 0);
		$("#board-ie").closest(".super-table-canvas").find(".super-row").removeClass("-selected");
	};
};

SuperTable.selection = new function __SuperTableSelection(){
	this.get = function(){
		var model = SuperTable.cache.model;
		var data = SuperTable.cache.data;

		var r = {
			model: model,
			ids: [],
			items: []
		};

		var $items = $("#"+model.canvas_id+" .super-row.-is-selected");
		$items.each(function(){
			var id = $(this).data("id");
			if (data){
				var obj = ARR.findObj(data, id);
				if (obj){
					r.items.push(obj);
				}
			}

			if (id){
				r.ids.push(id);
			}
		});


		return r;
	};


	this.clicked = function(context, ref){
		var $row = $(ref).closest(".super-row");
		$row.toggleClass("-is-selected");

		var count = $row.closest(".tbody").find(".-is-selected").length;
		var model = SuperTable.cache.model;
		if (model && model.selection){
			var $button = $(model.selection);
			if ($button.length){
				if (count>0){
					$button.find('.-js-scount').html("<b>("+(count)+")</b>");
					$button.show();
				}else{
					$button.hide();
				}
			}
		}
	};

	this.allClicked = function(context, ref) {
		var $row = $(ref).closest(".thead");
		if ($row.hasClass("-is-selected")) {
			$(".super-row").removeClass("-is-selected");
		}else {
			$(".super-row").addClass("-is-selected");
		}
		$row.toggleClass("-is-selected");


		var count = $row.closest(".super-table").find(".tbody").find(".-is-selected").length;
		var model = SuperTable.cache.model;
		if (model && model.selection){
			var $button = $(model.selection);
			if ($button.length){
				if (count>0){
					$button.find('.-js-scount').html("<b>("+(count)+")</b>");
					$button.show();
				}else{
					$button.hide();
				}
			}
		}
	}
};



Render.on("super-table", function(){
	var model = this.model;
	
	if (this.selection){
		model.selection = this.selection;
	}

	SuperTable.filter = this.filter || null;
	
	model.prepareRender();
	var colgroups = this.colgroups||null;
	
	var colgroups_html = '';
	
	if (colgroups){
		for (var i=0; i<colgroups.length; i++){
			colgroups[i].__index = i;
			
			colgroups[i].__st_left = 0;
			colgroups[i].__st_width = 0;
		}
		
		for (var i=0; i<model.models.length; i++){
			if ('group_id' in model.models[i]){
				model.models[i].group = ARR.findObj(colgroups, model.models[i].group_id);
			}
		}
		
		model.models = ARR.sort(model.models, function(m, i){
			if (m.group){
				return 1000 + m.group.__index + 1;
			}
			
			return i;
		});
		
		for (var i=0; i<model.models.length; i++){
			if (model.models[i].group){
				model.models[i].group.__st_width += model.models[i].width;
			}
		}
		
		var __st_left = 0;
		if (this.selection){
			__st_left = 40;
		}
		for (var i=0; i<model.models.length; i++){
			if (model.models[i].group){
				if (!model.models[i].group.__st_left){
					model.models[i].group.__st_left = __st_left;
					__st_left = model.models[i].group.__st_left + model.models[i].group.__st_width;
				}
			}else{
				__st_left = __st_left + model.models[i].width;
			}
		}
		
		colgroups_html = AP.render(colgroups, function(cg){
			if (!cg.__st_width){
				return '';
			}
			
			return SuperTable.ui.gheader(cg); 
		});
		
		colgroups_html = "<div class='colgroups'>"+(colgroups_html)+"</div>";
	}
	
	var headers = AP.render(model.models, function(e){
		return SuperTable.ui.header(e);
	});
	
	if (model.selection){
		headers = SuperTable.ui.headerCB(model) + headers;
	}
	
	this.ipp = parseInt(this.ipp) || 0;

	var rows= '';
	var page = Query.getInt("page") || 1;
	
	
	for (var i=0; i<this.data.length; i++){
		if (this.ipp && (i<(page-1)*this.ipp || i>=page*this.ipp)){
			continue;
		}
		
		rows += model.getRowHTML(this.data[i]);
	}
	
	// HARD-CODED
	SuperTable.cache = {
		data: this.data,
		model: this.model,
		colgroups: this.colgroups
	};
	
	if (this.sticky_header){
		this.addClass("-sticky-header");
	}
	
	if (colgroups){
		this.addClass("-multiple-lines");
	}
	
	return "<div class='super-table-canvas "+(this.get('class'))+"' "+(this.show('id'))+"> "+(SuperTable.ui.extra(this))+" <div class='super-table-wrapper scroll-x scroll-y' id='"+(model.canvas_id)+"'> <div class='super-table' style='width: "+(model.width())+"px'> <div class='thead'>"+(headers)+"</div> "+(colgroups_html)+" <div class='tbody'> "+(rows)+" </div> </div> </div> </div>";
}, {
	done: function(params){
		SuperTable.inline.init("#"+params.id);

		$(this).find(".filter").click(function(){
			if (SuperTable.filter) {
				var ref = $(this).closest(".th");
				SuperTable.filter.render(ref, ref.data("id"));
			}
		});
		
		var $extra = $(this).find(".super-table-extra");
		if ($extra.length){
			$extra.find(".stp.-left").click(function(){
				SuperTable.ui.updatePage(-1);
			});
			
			$extra.find(".stp.-right").click(function(){
				SuperTable.ui.updatePage(1);
			});
			
			$extra.find("select").on("change", function(){
				var v =$(this).val();
				SuperTable.ui.setPage(v);
			});
			
			var cur = Query.getInt("page");
			if (cur){
				$extra.find("select").val(cur);	
			}else{
				$extra.find("select").val(1);
			}
		}
		
		if (params.sticky_header){
			var $header = $(this).find(".super-table-wrapper .thead, .super-table-wrapper .colgroups");
			
			$(this).find(".super-table-wrapper").on("scroll", function(){
				var top = $(this).scrollTop();
				var left = $(this).scrollLeft();
				$header.css("top", top);
				
				$(this).find(".-sticky-left").css({'transform': "translateX("+(left)+"px)"});
			});
		}
		
		if (params.row_class){
			$(this).find(".super-row").addClass(params.row_class);
		}
	}
});



Render.on("super-row", function(){
	return "<div class='super-row "+(this.get('class'))+"' "+(this.showAllData())+" "+(this.show('id'))+">"+(this.content)+"</div>";
});

Render.on("super-cell-wrapper", function(){
	if (this.width){
		this.css("width", this.width+"px");
	}
	
	var extra='';
	
	if (this.sticky_left){
		this.addClass("-sticky-left");
		extra = " data-mleft='"+(this.sticky_margin||'')+"'";
	}
	
	return "<div class='super-cell-wrapper "+(this.get('class'))+"' "+(this.css())+" "+(extra)+" "+(this.show('id'))+">"+(this.content)+"</div>";
}, function(params){
	
});


Render.on("super-row-checkbox", function(){
	return "<div class='row-checkbox-wrapper'> <div class='row-checkbox core-url' data-url='::super/table/selected'></div> </div>";
});


Render.on("super-cell", function(){
	if (this.align){
		this.top=6;
	}
	
	if (this.fit){
		this.addClass('-fit');
	}
	
	if (this.top){
		this.css("padding-top", this.top+"px");
	}
	
	if (this.left){
		this.css("padding-left", this.left+"px");
	}
	
	this.addSizingClass();
	
	var icon='';
	
	if (this.icon){
		this.addClass("-picon");
		if (this.icon!=1){
			icon= "<span class='-cell-icon'>"+(Render.helper.getIcon(this))+"</span>";
		}
	}else if (this.icon_sm){
		this.addClass("-picon-sm");
		icon= "<span class='-cell-icon'>"+(Render.helper.getIcon(this))+"</span>";
	}
	
	if (this.fill){
		this.css("background-color", Color.get(this.fill));
		this.addClass("-fillable");
	}
	
	var content = "<div class='sc-inner core-ap-xdot "+(this.url?' url':'')+"' "+(this.show('url'))+">"+(this.content)+"</div>";
	if (this.url){
		content = "<div class='sc-inner core-ap-xdot'><span class='url' "+(this.show('url'))+">"+(this.content)+"</span></div>";
	}
	
	return "<div class='super-cell "+(this.get('class'))+"' "+(this.css())+" "+(this.showHTMLSemantics())+">"+(icon)+" "+(content)+" </div>";
	
});


Rewrite.on("::super/{entity}/{action}", function(qs){
	if (qs.entity == "table"){
		
		if (qs.action=="inline-edit" || qs.action=="inline-save" || qs.action=="inline-cancel" || qs.action=="inline-opt"){
			return SuperTable.inline.trigger(qs.action, this, qs);
		}
		
		if (qs.action == "selected"){
			return SuperTable.selection.clicked(qs, this, qs);
		}
		
		if (qs.action == "all-selected") {
			return SuperTable.selection.allClicked(qs, this, qs);
		}
	}
});



Render.on(["button-bg","button-outline"], function(){
    var content = this.content;
    var type = 'button';
    var disabled = '';
    var url = '';
    if(this.url){
		url = 'data-url="'+this.url+'"';
	}
    var class_name = this.get('class');
    var class_color = ' core-btn-';
    if(this.name == 'button_outline'){
        class_color = ' core-btn-outline-';
    }
    if(this.disabled){
        disabled = 'disabled';
        class_name += ' core-btn-disabled';
    }
    if(this.type){
        type = this.type;
    }
    if(this.sm){
        class_name += ' core-btn-sm';
    }
    var list_color = ["primary", "secondary", "success", "danger", "warning", "info", "light", "dark"];
    if (this.color && list_color.includes(this.color)){
        class_name += class_color+this.color;
    }else{
        class_name += class_color+"default";
    }

    if (this.icon){
        if(this.icon_position && this.icon_position == "right"){
            content = '<span class="core-btn-text">'+this.content +' </span>'+ Render.helper.getIcon(this);
        }else{
            content = Render.helper.getIcon(this) +'<span class="core-btn-text"> '+ this.content+'</span>';
        }
    }
    return "<button type='"+(type)+"' class='core-btn "+(class_name)+"' "+(this.css())+" "+(disabled)+" "+(url)+">"+(content)+"</button>";
});

Render.on("button-group", function(){
    var data1 = {};
    var data2 = {};
    for(let i in this.data){
        if(i<parseInt(this.group)){
            data1[i] = this.data[i];
        }else{
            data2[i] = this.data[i];
        }
    }
    var html1 = '';
    var html2 = '';
    for(let i in data1){
        if(typeof data1[i].url != 'undefined'){
            html1 += '<button type="button" data-url="'+data1[i].url+'" class="core-btn core-btn-light core-btn-text-dark core-btn-sm core-url">';
        }else{
            html1 += '<button type="button" class="core-btn core-btn-light core-btn-text-dark core-btn-sm">';
        }
        if(typeof data1[i].icon != 'undefined'){
            icon = data1[i].icon;
            html1 += '<span class="-icon-svg" data-svgicon="'+icon+'">';
            html1 += SVG[icon];
            html1 += '</span>';
        }
        if(typeof data1[i].text != 'undefined'){
            html1 += '<span> '+data1[i].text+'</span>';
        }
        html1 += '</button>';
    }
    if(!jQuery.isEmptyObject(data2)){
        html2 += "<div class='core-btn-group' role='group'> <button type='button' class='core-btn core-btn-sm core-btn-light core-btn-text-dark core-btn-dropdown-toggle' data-bs-toggle='dropdown' aria-expanded='false'> "+(SVG.arrow_down_short)+" </button> <ul class='core-btn-group-dropdown-menu core-btn-show'>";
        for(let i in data2){
            if(typeof data2[i].url != 'undefined'){
                html2 += '<li><div class="core-btn-dropdown-item core-url" data-url="'+data2[i].url+'">';
            }else{
                html2 += '<li><div class="core-btn-dropdown-item" >';
            }
            if(typeof data2[i].icon != 'undefined'){
                icon = data2[i].icon;
                html2 += '<span class="-icon-svg" data-svgicon="'+icon+'">';
                html2 += SVG[icon];
                html2 += '</span>';
            }
            if(typeof data2[i].text != 'undefined'){
                html2 += '<span> '+data2[i].text+'</span>';
            }
            html2 += '</div></li>';
        }
        html2 += "</ul> </div>";
    }
    return "<div class='core-btn-group "+(this.get('class'))+"' role='group' "+(this.show('id'))+" "+(this.css())+"> "+(html1)+"  "+(html2)+" </div>";
}, function(){
    var element = '#'+this.id;
    $(element).find('.core-btn-dropdown-toggle').click(function(){
        $(element).find('ul').toggle();
    });
});

Render.on("button", function(){
    if ('acl' in this && !Render.helper.acl(this.acl)){
        return '';
    }
    
	var label = this.label || '';
	var prefix = '';
	var suffix = '';

	if (this.dd){
		this.addClass("-pdd -cmenuw");
		suffix = "<div class='-suffix'><span class='-dd-icon'></span></div>";
	}

    if (this.fit) {
        this.addClass("core-fit");
    }

    if (this.borderless) {
        this.addClass("-borderless");
    }

	if (this.icon || this.svg){
		prefix = "<div class='-icon'>"+(Render.helper.getIcon(this))+"</div>";
		this.addClass("-picon");
	}

	if (this.right_icon){
		suffix = "<div class='-ricon'> <span class='-icon-svg' data-svgicon='"+(this.right_icon)+"'> "+(SVG[this.right_icon])+" </span> </div> ";
		this.addClass("-pricon");
	}

	if (this.disabled){
		this.addClass("-disabled");
	}

	if (this.subtle){
		this.addClass("-subtle -fit");
	}

	if (this.cta){
		this.addClass("-cta");
	}

	if (this.success){
		this.addClass("-success");
	}

	if (this.warning){
		this.addClass("-warning");
	}

    if (this.error) {
        this.addClass("-error");
    }

	if (this.special){
		this.addClass("-special");
	}

	if (this.left){
		this.css("float", "left");
	}

	if (this.right){
		this.css("float", "right");
	}

	if (this.icon_only){
		this.addClass('-icon-only');
	}

	if (this.center){
		this.addClass("core-center");
	}

	if (this.default) {
	    this.addClass('-default');
    }

	var subtle_link='';
	if (!this.dd){
		if (this.url || this.urlparam){
			this.addClass("core-url");
		}
	}else{
		if (this.url){
			subtle_link="<div class='-absfit core-url' data-url='"+(this.url)+"'></div>";
		}
	}

	this.addSizingClass();
	if (!this.not_fit) {
	    this.addClass('core-fit');
    }

	return "<div "+(this.showAllData())+" "+(this.show('id'))+" class='core-button "+(this.get('class'))+"' "+(this.show('url'))+" "+(this.showData('urlparam'))+" "+(this.showData('value'))+" "+(this.showHTMLSemantics())+" "+(this.showHTMLEvents())+" "+(this.css())+"> "+(subtle_link)+" "+(prefix)+" <span class='-txt'>"+(this.icon_only ? '' : label)+"</span> "+(suffix)+" "+(this.content)+" </div>";
});

Render.on("button-selected", function(){
	var label = this.label||this.title||__('Selected');
	this.icon = this.icon;
    var prefix = '';
	var suffix = "<div class='-suffix'></div>";;
    if (this.icon || this.svg){
		prefix = "<div class='-icon'>"+(Render.helper.getIcon(this))+"</div>";
		this.addClass("-picon");
	}

	if (this.active){
		this.css("display", "block");
	}

    if (this.fit) {
        this.addClass("core-fit");
    }

	if (this.disabled){
		this.addClass("-disabled");
	}

	if (this.subtle){
		this.addClass("-subtle -fit");
	}

	if (this.cta){
		this.addClass("-cta");
	}

	if (this.success){
		this.addClass("-success");
	}

	if (this.warning){
		this.addClass("-warning");
	}

	if (this.error) {
        this.addClass("-error");
    }

	if (this.special){
		this.addClass("-special");
	}

	if (this.left){
		this.css("float", "left");
	}

	if (this.right){
		this.css("float", "right");
	}

	if (this.icon_only){
		this.addClass('-icon-only');
	}

	if (this.center){
		this.addClass("core-center");
	}

	this.addSizingClass();

	return "<div class='core-selected-button "+(this.get('class'))+"' "+(this.show('url'))+" "+(this.showData('urlparam'))+" "+(this.showData('value'))+" "+(this.showHTMLSemantics())+" "+(this.css())+" "+(this.show('id'))+"> "+(prefix)+" <span class='-txt'>"+(label)+"</span> <span class='-js-scount'></span> "+(suffix)+" "+(this.content)+" </div>";
});

Render.on("button-dd", function(){
	this.addSizingClass();
	var icon="<span class='-icon-svg'>"+(SVG.three_dots)+"</span>";

	if (this.icon){
		icon = Render.helper.getIcon(this);
	}

	if (this.left){
		this.css("float", "left");
	}

	if (this.right){
		this.css("float", "right");
	}

	if (this.icon_only){
		this.addClass('-icon-only');
	}

	if (this.stroked || this.bordered){
		this.addClass("-stroked");
	}

	if (this.url){
		this.addClass("core-url");
	}

	return "<div class='core-button-dd -cmenuw "+(this.get('class'))+"' "+(this.show('url'))+" "+(this.css())+"> <div class='core-bdd-content core-ap-f13'>"+(this.content)+"</div> "+(icon)+" </div>";
});




Render.on("spin-bd", function(){
    var color = 'core-text-default';

    var list_color = ["primary", "secondary", "success", "danger", "warning", "info", "light", "dark"];
    if (this.color){
        if(list_color.includes(this.color)){
            color = "core-text-"+this.color;
        }
    }

    return "<span class='core-spinner-border "+(color)+" "+(this.get('class'))+"' role='status' "+(this.css())+"></span>";
});
Render.on("spin-grow", function(){
    var color = 'core-text-default';
    var list_color = ["primary", "secondary", "success", "danger", "warning", "info", "light", "dark"];
    if (this.color){
        if(list_color.includes(this.color)){
            color = "core-text-"+this.color;
        }
    }
    
    return "<span class='core-spinner-grow "+(color)+" "+(this.get('class'))+"' role='status' "+(this.css())+"></span>";
});



Render.on(["flex-basic", "flex-inline"], function(){
    var class_name = '';
    if(this.name == 'flex_basic'){
        class_name = 'core-flex';
    }else{
        class_name = 'core-flex-inline';
    }
    if(this.direction){
        class_name += ' core-flex-'+this.direction;
    }
    if(this.justify){
        class_name += ' core-justify-content-'+this.justify;
    }
    if(this.align_item){
        class_name += ' core-align-items-'+this.align_item;
    }
    if(this.align_self){
        class_name += ' core-align-self-'+this.align_self;
    }
    if(this.wrap){
        class_name += ' core-flex-'+this.wrap;
    }
    class_name += ' '+this.get('class');
    return "<div class='"+(class_name)+"' "+(this.css())+">"+(this.content)+"</div>";
});



Render.on("panel-basic", function(){
    let title = '';
    if(this.icon){
        title += Render.helper.getIcon(this)+' ';
    }
    if (this.title){
        title += this.title; 
    }

    return "<div class='core-panel-box "+(this.get('class'))+"' "+(this.css())+"> <div class='core-panel-box-heading'> "+(title)+" </div> <div class='core-panel-box-content'> "+(this.content)+" </div> </div>";
});


Render.on("grid-row", function(){
    return "<div class='core-row "+(this.get('class'))+"' "+(this.css())+">"+(this.content)+"</div>";
});
Render.on("grid-container", function(){
    return "<div class='core-container "+(this.get('class'))+"' "+(this.css())+">"+(this.content)+"</div>";
});
Render.on("grid-container-fluid", function(){
    return "<div class='core-container-fluid "+(this.get('class'))+"' "+(this.css())+">"+(this.content)+"</div>";
});
Render.on("grid-col", function(){
    var col = 'core-col';
    if(this.col){
        
        colum = this.col.split(',');
        if(typeof colum[0] != "undefined"){
            col = 'core-col-lg-'+colum[0];
        }
        if(typeof colum[1] != "undefined"){
            col += ' core-col-md-'+colum[1];
        }
        if(typeof colum[2] != "undefined"){
            col += ' core-col-sm-'+colum[2];
        }
    }
    return "<div class='"+(col)+" "+(this.get('class'))+"' "+(this.css())+">"+(this.content)+"</div>";
});


Render.on("slider-images", function () {
    return "<ul "+(this.show('id'))+" "+(this.get('class'))+" "+(this.css())+"> "+(this.content)+" </ul>";
  },
  function (params) {
    $(this).lightSlider({
      item: (params.col || 1),
      slideMargin: 0,
      loop: true,
      auto:true,
      pauseOnHover: true,
      pause: ((params.time ||3) * 1000),
    });
  }
);

Render.on("slider-image", function () {
  return "<li><img src='"+(this.data)+"' width='100%'/></li>";
});

Render.on("slider-items", function () {
  return "<div "+(this.show('id'))+" class='"+(this.get('class'))+"' "+(this.css())+"> <ul> "+(this.content)+" </ul> </div> ";
},
function (params) {
  $(this).find('ul').lightSlider({
    item: (params.col || 4),
    slideMargin: 10,
    loop: true,
    auto:true,
    pauseOnHover: true,
    pager: params.dot ? true : false,
    prevHtml: params.prev ? params.prev : '',
    nextHtml: params.next ? params.next : '',
    pause: ((params.time || 3) * 1000),
  });
  if(params.action_black){
    $(this).find('.lSAction a').css("background-image", 'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAC4jAAAuIwF4pT92AAAGYmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxNDUgNzkuMTYzNDk5LCAyMDE4LzA4LzEzLTE2OjQwOjIyICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxOSAoV2luZG93cykiIHhtcDpDcmVhdGVEYXRlPSIyMDIyLTEyLTI1VDEyOjQwOjExKzA3OjAwIiB4bXA6TW9kaWZ5RGF0ZT0iMjAyMi0xMi0yNVQxMjo0MTozOSswNzowMCIgeG1wOk1ldGFkYXRhRGF0ZT0iMjAyMi0xMi0yNVQxMjo0MTozOSswNzowMCIgZGM6Zm9ybWF0PSJpbWFnZS9wbmciIHBob3Rvc2hvcDpDb2xvck1vZGU9IjMiIHBob3Rvc2hvcDpJQ0NQcm9maWxlPSJzUkdCIElFQzYxOTY2LTIuMSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDphNGRjNGIwZi0zY2UzLTM0NDAtODg3Mi01YzFmNjY3MGFlMDIiIHhtcE1NOkRvY3VtZW50SUQ9ImFkb2JlOmRvY2lkOnBob3Rvc2hvcDpkY2QxYjJlYi1hZTcxLWU5NGYtYTU4YS0yZDAzMDVkNGNhZDMiIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo4ZTk4NGUyZC04OGFlLTc5NGMtOGQyMi04NWEzOTYwNTA1ZDMiPiA8eG1wTU06SGlzdG9yeT4gPHJkZjpTZXE+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJjcmVhdGVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjhlOTg0ZTJkLTg4YWUtNzk0Yy04ZDIyLTg1YTM5NjA1MDVkMyIgc3RFdnQ6d2hlbj0iMjAyMi0xMi0yNVQxMjo0MDoxMSswNzowMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTkgKFdpbmRvd3MpIi8+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJjb252ZXJ0ZWQiIHN0RXZ0OnBhcmFtZXRlcnM9ImZyb20gYXBwbGljYXRpb24vdm5kLmFkb2JlLnBob3Rvc2hvcCB0byBpbWFnZS9wbmciLz4gPHJkZjpsaSBzdEV2dDphY3Rpb249InNhdmVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOmE0ZGM0YjBmLTNjZTMtMzQ0MC04ODcyLTVjMWY2NjcwYWUwMiIgc3RFdnQ6d2hlbj0iMjAyMi0xMi0yNVQxMjo0MTozOSswNzowMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTkgKFdpbmRvd3MpIiBzdEV2dDpjaGFuZ2VkPSIvIi8+IDwvcmRmOlNlcT4gPC94bXBNTTpIaXN0b3J5PiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pt2+TtEAAASbSURBVHic7drLb1VVGAXwX1VQqBTlFRNngq2xsYkTTGSmYC+QqMFEHTow4VESYcJEHSl/hBiE4ERAXiao6EgUInVgTJyAAfGFURNRB0ow5jrY59ye3pzHPreX1NizkqaPu89Za69++9uvb6DdbpvLuGm2Bcw2boGBgYGYtsPYiNW4B3cmf7+KS5jESVyoelFR1EXqGMGGRMdK3NGl47NEx/kYHQPtdruKeBwvYQzv44zQyV+Tz5cI5qxBC1/gFXxYRpyHCh2tRMcDFToeTtp+id14r1RHSQ5YhqP4AVuxsExdgkFM4AoOJ6JyifO+CrAcx/A9tkTqWIjN+A4nsKJIRxHxKC7jDQxFEHZjMQ4IIXlfHnGkAaP4BnuxqAcdt2OPYMRYno484lH8jBd6IOzGLvwojNtpxBEG9FPHNvyiy4Q8A5YLjveDNMUuIRI6wyHCgGVCBPZTx4QQCZ3hkGfAMSHc+o0DQk7oEFcYcFQYfv3G6zie1ZElbgmJps5YW4DncXdFu8VCYlyXEpcYMC4k3qrcsxzPYH4NvYuEPrZSHVniT4QsG4sFwlTXxv6I9hM4nRKXGHBamHWqsC/hPq6eCVvwcaojJR7B7+KmGKZ3/i88EvHMIP7AcIkBwzV0bMT1RMMJ8SYsTDiGswbsxFuRL+ju/Hjkc3AIO0oM2IGDNd63SW8mHEx1pHuB1Tgb8eACvIO1uIYncaqG4DMJVxFWJ21icRTP4m88LiTaGBPOdnQkzk9KEkMJZvKfT7Ee50oi4FyEjjzUjYT1+DQ7BC4o/88QprKZdB4ewvkSA2J0FCFrwp5YHXW2w9eS7zcLCe2/hj/xT/LzrbEPpQZcVbBxyWC7EF7zhIS5qaZACcfVks9/i9CRh5awiLtNGKZV03lHR2rAJWEKKsN1PG1mJgzjYsnnFyN0dKO7808Iw7RKxyWmDJgU9tFVmKkJaxKuIkwmbWLRS+en6+hxITRfWIG1BVM2RDyTLoRWRSyEYnLMo0Jn2/hAmKViMJhw3Ju3FN4c+RKmm/BaRPsJfETUUnhbxPv2qt95ybs7S/Is8Xr1N0Pz8JSp88EiDInfDK1L2i6ueOddeE69zg8JG63HUh3d29ATqufQXrAfb6e/RGyHDwvrjn5jH45kdXQTrxAODSb6SLoTX2NplrjCgCXCjLCrzzouC4ctHR15R1FjwvFRP0zYiZ9wf/aPkUdiI8JxWj9MKNRRdBg5hm+FE5ReDiOHhHC73E2aEkceio4IkfCm6pxQpGO/EIG5OoqICcPhuPrH0VuFRHNEJty6iSMNIAyHQ0I0bBc3RQ4K2f6KkHuW5jVqt+MuRlp4UYiKU8ovRsaFi5HdSrbJRZ2t0LEWL+PBjI7zBTpa+ByvqrigiTEgxbCpK6miq7F33firsVWmruhWFug4ia9idAyUhN6cwJy/HW4MmG0Bs42mPiBiFmjqAzT1AbXR1AckaOoDNPUBaOoDmvoAmvqApj6Apj6gqQ9o6gM09QE3DE19gKY+oKkPaOoDInU09QGpjixxUx+gqQ9o6gNo6gPQ1AegqQ/ooKkPSNDUB/wfMedvh/8FQXyvCLfbYl8AAAAASUVORK5CYII=")');
  }
}
);

Render.on("slider-item", function () {
  return "<li>"+(this.content)+"</li>";
});




Render.on("process-bar", function(){
    var color = 'core-process-bg-default';
    var loading = '';
    if(this.loading){
        loading = 'core-process-active';
    }
    var list_color = ["primary", "secondary", "success", "danger", "warning", "info", "light", "dark"];
    if (this.color){
        if(list_color.includes(this.color)){
            color = "core-process-bg-"+this.color;
            if(this.color == "warning" || this.color == "info" || this.color == "light"){
                color += " core-process-bg-text-dask";
            }
        }
    }

    return "<div class='core-process "+(this.get('class'))+"' "+(this.css())+" "+(this.show('id'))+"> <div class='core-process-bar "+(color)+" "+(loading)+"' data-percent='"+(this.percent)+"' style='width: "+(this.percent)+"%;'> <span class='core-process-label'>"+(this.percent)+"%</span> </div> </div>";
});

Render.on("process-cicle", function(){
    if(this.max_width){
        this.css("--size", this.max_width+'px');
    }else{
        this.css("--size", '150px');
    }
    this.css("--value", this.percent);
    this.css("--unit", this.unit || '');
    var color = 'core-process-cicle-bg-default';
    var list_color = ["primary", "secondary", "success", "danger", "warning", "info", "light", "dark"];
    if (this.color){
        if(list_color.includes(this.color)){
            color = "core-process-cicle-bg-"+this.color;
        } else {
            this.css("--processBg", this.color);
        }
    }

    return "<div class='core-process-cicle "+(color)+" "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.css())+">"+(this.content)+"</div>";
});



Render.on("image-thumb", function () {
    var alt = "";
    if (this.alt) {
      alt = this.alt;
    }
    if (this.width) {
      this.css("width", this.width + "px");
    }

    return "<img src='"+(this.src)+"' data-image='"+(this.src)+"' alt='"+(alt)+"' class='core-image-thumbnail "+(this.get('class'))+" core-url' data-url=':zoom' "+(this.css())+"/>";
  });

Render.on("image-round", function () {
	var alt = "";
	if (this.alt) {
		alt = this.alt;
	}
	if (this.width) {
		this.css("width", this.width + "px");
	}
	if(this.radius){
		this.css("border-radius", this.radius+'px');
	}
	return "<img src='"+(this.src)+"' alt='"+(alt)+"' class='core-image-round "+(this.get('class'))+"' "+(this.css())+"/>";
});

Render.on("image", function(){
	if (this.src){
		if (AP.word.prefix(this.src,'<img')){
			return "<span "+(this.showAllData())+" class='core-image -direct-html "+(this.get('class'))+"' "+(this.css())+">"+(this.src)+"</span>";
		}else{
		    if (this.no_view_detail) {
		        return "<span class='core-image -direct-src "+(this.get('class'))+"' "+(this.css())+"><img "+(this.showAllData())+" src='"+(this.src)+"'/></span>";
            }
			return "<span class='core-image -direct-src "+(this.get('class'))+"' "+(this.css())+"><img data-image='"+(this.src)+"' "+(this.showAllData())+" class='core-url' data-url=':zoom' src='"+(this.src)+"'/></span>";
		}
	}

	return "";
});

Render.on("image-upload-box", function(){
	var class_box = 'upload__img-box';
	var class_close_box = 'upload__img-close';
	if(this.image){
		class_box = 'upload__img-box-old';
		class_close_box = 'upload__img-close-old';
	}
	return "<div class='"+(class_box)+"'> <div style='background-image: url("+(this.url)+")' data-number='"+(this.close_length || 0)+"' data-file='"+(this.file)+"' class='img-bg'> <div class='"+(class_close_box)+"'></div> <input type='hidden' name='"+(this._name || 'image')+""+(this.multiple ? '[]' : '')+"' value='"+(this.base64 || this.url)+"'> </div> </div>";
});

Render.on("image-upload", function(){
	var list_image = this.value || [];
	var image_html = '';
	if(AP.isArray(list_image)){
		for(i in list_image){
			if(list_image[i].trim() != ''){
				image_html += "  " +Render.render('image_upload_box', {url:list_image[i], file:list_image[i], multiple:this.multiple, _name: "old_image" , image:1}, '')+ '';
			}
		}
	}
	return "<div class='core-image-upload__box' "+(this.show('id'))+"> <div class='upload__btn-box'> <label class='upload__btn'> " +Render.render('button', {label:this.label || __("Upload Images"), _class: "core-image-button-upload" }, '')+ "<input type='file' "+(this.multiple ? 'multiple' : '')+" data-max_length='50' class='upload__inputfile' id='upload__inputfile'> </label> </div> <div class='upload__img-wrap'>"+(image_html)+"</div> </div>";
}, function (params) {
	var imgWrap = "";
	var imgArray = [];
	$('.upload__inputfile').each(function () {
		$(this).on('change', function (e) {
			if(!params.multiple){
				$('.upload__img-wrap').empty();
			}
			imgWrap = $(this).closest('.core-image-upload__box').find('.upload__img-wrap');
			var maxLength = $(this).attr('data-max_length');
			var files = e.target.files;
			var filesArr = Array.prototype.slice.call(files);
			var iterator = 0;
			filesArr.forEach(function (f, index) {
				if (!f.type.match('image.*')) {
					return;
				}
				if (imgArray.length > maxLength) {
					return false
				}
				var len = 0;
				for (var i = 0; i < imgArray.length; i++) {
					if (imgArray[i] !== undefined) {
						len++;
					}
				}
				if (len > maxLength) {
					return false;
				}
				imgArray.push(f);
				var reader = new FileReader();
				reader.onload = function (e) {
					var image_base64 = e.target.result.replace("data:", "").replace(/^.+,/, "");
					var close_length = $(".upload__img-close").length;
					var html = "  " +Render.render('image_upload_box', {url:e.target.result, base64:image_base64, close_length:close_length, file:f.name, multiple:params.multiple, _name:params._name}, '')+ '';
					imgWrap.append(html);
					iterator++;
				}
				reader.readAsDataURL(f);
			});
		});
	});

	$(this).on('click', ".upload__img-close", function (e) {
		var file = $(this).parent().data("file");
		for (var i = 0; i < imgArray.length; i++) {
			if (imgArray[i].name === file) {
				imgArray.splice(i, 1);
				break;
			}
		}
		$(this).parent().parent().remove();
	});
	$(this).on('click', ".upload__img-close-old", function (e) {
		$(this).parent().parent().remove();
	});
});



Render.on("avatar-img", function () {
  var alt = "";
  var width = "50px";
  if (this.alt) {
    alt = this.alt;
  }
  if (this.width) {
    width = "width:" + this.width + "px;" + "height:" + this.width + "px";
  }

  return "<div class='core-avatar "+(this.get('class'))+"' style='"+(width)+"'> <img src='"+(this.src)+"' alt='"+(alt)+"' class='core-avatar-img' /> </div>";
});

Render.on("avatar-text", function () {
    var alt = "";
    var width = "50px";
    var color = '';
    if (this.alt) {
      alt = this.alt;
    }
    if (this.width) {
      width = "width:" + this.width + "px;" + "height:" + this.width + "px";
    }
    var list_color = ["primary", "secondary", "success", "danger", "warning", "info"];
    if (this.color){
        if(list_color.includes(this.color)){
            color = "core-avatar-bg-"+this.color;
        }
    }
    function getRandomInt(max) {
        return Math.floor(Math.random() * max);
    }
    if(this.random){
        color = "core-avatar-bg-"+list_color[getRandomInt(5)];
    }
      
    return "<div class='core-avatar-text "+(color)+" "+(this.get('class'))+"' style='"+(width)+"' "+(this.show('id'))+"> </div>";
  },
  function (params) {
    function getInitials(fullName) {
      var allNames = fullName.trim().split(" ");
      var initials = allNames.reduce((acc, curr, index) => {
        if (index === 0 || index === allNames.length - 1) {
          acc = ""+(acc)+""+(curr.charAt(0).toUpperCase())+"";
        }
        return acc;
      }, "");
      return initials;
    }
    var avatar = getInitials(params.data);
    var avatar_element = '#'+params.id;
    $(avatar_element).text(avatar);
  }
);



Render.on("flag-message", function(){
    this.addStatusColor();

    if (this.fill || this.solid){
        var color = "#fff";
        this.css("background-color", Color.rgba(Render.helper.getColor(this.color), 5, 5));
        this.css("color", "rgba(255,255,255, 0.9)");
        this.css("border", "1px solid rgba(0,0,0,0.01)");
        this.addClass("-fill");
    }else if (this.color){
        var color = Render.helper.getColor(this.color);
        this.addClass("-colorful -edge");
        this.css("background-color", Color.rgba(color, 0.1));
        this.css("border", "1px solid "+Color.rgba(color, 0.3));
    }

    var icon='';
    if (this.icon){
        icon = "<div class='-icon'>"+(Render.helper.getIcon(this))+"</div>";
        this.addClass("-picon");
    }

    var cta='';
    if (this.url && this.cta){
        cta="<div class='bf-cta url' data-url='"+(this.url)+"'>"+(this.cta)+"</div>";
    }

    var title='';
    if (this.title){
        title= "<div class='-title' style='color:"+(color)+"'>"+(this.title)+"</div>";
        if (this.title_color){
            title= "<div class='-title' style='color:"+(Render.helper.getColor(this.title_color))+"'>"+(this.title)+"</div>";
        }
    }

    return "<div class='core-flag-message "+(this.get('class'))+"' "+(this.css())+" "+(this.showHTMLSemantics())+"> "+(icon)+" <div class='bm-inner'> "+(title)+" "+(this.content)+" </div> "+(cta)+" </div>";
});


Render.on("message", function(){
    if (this.acl && !Render.helper.acl(this.acl)){
        return '';
    }

    var that_color = this.color;
    if (this.type == 'success') {
        that_color = '#b7eb8f';
    }else if (this.type == 'info') {
        that_color = '#91d5ff';
    }else if (this.type == 'warning') {
        that_color = '#dfab00';
    }else if (this.type == 'error') {
        that_color = '#ffccc7';
    }else if (this.type == 'default') {
        that_color = '#000000';
    }
    if (that_color && this.edge){
        var color = Render.helper.getColor(that_color);
        this.addClass("-colorful -edge");
        this.css("border", "1px solid "+ Color.rgba(Color.adjust(color,20,20), 0.2));
        this.css("background-color", Color.rgba(color, 0.05));
        this.css("color", Color.adjust(color, 10, 10));
    }else if (that_color && (this.light||this.subtle)){
        var color = Render.helper.getColor(that_color);
        this.addClass("-colorful -subtle");
        this.css("background-color", Color.rgba(color, 0.1));
        this.css("border", "1px solid "+ Color.rgba(color, 0.3));
        this.css("color", Color.adjust(color, 10, 10));
    }else if (that_color){
        var color = Render.helper.getColor(that_color);
        this.css("background-color", Color.adjust(color, 10, 10));
        this.addClass("-colorful -fill");
    }

    this.addSizingClass();

    var icon='';
    if (this.icon){
        icon = "<div class='-icon'>"+(Render.helper.getIcon(this))+"</div>";
        this.addClass("-picon");
    }else if (this.avatar){
        this.addClass("-pavatar");
    }else if (this.avatar_xl){
        this.addClass("-pavatar-xl");
    }else if (this.avatar_lg){
        this.addClass("-pavatar-lg");
    }

    if (this.alert) {
        this.addClass("-alert");
        var color = Render.helper.getColor(that_color);
        this.css("color", '#202223');
        this.css("background-color", Color.rgba(color, 0.15));
        this.css("border", "1px solid "+ Color.adjust(color, 10, 10));
        icon = "<div class='-icon' style='color: "+(color)+";'>"+(Render.helper.getIcon(this))+"</div>";
    }

    if (this.custom) {
        this.css("color", this.color);
        this.css("background-color", this.background);
        this.css("border", "1px solid "+ this.border_color);
    }

    return "<div class='core-message "+(this.get('class'))+"' "+(this.css())+"><div class='bm-inner-wrapper std-padding'> "+(icon)+" <div class='bm-inner'> "+(this.content)+" </div> </div></div>";
});


// 
Render.on("side-bars", function () {
    return "<div class='core-sidebar-container "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.css())+"> <div class='core-sidebar'> <div class='core-sidebar-header'><button class='core-btn core-sidebar-button-toggle'>"+(SVG.sidebar_icon_list)+"</button></div> <div> <div class='core-sidebar-body'> "+(this.content)+" </div> </div> </div> </div>";
  }, function(){
      $(this).find('.core-sidebar-button-toggle').click(function(){
        if($(this).parents('.core-sidebar-toggle').length){
            $(this).parents('.core-sidebar').removeClass('core-sidebar-toggle');
        }else{
            $(this).parents('.core-sidebar').addClass('core-sidebar-toggle');
        }
      });
      $(this).find('a').click(function(){
        $(this).parent().find('a').removeClass('core-sidebar-active');
        $(this).addClass('core-sidebar-active');
      });
  });

  Render.on("side-bar", function () {
    var html = '<a class="'+this.get('class');
        if(this.active){
            html += ' core-sidebar-active';
        }
        
        if(this.url){
            html += '" data-url="'+this.url;
        }
        html += '" '+this.css()+'>';
        html += '<div>';
        if(this.icon){
            html += SVG[this.icon];
        }
        if(this.content){
            html += '<span class="core-sidebar-text"> '+this.content+'</span>';
        }
        html += '</div>';
        if(this.notify){
            html += '<span class="core-sidebar-count core-sidebar-text"> '+this.notify+'</span>';
        }
        html += '</a>';
  
    return html;
  });



Render.on("form", function () {
    if (this.action) {
        return "<div class='core-form "+(this.get('class'))+"'> <form method='POST' "+(this.show('id'))+" action='"+(this.action)+"'>"+(this.content)+"</form> </div>";
    } else {
        return "<div class='core-form "+(this.get('class'))+"' "+(this.show('id'))+"> "+(this.content)+" </div>";
    }
});

Render.on("form-header", function () {
    var title = this.title ? ("  " +Render.render('title', {}, ""+(this.title)+"")+ '') : '';
    var subtitle = this.subtitle ? ("  " +Render.render('subtitle', {}, ""+(this.subtitle)+"")+ '') : '';

    return "<div class='core-form-header'>"+(title)+""+(subtitle)+""+(this.content)+"</div>";
});

Render.on("form-checkbox", function () {
    var label = '';
    if (this.label) {
        label = "<span title='"+(this.label)+"'>"+(this.label)+"</span>";
    }
    var input_checked = this.checked ? 'checked' : '';
    var disabled = this.disabled ? 'disabled' : '';
    return "<label class='core-ant-checkbox-wrapper "+(this.get('class'))+"' "+(this.css())+" "+(this.show('id'))+"> <span class='core-ant-checkbox'> <input value='"+(this.value || '')+"' "+(disabled)+" type='checkbox' name='"+(this._name || '')+"' "+(input_checked)+" class='core-ant-checkbox-input'> <span class='core-ant-checkbox-inner'></span> </span> "+(label)+" </label> ";
});



Render.on("form-input", function() {
    var help = '';
    var icon_left = '';
    var icon_right = '';
    var attrs = '';
    var link_html = '';
    var explain_html = '';
    if (this.width) {
        this.css("width", this.width);
    }
    if (this.explain) {
        explain_html = "  " +Render.render('text_explain', {direction:this.explain_direction || "up"}, ""+(this.explain)+"")+ '';
    }
    if (this.link) {
        link_html = "<a class='form-input-link' href='"+(this.link)+"' target='_blank'>"+(this.link_text)+"</a>";
    }

    if (this.disable_autocomplete){
        attrs += " autocomplete='off' ";
    }

    if (this.icon_left) {
        icon_left = "<span class='core-icon core-is-small core-is-left'>"+(SVG[this.icon_left])+"</span>";
    }

    if (this.icon_right) {
        icon_right = "<span class='core-icon core-is-small core-is-right'>"+(SVG[this.icon_right])+"</span>";
    }

    if (this.help) {
        help = "<p class='core-help'>"+(this.help)+"</p>";
    }
    var html = '';
    var label = "<label class='core-label'>"+(this.label || '')+" "+(link_html)+" "+(explain_html)+"</label>";
    if (this.no_label) {
        this.addClass('-no-label');
        label = '';
    }

    if (this.type == 'html') {
        html = '<div class="core-control"></div>';
    } else if (this.type == 'textarea' || this.textarea) {
        html = "<div class='core-control'> <textarea  "+(this.showAllData())+" class='core-textarea "+(this.style_color || '')+"' name='"+(this._name || '')+"' placeholder='"+(this.placeholder || '')+"'>"+(this.value || '')+"</textarea> </div> ";
    } else if(this.type == 'read' || this.read_only) {
        return "<fieldset disabled> <div class='core-field "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.css())+"> "+(label)+" "+(html)+"<div class='core-control core-has-icons-left'> <input value='"+(this.value || '')+"' read-only "+(this.showAllData())+" class='core-input "+(this.style_color || '')+"' name='"+(this._name || '')+"' type='"+(this.type || 'text')+"' placeholder='"+(this.placeholder || '')+"'> <span class='core-icon core-is-small core-is-left' style='color: #42b814;'>"+(SVG['lock'])+"</span> </div> "+(help)+" "+(this.content)+" </div> </fieldset> ";
    } else if(this.type == 'checkbox') {
        if (!this.label) {
            return "<label class='core-checkbox' "+(this.disabled ? 'disabled' : '')+"> <input type='checkbox' "+(this.disabled ? 'disabled' : '')+" value='"+(this.value || '')+"' name='"+(this.namme || '')+"' "+(this.checked ? 'checked' : '')+"> "+(this.content)+" </label> ";
        }
        var content = '';
        if (this.options){
            content = AP.render(this.options, function(e){
                if (AP.data.isObject(e)){
                    return "<label class='core-checkbox' "+(e.disabled ? 'disabled' : '')+"> <input type='checkbox' "+(e.disabled ? 'disabled' : '')+" value='"+(e.value || '')+"' name='"+(e.name || '')+"' "+(e.checked ? 'checked' : '')+"> "+(e.content)+" </label> ";
                }

                return '';
            });
        }
        if (this.new_line) {
            this.addClass('-new-line');
        }
        html = "<div class='core-control "+(this.get('class'))+"' "+(this.show('id'))+"> "+(content)+" </div> ";
    } else if(this.type == 'radio') {
        var content = '';
        if (this.options){
            content = AP.render(this.options, function(e){
                if (AP.data.isObject(e)){
                    return "<label class='core-radio' "+(e.disabled || '')+"> <input type='radio' "+(e.disabled || '')+" name='"+(e.name || '')+"' value='"+(e.value)+"'> "+(e.label)+" </label> ";
                }

				return "<option value='"+(e)+"'>"+(e)+"</option>";
			});
		}
        if (this.new_line) {
            this.addClass('-new-line');
        }
        html = "<div class='core-control "+(this.get('class'))+"' "+(this.disabled || '')+" "+(this.show('id'))+"> "+(content)+" </div> ";
    } else if(this.type == 'select') {
        var content = '';
        if (this.options){
            content = AP.render(this.options, function(e){
                if (AP.data.isObject(e)){
                    var option_id = '';
                    if(typeof e.id != "undefined") {
                        option_id = "data-id='"+(e.id)+"'";
                    }
                    return "<option value='"+(e.value)+"' "+(option_id)+">"+(e.content)+"</option> ";
                }

                return '';
            });
        }
        html = "<div class='core-control' "+(this.show('id'))+"> <div class='core-select'> <select name='"+(this._name || '')+"'> "+(content)+" </select> </div> </div> ";
    } else if (this.type == 'file') {
        var image_html = '';
        if (this.src && this.src != '') {
            image_html = "  " +Render.render('image', {src:this.src}, '')+ '';
        }
        html = "<div class='core-control'> <input type='file' name='"+(this._name)+"'/> "+(image_html)+" </div> ";
    } else if (this.type == "files"){
        var limit = this.limit || 10;
        var show = this.display || this.initial || 1;

        var content = '';
        var remove_file = "<span class='-icon-svg'> "+(SVG.close)+" </span> ";
        for (var i=0; i<=limit; i++){
            content+= "<div class='core-input-file "+(i>=show?'core-hidden':'')+"'> "+(i > 0 ? remove_file : '')+" <input type='file' name='"+(this._name)+"[]'/> </div> ";
        }

        html = "<div class='core-control'> "+(content)+" </div> ";

    }else if (this.type == "editor") {
        html = "<div class='relative js-textarea-editor'> <textarea "+(this.showAllData())+" name='"+(this._name)+"' data-type='editor' id='"+(AP.uuid())+"' "+(attrs)+" placeholder='"+(this.placeholder||'')+"'>"+(this.value || '')+"</textarea> </div> ";
    } else if (this.type == "datetime") {
        var date_val = '';
        var time_val = '';
        if (this.value){
            date_val = UI.inputDate(this.value);
            time_val = AP.time.time("%H:%i", this.value);
        }

        html = "<div class='core-control -datetime "+(this.icon_left ? 'core-has-icons-left' : '')+" "+(this.icon_right ? 'core-has-icons-right' : '')+"'> <input "+(this.showAllData())+" type='text' name='"+(this._name)+"-date' class='-ip-date core-input "+(this.style_color || '')+"' placeholder='"+(__('Choose a date'))+"' value='"+(date_val||'')+"' "+(attrs)+"/> <input "+(this.showAllData())+" type='text' name='"+(this._name)+"-time' class='-ip-time core-input "+(this.style_color || '')+"' placeholder='"+(__('Choose a time'))+"' value='"+(time_val||'')+"' "+(attrs)+"/> </div> ";
    } else if (this.type == 'daterange') {
        html = "<div class='core-control -daterange'> <input "+(this.showAllData())+" value='"+(this.value || '')+"' class='core-input "+(this.style_color || '')+"' name='"+(this._name || '')+"' type='text'> <div class='input-value js-range'></div> <div class='core-input-mask core-abs-fit'></div> </div> ";
    } else if (this.type == "color"){
        html = "  " +Render.render('form_color', {_name:this._name, value:this.value||''}, '')+ '';
    } else if(this.type == "switch") {
        html = " " +Render.render('switch_basic', {checked:this.checked, color:this.color, size:this.size, name_switch:this._name, text_on:this.text_on, text_off:this.text_off}, '')+ " ";
        if (this.inline) {
            return "<div class='core-field "+(this.get('class'))+" core-field-switch-inline' "+(this.show('id'))+" "+(this.css())+"> "+(html)+" <span class='-ph'>"+(this.label || '')+"</span> </div> ";
        }
    } else {
        html = "<div class='core-control "+(this.icon_left ? 'core-has-icons-left' : '')+" "+(this.icon_right ? 'core-has-icons-right' : '')+"'> <input "+(this.showAllData())+" value='"+(Render.helper.escape(this.value) || '')+"' class='core-input "+(this.style_color || '')+"' name='"+(this._name || '')+"' type='"+(this.type || 'text')+"' placeholder='"+(this.placeholder || '')+"'> "+(icon_left)+" "+(icon_right)+" </div> ";
    }

    if (this.no_type) {
        html = '';
    }

    return "<div class='core-field "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.css())+"> "+(label)+" "+(html)+" "+(help)+" "+(this.content)+" </div> ";
}, {
    done: function(params, obj) {
        var $that = $(this);
        if (params.type=='editor' || params.editor){
            UI.editor($that.find("textarea"), {
                value: Textarea.editor(obj.value||''),
                minHeight: params.height||'300px',
                bubble: params.bubble||'',
                compact: params.bubble?1:'',
                autogrow: params.autogrow||'',
                minWidth: params.width||'100%',
                maxHeight: params.maxHeight || '500px',
                maxWidth: params.maxWidth || '100%',
            });
        }

        if (params.role == "date" || params.type == "date" || params.date){
            var $ip = $that.find("input");
            if (!$ip.length){
                $ip = $that.find("textarea");
            }

            var val=$ip.val();
            if (val && val.length && AP.data.isInt(val)){
                $ip.data("ts", val).val(UI.inputDate(val));
            }


            $ip.attr("autocomplete", "off");
            return $ip.selectDate();
        }

        if (params.role == "datetime" || params.type == "datetime" || params.datetime){
            $that.find("input.-ip-date").selectDate();
            $that.find("input.-ip-time").selectTime();
        }

        if (params.role == "daterange") {
            var $ip = $that.find("input");
            var m_start = null, m_end = null;

            if (!params.value) {
                var now = AP.time.now();
                m_start = moment(AP.time.time("%d-%m-%Y", now), "DD-MM-YYYY"), m_end = moment(AP.time.time("%d-%m-%Y", now), "DD-MM-YYYY");
                $ip.val(""+(now)+"-"+(now)+"");
                $that.find(".js-range").html("  " +Render.render('text_daterange', {_from:now, to:now}, '')+ '');
            } else {
                var data = AP.word.split("-", params.value, true);
                $that.find(".js-range").html("  " +Render.render('text_daterange', {_from:data[0], to:data[1]}, '')+ '');
                m_start = moment(AP.time.time("%d-%m-%Y", data[0]), "DD-MM-YYYY");
                m_end = moment(AP.time.time("%d-%m-%Y", data[1]), "DD-MM-YYYY");
            }
            $that.find(".core-input-mask").dateRangePicker({
                opens: 'left',
                getValue: function(){
                    return this.innerHTML;
                },
                onSelect: function(from, to){
                    var start_time = encodeURIComponent(AP.time.time("%d-%m-%Y", from));
                    var to_time = encodeURIComponent(AP.time.time("%d-%m-%Y", to));
                    var dr = $(this).data('dateRangePicker');
                    $ip.val(""+(from)+"-"+(to)+"");
                    if ($that.bind) {
                        $ip.trigger('change');
                    }
                    $that.find(".js-range").html("  " +Render.render('text_daterange', {_from:moment(start_time, "DD-MM-YYYY").unix(), to:moment(to_time, "DD-MM-YYYY").unix()}, '')+ '');

                    dr.setStart(moment(start_time, "DD-MM-YYYY").format("YYYY-MM-DD"));
                    dr.setEnd(moment(to_time, "DD-MM-YYYY").format("YYYY-MM-DD"));
                    dr.close();
                }
            });

            var dr = $that.find(".core-input-mask").data("dateRangePicker");
            if (m_start){
                dr.setStart(m_start.format("YYYY-MM-DD"));
            }

            if (m_end){
                dr.setEnd(m_end.format("YYYY-MM-DD"));
            }
        }

        if (params.role == "int"){
            better_int_enter($that.find("input"));
        }

        if (params.type == "radio" && params.value) {
            $that.find("input[type='radio'][value='"+params.value+"']").prop('checked', true);
            return;
        } else if (params.type == "checkbox") {
            var array_value_checked = AP.word.split(",", params.value)
            $that.find("input[type='checkbox']").each(function() {
                AP.array.contain(array_value_checked, $(this).val()) && $(this).prop("checked", true);
            });
            return;
        } else if (params.type == "select") {
            if (params.multiple || params.improve){
                Form.improveSelect("select[name='"+params._name+"']", obj);
            } else {
                $that.find("select[name='"+params._name+"']").val(params.value);
            }
        } else if (params.type == "files"){
            $that.find("input[type=file]").change(function(){
                $(this).closest(".core-input-file").next().show();
            });

            $that.find(".core-input-file .-icon-svg").each(function() {
                $(this).click(function() {
                    var file_input = $(this).closest(".core-input-file");
                    file_input.find("input").val('');
                    file_input.hide();
                });
            });
        }

    }
});

Render.on("form-horizontal", function() {
    var label_size = this.label_size || '25';
    var explain_html = '';
    if (this.explain) {
        explain_html = "  " +Render.render('text_explain', {direction:this.explain_direction || "up"}, ""+(this.explain)+"")+ '';
    }
    return "<div class='core-field core-is-horizontal "+(this.single_line ? 'core-is-horizontal-line' : '')+" "+(this.get('class'))+"' "+(this.css())+"> <div class='core-field-label "+(this.is_normal || 'core-is-normal')+"' style='flex-basis: "+(label_size)+"%;'> <label class='core-label'>"+(this.label || '')+" "+(explain_html)+"</label> </div> <div class='core-field-body'> "+(this.content)+" </div> </div> ";
});

Render.on("form-vertical", function() {
    return "<div class='core-field core-is-vertical' "+(this.css())+"> <div class='core-field-body'> "+(this.content)+" </div> </div> ";
});

Render.on("form-addon", function() {
    var help = '';
    var icon_left = '';
    var icon_right = '';
    var title = "<div class='core-control'> <a class='core-bulma-button "+(this.style_color || 'core-bulma-is-static')+"'> "+(this.title || '')+" </a> </div> ";
    var option_content = '';
    var option_value = this.option_value || '';
    if (this.options){
        option_content = AP.render(this.options, function(e){
            if (AP.data.isObject(e)){
                var selected = '';
                if(option_value == e.value){
                    selected = 'selected';
                }
                var option_id = '';
                if(typeof e.id != "undefined") {
                    option_id = "data-id='"+(e.id)+"'";
                }
                return "<option value='"+(e.value)+"' "+(selected)+" "+(option_id)+">"+(e.content)+"</option> ";
            }

            return '';
        });
    }
    var option = "<div class='core-control'> <div class='core-select'> <select name='"+(this.option_name || '')+"'> "+(option_content)+" </select> </div> </div>";

    if (this.help) {
        help = "<p class='core-help'>"+(this.help)+"</p>";
    }

    if (this.icon_left) {
        icon_left = "<span class='core-icon core-is-small core-is-left'>"+(SVG[this.icon_left])+"</span>";
    }

    if (this.icon_right) {
        icon_right = "<span class='core-icon core-is-small core-is-right'>"+(SVG[this.icon_right])+"</span>";
    }
    var value = typeof this.value !== 'undefined' ? this.value : '';
    return "<div class='core-field core-has-addons "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.css())+"> <label class='core-label'>"+(this.label || '')+"</label> "+(this.title_left ? title : '' )+" "+(this.option_left ? option : '' )+" <div style='"+(this.flex ? 'flex:'+this.flex : 'flex:'+1)+"' class='core-control "+(this.icon_left ? 'core-has-icons-left' : '')+" "+(this.icon_right ? 'core-has-icons-right' : '')+"'> <input "+(this.showAllData())+" value='"+(value)+"' class='core-input "+(this.style_color || '')+"' name='"+(this._name || '')+"' type='"+(this.type || 'text')+"' placeholder='"+(this.placeholder || '')+"'> "+(icon_left)+" "+(icon_right)+" </div> "+(this.title_right ? title : '' )+" "+(this.option_right ? option : '' )+" "+(this.content)+" "+(help)+" </div> ";
}, {
    done: function(params) {
        var $that = $(this);
        if (params.role == "int"){
            better_int_enter($that.find("input"));
        }
    }
});

Render.on("form-range", function() {
    return "<div class='core-field core-is-vertical' "+(this.css())+"> <div class='core-field-body'> "+(this.content)+" </div> </div> ";
});

Render.on("form-select-shop", function() {
    var name = this._name || "shop_context";
    var label = this.label || "";
    var value = this.value || Client.current_shop_context+"-"+Client.current_shop_id;
    var options = this.options || Client.list_shop;
    if(!Client.is_multishop) {
        return "<div "+(this.show('id'))+"></div>";
    }
    return "<div "+(this.show('id'))+"> " +Render.render('form_input', {_class: "select-shop-input" , label:label, type: "select" , _name:name, options:options, value:value}, '')+ "</div> ";
}, function () {
    if(!Client.is_multishop) {
        $('.core-select-shop-tab').hide();
    }
    $('[name="shop_context"]').change(function () {
        var data = $(this).val().split('-');
        var context = parseInt(data[0]);
        var id_shop = parseInt(data[1]);
        var link = '&setShopContext=';
        if(context != 4){
            link += 's-'+id_shop;
        }
        AP.toURL(Client.current_path+'&setShopContext='+link);
    });
});



Render.on("form-color", function(){
	var presets = AP.render(range(1, 9), function(e){
		var c= Color.alt(e)
		return "<div class='core-fc-val' data-value='"+(c)+"' onclick='Form.ui.color.pallete(this)' style='background-color:"+(c)+"'><div class='core-r'></div></div>";
	});

	presets += AP.render(range(1, 9), function(e){
		var c= Color.adjust(Color.alt(e), -10, -85);
		return "<div class='core-fc-val' data-value='"+(c)+"' onclick='Form.ui.color.pallete(this)' style='background-color:"+(c)+"'><div class='core-r'></div></div>";
	});

	if (!this.presets){
		presets = '';
	}

	this.addSizingClass();
	if (!this.value){
		this.addClass("-empty");
	}

	return "<div class='core-fi-colorbox "+(this.get('class'))+"' "+(this.show('id'))+"> <div class='core-hidden'> <input name='"+(this._name)+"' class='core-js-color-value core-js-ignored core-js-hidden' value='"+(this.value||'')+"'/> </div> <div class='-fc-wrapper'> <div class='core-fc-presets'> <div class='core-fc-custom core-js-custom'  title='"+(__('Click to select a custom color'))+"'> <div> " +Render.render('icon', {icon: "form_color" }, '')+ "</div> <em class='core-js-selected-color'></em> </div> "+(presets)+" </div> <div class='core-fc-chosen'></div> </div> </div>";
}, function(params){
	var $input = $(this).find(".core-js-custom");

	$input.spectrum({
		color: params.value||null,
		type: "flat",
		hideAfterPaletteSelect: false,
		showInitial: true,
		showAlpha: false,
		allowEmpty: "false",
		palette: Color.pallete(),
        showPalette: true,
		change: function(val){
			if (val){
				Form.ui.color.set(val.toHexString(), this);
			}else{
				Form.ui.color.set("", this);
			}
		}
	});

	if (params.value){
		Form.ui.color.set(params.value, $input);
	}
});

Form.ui.color = {
	pallete: function(ref){
		return this.set($(ref).data("value"), ref);
	},

	set: function(val, ref){
		var $canvas = $(ref).closest(".core-fi-colorbox");
		$canvas.removeClass("-empty").find(".core-fc-chosen").html("<div class='core-chosen "+(Color.isDark(val)?'-dark':'-light')+"'> " +Render.render('tooltip', {width: "90" }, ""+(__('Chosen color'))+": "+(val)+"")+ "<div class='core-sq' style='background-color:"+(val)+"'> " +Render.render('icon', {icon: "fa check" }, '')+ "</div> </div> <div class='core-reset' onclick='Form.ui.color.reset(this)'><span class='-bis-icon'>"+(SVG.close)+"</span></div>");

		$canvas.find(".core-js-color-value").val(val).trigger("change");

		if (val){
			$canvas.find(".core-js-custom").css("background-color", val).addClass("-selected");
			$canvas.find(".core-js-custom em").html(val);

			if (Color.isDark(val)){
				$canvas.find(".core-js-custom").addClass("-dark-bg");
			}else{
				$canvas.find(".core-js-custom").removeClass("-dark-bg");
			}
		}else{
			$canvas.find(".core-js-custom").css("background-color", "#fff").removeClass("-selected");
		}
	},

	reset: function(ref){
		var $canvas = $(ref).closest(".core-fi-colorbox");
		$canvas.find(".core-js-color-value").val("").trigger("change");
		$canvas.addClass("-empty");

		$canvas.find(".core-js-custom").css("background-color", "#fff").removeClass("-selected");
	}
};



Render.on("form-langs", function() {
	var title = "<div class='core-control'> <a class='core-bulma-button "+(this.style_color || 'core-bulma-is-static')+"'> "+(this.title || '')+" </a> </div> ";
	var icon_left = '';
    var icon_right = '';
	var help = '';
	var html = '';
	var limit = this.limit || 10;
	var show = this.display || this.initial || 1;
	var remove_file = "<span class='-icon-svg'> "+(SVG.close)+" </span>";
	if (this.help) {
        help = "<p class='core-help'>"+(this.help)+"</p>";
    }
	if (this.icon_left) {
        icon_left = "<span class='core-icon core-is-small core-is-left'>"+(SVG[this.icon_left])+"</span>";
    }

    if (this.icon_right) {
        icon_right = "<span class='core-icon core-is-small core-is-right'>"+(SVG[this.icon_right])+"</span>";
    }

	var input_langs = '';
	var option_langs = '';
	for (var i = 0; i < Client.langs.length; i++) {
		var lang = Client.langs[i];
		var value = typeof this.value !== 'undefined' ? this.value[lang.id_lang] : '';

		option_langs += "<option value='"+(lang.id_lang)+"'>"+(lang.iso_code)+"</option>";

		var hidden = Client.current_lang_id == lang.id_lang ? '' : 'display: none;';
		if (this.type == 'textarea' || this.textarea) {
			input_langs += "<textarea  "+(this.showAllData())+" style='"+(hidden)+"' class='core-input-lang core-textarea "+(this.style_color || '')+"' name='"+(this._name || '')+"["+(lang.id_lang)+"]' placeholder='"+(this.placeholder || '')+"'>"+(value)+"</textarea>";
			continue;
		}
		if (this.type == 'file') {
			input_langs += "<input type='file' class='core-input-lang' style='"+(hidden)+"' name='"+(this._name)+"["+(lang.id_lang)+"]'/>";
			continue;
		}

		if (this.type == 'editor') {
            var lang = Client.langs[i];
            var value = typeof this.value !== 'undefined' ? this.value[lang.id_lang] : '';
			input_langs += "<div class='relative js-textarea-editor core-input-lang core-input-lang-"+(lang.id_lang)+"' style='"+(hidden)+"' "+(this.showAllData())+"> <textarea name='"+(this._name)+"["+(lang.id_lang)+"]' data-lang='"+(lang.id_lang)+"' data-type='editor' placeholder='"+(this.placeholder||'')+"'>"+(value)+"</textarea> </div>";
			continue;
		}

		if (this.type == 'files') {
			for (var j=0; j<=limit; j++){
				input_langs+= "<div class='core-input-file "+(j>=show?'core-hidden':'')+"'> "+(j > 0 ? remove_file : '')+" <input type='file' class='core-input-lang' style='"+(hidden)+"' name='"+(this._name)+"["+(lang.id_lang)+"][]'/> </div>";
			}
			continue;
		}

		input_langs += "<input "+(this.showAllData())+" style='"+(hidden)+"' value='"+(Render.helper.escape(value))+"' class='core-input-lang core-input "+(this.style_color || '')+"' name='"+(this._name || '')+"["+(lang.id_lang)+"]' type='text' placeholder='"+(this.placeholder || '')+"'>";
	}
	html = "<div style='margin-right: 8px;' class='core-control core-control-input core-is-expanded "+(this.icon_left ? 'core-has-icons-left' : '')+" "+(this.icon_right ? 'core-has-icons-right' : '')+"'> "+(input_langs)+" "+(icon_left)+" "+(icon_right)+" </div>";

    return "<div class='core-field "+(this.get('class'))+"' id='"+(this.id)+"'> <div class='core-field-label'> <div class='core-label'>"+(this.label || '')+"</div> </div> <div class='core-field-body'> "+(this.title ? title : '' )+" <div class='core-field core-has-addons'> "+(html)+" <div class='core-control'> <div class='core-select'> <select> "+(option_langs)+" </select> </div> </div> </div> </div> "+(help)+" </div> ";
}, {
	done: function(params) {
		var $that = $(this);
		if (params.role == "int"){
            better_int_enter($that.find("input"));
        }

		if (params.type=='editor' || params.editor){
			$that.find("textarea").each(function(){
				UI.editor($(this), {
					value: Textarea.editor($(this).val()),
					minHeight: params.height||100,
					bubble: params.bubble||'',
					compact: params.bubble?1:'',
					autogrow: params.autogrow||'',
                    maxHeight: params.maxHeight||500,
                    minWidth: params.minWidth || 380
				});
            });
        }

		if (params.type == "files"){
            $that.find("input[type=file]").change(function(){
                $(this).closest(".core-input-file").next().show();
            });

            $that.find(".core-input-file .-icon-svg").each(function() {
                $(this).click(function() {
                    var file_input = $(this).closest(".core-input-file");
                    file_input.find("input").val('');
                    file_input.hide();
                });
            });
        }
		$(this).find("select").change(function() {
			var lang_id = $(this).val();

			$(this).closest(".core-field-body").find(".core-control-input").find('.core-input-lang').hide();
			if (params.type == 'files') {
				$(this).closest(".core-field-body").find(".core-control-input").find(".core-input-lang[name='"+(params._name)+"["+(lang_id)+"][]']").show();
				return;
			}

			if (params.type == "editor") {
				$(this).closest(".core-field-body").find(".core-control-input").find(".core-input-lang-"+(lang_id)+"").show();
				return;
			}

			$(this).closest(".core-field-body").find(".core-control-input").find(".core-input-lang[name='"+(params._name)+"["+(lang_id)+"]']").show();
		});
	}
});




Render.on("table", function(){
    if (this.padding) {
        this.addClass("core-padded");
    }

    if (this.no_padding) {
        this.addClass('-no-padding');
    }

    if (this.definition) {
        this.addClass("core-definition");
    }

    if (this.structure) {
        this.addClass("core-semantic-structured");
    }

    if (this.fixed) {
        this.addClass("core-semantic-fixed");
    }

    if (this.single_line) {
        this.addClass("core-semantic-single core-semantic-line");
    }

    if (this.celled) {
        this.addClass("core-celled");
    }

    if (this.fill_white) {
        this.addClass("-core-fill-white");
    }

    if (this.borderless) {
        this.addClass("-borderless");
    }

    if (this.table_block) {
        this.addClass("-table-block");
    }

	return "<div class='core-table-wrapper' "+(this.show('id'))+"> <div class='core-table-inner'> <div class='core-table'> <table class='core-ui core-table "+(this.get('class'))+"'>"+(this.content)+"</table> </div> </div> </div>";
});



Render.on("cell", function(){
    var rowspan = '';
    var colspan = '';

    if (this.colspan) {
        colspan = "colspan='"+(this.colspan)+"'";
    }

    if (this.rowspan) {
        rowspan = "rowspan='"+(this.rowspan)+"'";
    }

    if (this.xdot) {
        this.addClass('core-cell-xdot');
    }

    if (this.right) {
        this.addClass('core-right core-aligned');
    }

    if (this.fit) {
        this.addClass('core-fit');
    }

    if (this.positive) {
        this.addClass('core-semantic-positive');
    }

    if (this.negative) {
        this.addClass('core-semantic-negative');
    }

    if (this.grid) {
        this.addClass('core-wide');
    }

    if (this.left) {
        this.css("padding-left", ""+(this.left)+"px");
    }
    if (this.top) {
        this.css("padding-top", ""+(this.top)+"px");
    }
    if (this.right) {
        this.css("padding-right", ""+(this.right)+"px");
    }
    if (this.align) {
        this.addClass('-align');
    }

    if (this.actions) {
        this.addClass('-actions');
    }

    if (this.checkbox) {
        var content_checkbox = "<div class='core-semantic-ui core-semantic-fitted core-semantic-slider core-semantic-checkbox'> <input type='checkbox' name='"+(this._name)+"' value='"+(this.value)+"'> <label></label> </div> ";
        if (this.checkbox_normal) {
            content_checkbox = " " +Render.render('form_checkbox', {disabled:this.disabled, _name:this._name, value:this.value, checked:this.checked}, '')+ " ";
        }
        if (this.head) {
            return "<th "+(this.css())+" class='"+(this.get('class'))+"' "+(rowspan)+" "+(colspan)+">"+(content_checkbox)+"</th>";
        }
        return " <td "+(this.css())+" class='"+(this.get('class'))+"' "+(rowspan)+" "+(colspan)+">"+(content_checkbox)+"</td>";
    }

    if (this.head) {
        return "<th "+(this.css())+" class='"+(this.get('class'))+"' title='"+(this.label || '')+"' "+(rowspan)+" "+(colspan)+"> "+(this.content)+" </th> ";
    }
    return "<td "+(this.css())+" class='"+(this.get('class'))+"' title='"+(this.label || '')+"' "+(rowspan)+" "+(colspan)+"> "+(this.content)+" </td> ";
});

Render.on("table-header", function(){
	this.addSizingClass();
	this.addStatusColor();

	if (this.gray){
		this.addClass('-gray');
	}

    if (this.full) {
        this.addClass("core-semantic-full-width")
    }

    if (this.thin) {
        this.addClass("-thin");
    }

	return "<thead "+(this.show('id'))+" class='"+(this.get('class'))+"'> "+(this.content)+" </thead> ";
}, {
	done: function(){
		$(this).find(".core-cell").wrapInner("<div class='core-ap-xdot'></div>");
	}
});

Render.on("table-body", function(){
	return "<tbody "+(this.show('class'))+" "+(this.show('id'))+">"+(this.content)+"</tbody>";
});

Render.on("table-row", function(){
    if (this.positive) {
        this.addClass('core-semantic-positive');
    }

    if (this.negative) {
        this.addClass('core-semantic-negative');
    }

	return "<tr class='js-table-row "+(this.get('class'))+"' "+(this.show('id'))+" "+(this.showAllData())+">"+(this.content)+"</tr>";
});




Render.on("layout-focus", function(){
	this.addSizingClass();
	if (this.borderless){
		this.addClass("-borderless");
	}
	
	return "<div class='core-layout-focus "+(this.get('class'))+"' "+(this.show('id'))+"> <div class='core-layout-internal'>"+(this.content)+"</div> </div>";
});




var Layout = new function __Layout() {
    this.init = function () {
        AP.sys.fire("system.init");
    };

    this.start = function () {
        Layout.scrollable('.scrollable');
        $("#page").removeClass();

        this.checkWidth();
        AP.sys.fire("system.start");
        $("#core-master-fs").remove();
        $(".nobootstrap").removeClass("nobootstrap");

        var check_page = setInterval(function () {
            if ($("#page").length > 0) {
                AP.sys.fire("system.autorun");
                clearInterval(check_page);
            }
        });
        $(document).mousedown(function(e) {
            if ($(e.target).closest(".core-js-improved-select").length > 0) {
                return;
            }
            $(".core-select.core-js-improved-select").each(function() {
                if (!$(this).find(".core-improve-select").hasClass("core-active")) {
                    return;
                }
                $(this).find(".core-improve-select").removeClass("core-active");
                Form.improveSelectHelper.updateValue($(this));
            });
        });
    }

    this.scrollable = function (box, callback = false) {
        $(box).each(function () {
            if ($(this).hasClass('__set')) {
                return;
            }

            $(this).addClass('__set');
            $(this).wrapInner("<div class='core-scrollin core-absolute'></div>");
            $(this).find(".core-scrollin").css({"right": -$.sbWidth(), top: 0, left: 0, bottom: 0});
            AP.scrollBar($(this).find('.core-scrollin'), callback).init();
        });
    };

    this.checkWidth = function () {
        $("#document").removeClass("screen-ld screen-md screen-sd screen-hd");

        if ($(window).width() < 1100) {
            $("#document").addClass("screen-ld");
        } else if ($(window).width() < 1280) {
            $("#document").addClass("screen-md");
        } else if ($(window).width() < 1500) {
            $("#document").addClass("screen-sd");
        } else {
            $("#document").addClass("screen-hd");
        }

    };
}

var Offcanvas = new function __Offcanvas() {
    this.__buttons = [];
    this.__id = '';

    this.load = function (options) {
        var $that = this;
        var prefix_id = options.id || 'uk-offcanvas';
        this.__id = ""+(prefix_id)+"-bar-content";
        this.__buttons = [
            {
                label: __('Cancel'),
                action: function () {
                    closeOffcanvas();
                },
                id: 'form-button-cancel',
                style: 'core-semantic-ui core-semantic-button core-form-button'
            },
            {
                label: __('Save'),
                action: function (ref) {
                    Form.submit("#"+(prefix_id)+"-form", function (code) {
                        if (!code.good()) {
                            return AP.alertError(code.message);
                        }
                        if (!options.success || !AP.data.isFunction(options.success)) {
                            UI.flash(__('Update successfully'));
                            closeOffcanvas();
                            AP.xRefresh();
                        } else if (AP.data.isFunction(options.success)) {
                            options.success(code);
                            closeOffcanvas();
                        }
                    }, $.extend({_r: 1}, options.data));
                },
                id: 'form-button-save',
                style: 'core-semantic-ui core-semantic-button core-semantic-positive core-form-button',
                validator: options.validator
            }
        ];
        if (options.disable_save) {
            this.__buttons.pop();
        }
        if (options.override_buttons) {
            this.__buttons = [];
        }
        if (options.buttons && AP.data.isArray(options.buttons)){
            this.buttons(options.buttons);
        }
        var has_footer = AP.data.isFunction(options.success);
        var footer = '';
        if (has_footer) {
            footer = "<div class='footer'> "+(this.renderFooter())+" </div> ";
        }
        $("#offcanvas-flip").html("<div class='uk-offcanvas-bar' style='width: "+(options.width || '480')+"px;'> <div class='header'> " +Render.render('title', {}, ""+(options.title || 'Title')+"")+ " " +Render.render('side', {}, '' +Render.render('icon', {_class: "close" , icon: "close" , _class: "uk-offcanvas-close" }, '')+ '')+ "</div> <div id='"+(prefix_id)+"-bar-content' class='content core-scrollable' data-autohide='1' data-autoscroll='1' style='height: calc(100% - "+(has_footer ? 116 : 56)+"px);'> <form method='post' style='padding: 20px; padding-top: 0;' id='"+(prefix_id)+"-form' action='"+(options.action || '')+"'> "+(options.html)+" </form> </div> "+(footer)+" </div> ");

        bindEvents(this);
        if (AP.data.isFunction(options.render)) {
            options.render.apply($that);
        }
        Layout.scrollable("#"+(prefix_id)+"-bar-content");
        Render.finish();
    }

    this.buttons = function(buttons) {
        var buttons_tmp = [];
        for (var i=0; i<buttons.length; i++){
            buttons_tmp.push(buttons[i]);
        };

        if (this.__buttons.length == 2) {
            this.__buttons = AP.array.merge([this.__buttons[0]], buttons_tmp, [this.__buttons[1]]);
        } else if(this.__buttons.length == 0) {
            this.__buttons = buttons_tmp;
        }else {
            this.__buttons = AP.array.merge([this.__buttons[0]], buttons_tmp);
        }
        return this;
    }

    function bindEvents($that) {
        $("#offcanvas-flip").show();
        setTimeout(function () {
            $("#offcanvas-flip").addClass("uk-offcanvas-overlay uk-open");
            $("#offcanvas-flip").find(".uk-offcanvas-bar").addClass("uk-offcanvas-bar-animation uk-offcanvas-slide");
        });

        $("#offcanvas-flip .header .uk-offcanvas-close").click(function (e) {
            e.stopPropagation();
            closeOffcanvas();
        });

        $("#offcanvas-flip .footer .core-form-button").each(function (index) {
            var btn = $that.getButton(index);
            $(this).data("action", btn.action);
            $(this).click(function () {
                if (AP.data.isFunction(btn.validator)) {
                    var result = btn.validator.apply();
                    if (result.code == 0) {
                        AP.alertError(result.message);
                        return;
                    }
                }
                var action = $(this).data("action");
                action(this);
                }
            );
        });
    }

    this.getButton = function (index) {
        return this.__buttons[index];
    }

    function closeOffcanvas() {
        $("#offcanvas-flip").removeClass("uk-offcanvas-overlay uk-open");

        setTimeout(function () {
            $("#offcanvas-flip").find(".uk-offcanvas-bar").removeClass("uk-offcanvas-bar-animation uk-offcanvas-slide");
            $("#offcanvas-flip").hide();
        });

        $("#offcanvas-flip .header .core-form-button").unbind("click");
        $("#offcanvas-flip .header .close").unbind("click");
    }

    this.closeOffcanvasManually = function() {
        closeOffcanvas();
    }

    this.renderFooter = function () {
        var html = "";
        for (var i = 0; i < this.__buttons.length; i++) {
            html += this.renderButton(this.__buttons[i]);
        }
        return html;
    }

    this.renderButton = function (button) {
        var id = '';
        if (typeof button.id !== 'undefined') {
            id = " id='"+(button.id)+"'";
        }
        return "<div class='core-form-button "+(button.style)+"'"+(id)+">"+(button.label)+"</div>";
    }

    this.findName = function(name) {
        return $("*[name='"+name+"']", "#"+this.__id);
    }

    this.findClass = function(className) {
        return $("." + className, "#"+this.__id);
    }
}



Render.on("menu-section", function(){
    if (!Render.acl(this)){
        return '';
    }

    var title='';
    if (this.title){
        title="<div class='ms-title'>"+(this.title)+"</div>";
    }

    return "<div class='menu-section'>"+(title)+""+(this.content)+"</div>";
});




Render.on("files", function(){
	var cx = this.get('class');
	if (!this.files || !this.files.length){
		this.addClass("-no-files");
	}
	
	if (!this.files || !this.files.length){
        return "<div class='core-list-files -empty'> " +Render.render('empty', {icon: "document" , sm:1}, ""+(this.es|| __('No files to show'))+"")+ "</div> ";
    }

    if (this.list){
        var files=AP.render(this.files, function(e){
            return Render.helper.getFile(e);
        });
        
        return "  " +Render.render('list', {_class: "core-list-files "+(cx)+"" , style:this.style, borderless:this.borderless||''}, ""+(files)+"")+ '';	
    }
    
    var files=AP.render(this.files, function(e){
        return Render.helper.getEmbededFile(e);
    });
    return "<div class='core-files display-files "+(cx)+"' "+(this.css())+">"+(files)+"</div>";
});

Render.helper.getFile = function(e){
	var ficon = UI.file.icon(e.url); 
	return "  " +Render.render('list_item', {avatar:1}, '' +Render.render('icon', {icon:SVG[ficon], xl:1}, '')+ " " +Render.render('text_title', {style: "margin-right:16px" }, "<span class='core-url' data-url=':file' data-file='"+(e.url)+"'>"+(e.name)+"</span>")+ " " +Render.render('info', {}, ""+(UI.file.kb(e.size))+" &middot; " +Render.render('text_datetime', {}, ""+(e.since)+"")+ '')+ " " +Render.render('side', {}, '' +Render.render('action', {dd:1}, '' +Render.render('cmenu', {}, '' +Render.render('cmenu_item', {url:Core.file.download(e.name, e.url)}, ""+(__('Download'))+"")+ " " +Render.render('cmenu_item', {url: ":file" , data_file:e.url}, ""+(__('View in popup'))+"")+ '')+ '')+ '')+ '')+ '';
};

Render.helper.getEmbededFile = function(e){
	return "<div class='file'> <div class='fileheader'> <div class='name'>"+(e.name)+"</div> <div class='info'>"+(UI.file.kb(e.size))+" &middot; @"+(e.username)+"</div> " +Render.render('actions', {}, '' +Render.render('action', {url:Core.file.download(e.name, e.fid)}, ""+(__('Download'))+"")+ " " +Render.render('action', {more:1}, '' +Render.render('cmenu', {}, '' +Render.render('cmenu_item', {url:Core.file.download(e.name, e.fid)}, ""+(__('Download'))+"")+ " " +Render.render('cmenu_item', {url: ":file" , data_file:e.url}, ""+(__('View in popup'))+"")+ '')+ '')+ '')+ "</div> <div class='filedisplay'>"+(Core.file.getHTML(e.url))+"</div> </div>";
};


Render.ui.logUI = new function __RULogUI(){
	this.showChanges = function(ref){
		var changes = $(ref).closest(".js-core-log").data("changes");

		var rows = AP.render(changes, function(c){
			return " " +Render.render('table_row', {}, '' +Render.render('cell', {}, ""+(c.k)+"")+ " " +Render.render('cell', {}, ""+(c.o)+"")+ " " +Render.render('cell', {}, ""+(c.n)+"")+ '')+ "";
		});

		var html = " " +Render.render('table', {padding:1, celled:1}, '' +Render.render('table_header', {full:1}, '' +Render.render('table_row', {}, '' +Render.render('cell', {label:__('Key'), head:1}, ""+(__('Key'))+"")+ " " +Render.render('cell', {label:__('Old value'), head:1}, ""+(__('Old value'))+"")+ " " +Render.render('cell', {label:__('New value'), head:1}, ""+(__('New value'))+"")+ '')+ '')+ " " +Render.render('table_body', {}, ""+(rows)+"")+ '')+ "";

		return "  " +Render.render('dialog', {width: "500" , title:__('Changed values')}, ""+(html)+"")+ '';
	};
};


Render.on("logs", function(){
	var that = this;
	var logs = AP.render(this.logs, function(log){
		return "  " +Render.render('log', {compact:that.compact||0, log:log}, '')+ '';
	});

	return "<div class='core-logs' "+(this.show('id'))+">"+(logs)+"</div>";

}, function(params, obj){
	if (params.limit){
		$(this).shortlist({
			max: params.limit
		});
	}
});

Render.on("logs-group", function() {
    var groups = AP.array.groupDate(this.logs);
    var html = '';

    for (var time in groups) {
        var group_logs = groups[time];
        if (group_logs.length == 0) {
            continue;
        }
        html += "<span class='core-logs-time'>"+(time)+"</span>";
        html += "<div class='group-date'>";
        for (var j=0; j < group_logs.length; j++) {
            html += "  " +Render.render('log_group', {log:group_logs[j]}, '')+ '';
        }
        html += '</div>';
    }

    return "<div class='core-logs-group' "+(this.show('id'))+" "+(this.css())+">"+(html)+"</div>";
});

Render.on("log-group", function() {
    var msg = this.log.message || '';
    var change = '';
    var icon = '';
    var link = '';
    var url = '';
    if (this.log.data && this.log.data.url){
        link = " &middot; <em class='core-url' data-blank='1' data-url='"+(this.log.data.url)+"'>"+(__('View'))+"</em>";
        url = this.log.data.url;
    }

    if (this.log.changes && this.log.changes.length > 0){
        change = "&middot; <span class='url' onclick='Render.ui.logUIGroup.showChanges(this);'>"+(__('View changes'))+"</span>";
    }
    if (this.log.data && this.log.data.name_icon){
        icon = "  " +Render.render('iconbox', {icon:this.log.data.name_icon, color:this.log.data.color_icon||'main', edge: "3" , el:1}, '')+ '';
        color = this.log.data.color_icon;

        if (this.log.data.icon_fill){
            color = this.log.data.icon_fill;
            icon = "  " +Render.render('iconbox', {icon:this.log.data.name_icon, color:this.log.data.icon_fill||'main', el:1, solid:1}, '')+ '';
        }
    } else{
        icon = "  " +Render.render('iconbox', {icon: "update_obj" , color: "main" , edge: "3" , el:1}, '')+ '';
    }

    return "<div class='core-log-group js-core-log "+(this.get('class'))+"' "+(this.css())+" "+(this.show('id'))+"> <div class='core-log-icon'>"+(icon)+"</div> <div class='-bl-message'>"+(msg)+"</div> <div class='-bl-info'> " +Render.render('text_datetime', {ts:this.log.since}, '')+ ""+(link)+" "+(change)+" </div> </div> ";
}, function(params, obj){
    $(this).data("changes", obj.log.changes);
});

Render.on("log", function(){
	var date = AP.i18n.date(this.log.since);
	if (this.compact){
		date = AP.time.time("%d/%m<em>%Y</em>", this.log.since);
	}

	if (AP.time.sameYear(this.log.since, AP.time.now()) && 1==2){
		date = AP.time.time("%V, %d/%m", this.log.since);
		if (this.compact){
			date = AP.time.time("%d/%m", this.log.since);
		}
	}

	var icon = '';
	var color = '';

	if (this.log.data && this.log.data.name_icon){
		icon = "  " +Render.render('iconbox', {icon:this.log.data.name_icon, color:this.log.data.color_icon||'main', edge: "3" , el:1}, '')+ '';
		color = this.log.data.color_icon;

		if (this.log.data.icon_fill){
			color = this.log.data.icon_fill;
			icon = "  " +Render.render('iconbox', {icon:this.log.data.name_icon, color:this.log.data.icon_fill||'main', el:1, solid:1}, '')+ '';
		}
	} else{
		this.addClass("-no-icon");
	}

	var link = '';
	var url = '';
	if (this.log.data && this.log.data.url){
		link = " &middot; <em class='core-url' data-blank='1' data-url='"+(this.log.data.url)+"'>"+(__('View'))+"</em>";
		url = this.log.data.url;
	}

	var msg = this.log.message || '';
	var change = '';

	if (this.log.changes && this.log.changes.length > 0){
		change = " &middot; <span class='core-url' onclick='Render.ui.logUI.showChanges(this);'>"+(__('View changes'))+"</span>";
	}

	var since = " &middot; " +Render.render('text_datetime', {}, ""+(this.log.since)+"")+ '';
	if (this.compact){
		since = '';
		this.addClass("-compact");
	}

	return "<div class='core-log js-core-log "+(this.get('class'))+"' "+(this.show('id'))+"> <div class='-bl-date'>"+(date)+"</div> <div class='-bl-dot'></div> <div class='-bl-icon'> "+(icon)+" </div> <div class='-bl-message'> <div>"+(msg)+"</div> </div> <div class='-bl-info'> " +Render.render('special_tag', {color:color, edge:1, subtle:1, sm:1}, ""+(this.log.event)+"")+ " &nbsp; "+(since)+" "+(change)+" "+(link)+" </div> </div>";
}, function(params, obj){
	$(this).data("changes", obj.log.changes);
});



Render.on("dialog", function(){
	var header = '';
	if (this.title){
		header = "<div class='core-bd-header "+((this.title_fill||this.fill_title)?' -fill':'')+"'> <div class='core-bd-title'>"+(this.title)+"</div> <div class='core-bd-close' onclick=\"AP.hideCustomDialog('#"+(this.id)+"', true)\"><span class='-icon-svg'>"+(SVG.close)+"</span></div> </div>";
	}

	if (this.gray){
		this.addClass('-gray');
	}

	if (this.fit){
		this.addClass("-fit");
	}

	var w = this.width||800;

	var content = "<div class='core-baseui-dialog "+(this.get('class'))+"' style='width:"+(w)+"px'> "+(header)+" <div class='core-bd-body core-js-dx-body'>"+(this.content)+"</div> </div> ";

	AP.customDialog(content, {
		id: this.id,
		closable: false,
		fs: 1
	}).addClass("-baseui-fit").addClass(this.get('class')).show();


	var id = this.id;
	setTimeout(function(){
		AP.balanceDialog(id);
	});

	return "";
});


